echarts4R tooltip not updating/accurate

48 Views Asked by At

I have created the chart below with a forecast section using echarts4R, but the tooltip doesn't seem to be accurate - the label for the "Upper band" seems to be stuck on one value, and doesnt change like when I hover over other data points. Any idea why that is?

enter image description here

enter image description here

Below is a reproducible example:

dat <- data.frame(
time = as.Date(c("2015-09-01","2015-10-01","2015-11-01","2015-12-01","2016-01-01","2016-02-01",
  "2016-03-01","2016-04-01")),
Profit = c(58307.99, 54626.44,58675.40,44361.57,NA,NA,NA,NA),
Forecast = c(NA,NA,NA, 44361.57, 36500.09, 30506.53, 35241.72, 31922.28),
Lower_CI = c(NA,NA,NA, 22159.93, 22159.93, 16166.36, 20901.56, 17582.11),
Upper_CI = c(NA,NA,NA, 50840.26, 50840.26, 44846.69, 49581.89, 46262.44)
)

dat |>
  e_charts(x = time) |>
  e_line(serie = Profit) |>
  e_line(serie = Forecast) |>
  e_band(
    min = Lower_CI,
    max = Upper_CI,
    stack = "confidence-band",
    name = c("Lower bound", "Upper bound")) |>
  e_tooltip(formatter = e_tooltip_pointer_formatter("currency")) |>
  e_legend(show=FALSE) |>
  e_x_axis(time, axisPointer = list(show = TRUE))
1

There are 1 best solutions below

0
stefan On BEST ANSWER

The issue is that the value shown for the upper bound is the difference between the upper and the lower bound and according to your data this difference amounts to a constant value of 28680.

According to this post fixing the tooltip requires a custom JS formatter. An advantage of the custom formatter is that it allows for some further customization of the tooltip, e.g. in the code below I dropped all missing values from the tooltip:

library(echarts4r)

dat |>
  e_charts(x = time) |>
  e_line(serie = Profit) |>
  e_line(serie = Forecast) |>
  e_band(
    min = Lower_CI,
    max = Upper_CI,
    stack = "confidence-band",
    name = c("Lower bound", "Upper bound")
  ) |>
  e_tooltip(
    formatter = htmlwidgets::JS("
      function(params){
        let USDollar = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
            maximumFractionDigits: 0
        });
      
        let tooltip = params[0].value[0];
        let value = 0;
        for (let i = 0; i < 4; i++) {
          if (i === 3) {
            value = Number(params[2].value[1]) + Number(params[3].value[1]);
          } else {
            value = Number(params[i].value[1])
          }
          if (params[i].value[1] !== null) {
            tooltip += '<br>' + params[i].marker;
            tooltip += params[i].seriesName + ': ';
            tooltip += USDollar.format(value);
          }
        }

        return(tooltip)
      }
    ")
  ) |>
  e_legend(show = FALSE) |>
  e_x_axis(time, axisPointer = list(show = TRUE))

enter image description here