如何修改ggplotly柱状图悬浮提示框以显示Total Crashes求和值
问题描述
我使用ggplot搭配ggplotly()渲染堆叠柱状图,图表渲染效果符合预期:可按Mode Type、Crash Year两个维度展示Total Crashes的分组求和值。
但存在明确异常:悬浮提示框仅显示原始记录值“1”,无法展示对应分组的Total Crashes求和结果。
需要调整代码,让提示框展示对应分组的实际总和,而非单条记录的数值1。
最初使用的绘图代码
crashplot <- ggplot(totcrashes_by_year, aes(totcrashes_by_year$`Crash Year`, totcrashes_by_year$`Total Crashes`)) crashplot + geom_bar( stat = "identity", aes(fill = totcrashes_by_year$`Mode Type`), position = "stack" ) + xlab("Crash Year") + ylab("Total Crashes") + ggtitle("Total Crashes by Year and Mode Type") + labs(fill = "Mode Type")
补充说明:附可复现问题的最小代码示例
首先构造测试数据集:
crashsample <- data.frame( year = sample(2007:2018, 40, replace = TRUE), crashes = 1, type = sample(c('Vehicle', 'Pedestrian', 'Bike', 'Motorcycle'), 40, replace = TRUE) )
创建ggplot静态图表
crashplot <- ggplot(crashsample, aes(x = year, y = crashes, fill = type)) + geom_bar(stat = "identity") + labs( x = 'Crash Year', y = 'Total Crashes', title = "Total Crashes by Year and Mode Type", fill = "Mode Type" ) # 调用ggplotly转换为交互式图表 ggplotly(crashplot)
异常原因
逐行记录的原始数据中,每条样本的crashes值为1。geom_bar(stat="identity")绘制堆叠柱时,会自动对同分组下的y值累加得到柱子的实际高度,但默认的悬浮提示会绑定原始逐行的y值,不会自动读取累加后的分组结果,因此提示框始终显示原始值1。
调整方案
方案1:提前做数据分组聚合(最稳妥)
先对原始数据按year + type维度分组,计算每个组合的崩溃数总和,从根源上避免逐行数据导致的取值错位,再显式指定悬浮提示要展示的数值字段。
完整可运行代码:
# 加载依赖包 library(dplyr) library(ggplot2) library(plotly) # 分组聚合计算每个维度组合的崩溃总和 crash_agg <- crashsample %>% group_by(year, type) %>% summarise(total_crashes = sum(crashes), .groups = "drop") # 基于聚合数据绘图,手动映射悬浮展示的数值 crashplot_adj <- ggplot(crash_agg, aes(x = year, y = total_crashes, fill = type)) + geom_bar(stat = "identity", aes(label = total_crashes)) + labs( x = 'Crash Year', y = 'Total Crashes', title = "Total Crashes by Year and Mode Type", fill = "Mode Type" ) # 渲染交互式图表,指定提示框展示的字段 ggplotly(crashplot_adj, tooltip = c("x", "fill", "label"))
方案2:不提前聚合,直接绑定柱子高度值
如果不想提前处理原始数据,可直接在geom_bar的美学映射中,将悬浮展示的字段绑定为柱子的最终高度值,不需要改动原始数据结构。
完整可运行代码:
crashplot_adj2 <- ggplot(crashsample, aes(x = year, y = crashes, fill = type)) + geom_bar( stat = "identity", aes(label = after_stat(y)) # 绑定柱子实际高度值作为悬浮展示内容 ) + labs( x = 'Crash Year', y = 'Total Crashes', title = "Total Crashes by Year and Mode Type", fill = "Mode Type" ) ggplotly(crashplot_adj2, tooltip = c("x", "fill", "label"))
调整完成后,悬浮提示框会准确展示每个柱子段对应的Total Crashes分组总和,不会再出现原始值1。
内容的提问来源于stack exchange,提问作者myClone
相关产品推荐
相关产品推荐

