In echarts4r, I am creating a tooltip that is to display both total and percentage. It works in pie or donut charts, but not in bar charts, which show undefined%. I have tried totals += params.value[1]; perc = params.value[1] / totals; in the bar chart JS function. But it does not work.
library(tidyverse)
library(echarts4r)
My_df <- data.frame(n = c(2, 4, 10),
x = c("A", "B", " C")) %>%
mutate(percent = round(n/sum(n), 2) )
- Donut chart:
My_df %>%
e_charts(x) %>%
e_pie(n, radius = c("50%", "70%")) %>%
e_tooltip(formatter = htmlwidgets::JS("
function(params){
return('<strong>' + params.name +
'</strong><br/>total: ' + params.value +
'<br />percent: ' + params.percent) +'%' } "))
- Bar chart:
My_df %>%
e_charts(x) %>%
e_bar(n) %>%
e_tooltip(formatter = htmlwidgets::JS("
function(params){
return('<strong>' + params.name +
'</strong><br/>total: ' + params.value[1] +
'<br/>percent: ' + params.percent) +'%' } "))



The difference is that for
e_piethe percentage value is computed byechartsunder the hood and added as an attribute to theparamsobject (Put differently: There is no need to compute the percentage value manually for a pie chart and actually thepercentcolumn of your data is not used). But this is not the case fore_bar. Hence,params.percentisundefinedas there is not attribute with namepercent.However, one possible hack would be to pass the
percentvalue via thebindparameter which is then stored in thenameattribute, whereas the category value mapped onxcan be retrieved from thevaluearray, i.e.value[0]: