R语言highcharter:如何在提示框中添加Y轴数值总和
在Highcharter提示框中添加Y轴数值总和的解决方案
嘿,我来帮你搞定这个tooltip显示Y轴数值总和的问题!你现在的思路是对的,但footerFormat里直接用sum(point.y)的写法不符合Highcharts的语法规则,咱们得用JavaScript来计算总和才行。
问题分析
你已经正确完成了数据聚合:
library(gapminder) library(highcharter) ga <- gapminder %>% group_by(year, continent) %>% summarise(pop = sum(pop))
但在hc_tooltip里,Highcharts的格式化规则需要用JS逻辑来遍历当前显示的所有点,计算它们的Y值总和,而不是直接用R的函数语法。
修改后的完整代码
hchart(ga, "line", hcaes(x = year, y = pop, group = continent)) %>% hc_tooltip( shared = TRUE, sort = TRUE, formatter = JS("function() { // 初始化总和变量 var totalPopulation = 0; // 遍历当前提示框中的所有点,累加Y值 this.points.forEach(function(point) { totalPopulation += point.y; }); // 保留默认的提示框内容,再追加总和行 var defaultTooltip = this.defaultFormatter.call(this, this); return defaultTooltip + '<br/><b>Total Population: </b>' + Highcharts.numberFormat(totalPopulation, 0); }") )
代码说明
- 用
JS()函数包裹JavaScript代码,这是Highcharter调用Highcharts原生API的方式 this.points包含了当前共享提示框内的所有数据点,我们遍历它来计算总和this.defaultFormatter.call(this, this)保留了原来的提示框样式和内容,避免重新写所有格式化逻辑Highcharts.numberFormat(totalPopulation, 0)把总和格式化为整数,让显示更友好
这样修改后,当你hover到图表上的年份时,提示框底部就会显示所有大洲的人口总和啦!
内容的提问来源于stack exchange,提问作者nadjib amrouche
相关产品推荐
相关产品推荐

