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_pie
the percentage value is computed byecharts
under the hood and added as an attribute to theparams
object (Put differently: There is no need to compute the percentage value manually for a pie chart and actually thepercent
column of your data is not used). But this is not the case fore_bar
. Hence,params.percent
isundefined
as there is not attribute with namepercent
.However, one possible hack would be to pass the
percent
value via thebind
parameter which is then stored in thename
attribute, whereas the category value mapped onx
can be retrieved from thevalue
array, i.e.value[0]
: