I am needing to display stackLabels on the stacked bar chart as both a total of the stack and a percent of the total. This question gives a version of the answer I am looking for, but the data var they declare at the beginning of the code is hardcoded data, whereas I will need it to be dynamic. Additionally, I have several series I am dealing with that all need to be summed together (example below just uses two). I think the main thing I am missing is how to reference associated data from JS code to sum over it? I am very unfamiliar with JS.
For the example code and plot below, I want the stackLabels to say '30(30%)' for a, '20(20%)' for b, '50(50%)' for a. (If it was a different data set of 10, 20, and 30 it would be '10(17%)' for a, '20(33%)' for b, '30(50%)' for c since the total across everything would be 60.)
library(highcharter)
library(dplyr)
df <- data.frame(z = c(20,4,6,8,25),
y = c(3,3,2,4,25),
x = c('a', 'a', 'b', 'b', 'c'))
df <- df %>% group_by(x) %>% summarize(y = sum(y), z = sum(z), total = sum(y,z))
df
highchart() %>%
hc_chart(type = 'column') %>%
hc_plotOptions(column = list(stacking = 'normal')) %>%
hc_xAxis(categories = as.factor(unique(df$x))) %>%
hc_add_series(df$y, name = 'y', stack = 'stack') %>%
hc_add_series(df$z, name = 'z', stack = 'stack') %>%
hc_yAxis(stackLabels = list(enabled = TRUE)) %>%
hc_tooltip(shared = TRUE)
Based on the linked question above, I am thinking I need to alter the code to add a loop sum, but am not sure how to finish it.
highchart() %>%
hc_chart(type = 'column') %>%
hc_plotOptions(column = list(stacking = 'normal')) %>%
hc_xAxis(categories = as.factor(unique(df$x))) %>%
hc_add_series(df$y, name = 'y', stack = 'stack') %>%
hc_add_series(df$z, name = 'z', stack = 'stack') %>%
hc_yAxis(stackLabels = list(enabled = TRUE,
formatter = JS("function() {var data = *reference to the data*;
var dataSum = 0;
for (var i=0;i < data.length;i++) {
dataSum += data[i]
}
var pcnt = (this.y / dataSum) * 100;
return Highcharts.numberFormat(pcnt) + '%';
}"))) %>%
hc_tooltip(shared = TRUE)
Please advise. Still new to stack overflow so let me know if I missed anything.