Search code examples
recharts4r

Displaying multiple extra variables in tooltips


I want to show multiple variables in the tooltip that are in the data but not used to create the echarts. I tried the e_add as suggested here, but I cannot get it to work with trigger = "axis".

My goal is to create a tooltip that triggers using "axis" and shows

  1. The x-Axis value
  2. Below the y-values for each group with its distinct color
  3. After a <hr> the additional variables "c" and "d"

MWE:

library(echarts4r)
set.seed(1234)
df <- tibble(
  a = as.factor(1:10),
  b = runif(10),
  dummy = rep(c("Group 1", "Group 2"),5),
  c = LETTERS[1:10],
  d = LETTERS[2:11]
)
df |> 
  dplyr::group_by(dummy) |> 
  e_chart(a) |> 
  e_line(b) |> 
  e_add_nested('extra', c) |> 
  e_add_nested('extra2', d) |>
  e_tooltip(
    trigger = "item",
    formatter = htmlwidgets::JS(
      'function(params){
        return "<span> <b>First Letter: " + params.data.extra.c + "<br> <b>Second Letter: " + params.data.extra2.d + "</span>";
      }'
    )
  )

Solution

  • When you use trigger='axis' you are no longer dealing with one item or series. Instead params is an array of objects in that case, which in general contains one object per series. Hence, in the general case you have to loop over the array to extract the information you want to show in the tooltip. However, for the special case of your example data the array is of length 1 as only group or series is present per x axis category. In that case you could simply use params[0] to access the first or single element of the array.

    library(echarts4r)
    set.seed(1234)
    df <- tibble(
      a = as.factor(1:10),
      b = runif(10),
      dummy = rep(c("Group 1", "Group 2"), 5),
      c = LETTERS[1:10],
      d = LETTERS[2:11]
    )
    df |>
      dplyr::group_by(dummy) |>
      e_chart(a) |>
      e_line(b) |>
      e_add_nested("extra", c) |>
      e_add_nested("extra2", d) |>
      e_tooltip(
        trigger = "axis",
        formatter = htmlwidgets::JS(
          'function(params){
            params = params[0]
            return "<span> <b>First Letter: " + params.data.extra.c + "<br> <b>Second Letter: " + params.data.extra2.d + "</span>";
          }'
        )
      )
    

    enter image description here