Changing tooltip for markLine using echarts4r

35 Views Asked by At

I want to change the tooltip content for lines drawn using echarts4r::e_mark_line() without changing existing series' names. I also want the tooltip content for other elements in the chart to remain the same. By default, the lines inherit the series name in the tooltip. I want to change this to something else.

Here is an example where the tooltip for the line shows "y" for the name of the series.

data.frame(x = c("a"), y = c(5)) |> 
  echarts4r::e_charts(x = x) |> 
  echarts4r::e_bar(serie = y) |> 
  echarts4r::e_mark_line(
    data = list(
      yAxis = 3
    )
  ) |> 
  echarts4r::e_tooltip()

bar chart with marked line and default tooltip

1

There are 1 best solutions below

0
Giovanni Colitti On

I was able to achieve the result I was looking for by passing a custom formatter function that alters the tooltip for the markLine component and reconstructs the default tooltip for the bar:

data.frame(x = c("a"), y = c(5)) |> 
  echarts4r::e_charts(x = x) |> 
  echarts4r::e_bar(serie = y) |> 
  echarts4r::e_mark_line(
    data = list(
      yAxis = 3
    )
  ) |> 
  echarts4r::e_tooltip(formatter = htmlwidgets::JS(
    'function(params) {
      // Check if the tooltip corresponds to the line
      if(params.componentType === "markLine") {
        return "Custom content: " + params.value;
      } else {
        // If its not the line, use the default tooltip content
    return params.seriesName + "<br/>" + params.marker + params.name + "<span style=\'text-align: right; margin-left:20px; font-weight: bold;\'>" + params.value[1] + "</span>";
    }
}'
  ))