我使用 echarts4R 创建了带有预测部分的图表,但工具提示似乎并不准确 - “上限”的标签似乎停留在一个值上,并且不会像我将鼠标悬停在其他值上时那样发生变化数据点。知道这是为什么吗?
下面是一个可重现的示例:
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))
问题在于,上限显示的值是上限和下限之间的差值,根据您的数据,该差值等于恒定值 28680。
根据这篇文章修复工具提示需要自定义 JS 格式化程序。自定义格式化程序的一个优点是它允许对工具提示进行一些进一步的自定义,例如在下面的代码中,我从工具提示中删除了所有缺失的值:
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))