Search code examples
rechartsecharts4r

How to extract y-axis value by group in echarts tooltip formatter


I'd like to reference the y-axis value for each group in the custom formatting function:

library(echarts4r)

# Example data
data <- data.frame(
  category = c("A", "B", "C", "D", "E"),
  value1 = c(10, 15, 20, 25, 30),
  value2 = c(12, 18, 22, 28, 35)
)

# define formatter function
formatter <- htmlwidgets::JS(
  "
   function(params) {
      var tooltipContent = '<b>Category:</b> ' + params[0].axisValue + '<br/>';
  
      params.forEach(function(item) {
        var groupName = item.seriesName;
        var groupValue = 1;
        var groupColor = item.color;
        
        tooltipContent += '<div style=\"display: inline-block; width: 10px; height: 10px; margin-right: 5px; background-color: ' + groupColor + '\"></div>' +
                          '<b>' + groupName + ':</b> ' + groupValue + '<br/>';
      });
      
      return tooltipContent;
    }
  "
)

# Create the echart
data |>
  e_charts(category) |>
  e_line(value1, name = "Group 1") |>
  e_line(value2, name = "Group 2") |>
  e_y_axis(name = "Value") |>
  e_x_axis(name = "Category") |>
  e_tooltip(trigger = "axis", axisPointer = list(type = "cross"), formatter = formatter)

In particular, how can I replace var groupValue = 1; to reference the y-axis value for each group?


Solution

  • To get the y-axis value of the group, with your variables, and taking into account that your js data is structured as an array of arrays (from an R list of lists through echarts4r using ToListExplicit), you should use:

    var groupValue = item.value[item.encode.y[0]];
    

    The reference is here, go to 2. Callback function and then "When the dataset is like" ... "We can get the value of the y-axis via" ... (unfortunately, there are no linkable ids in the whole long text). Your item variable stands for params - the object of parameters for each dataset.