You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为ggplot2百分比堆叠条形图添加数值总和标签?

解决堆叠比例条形图添加分组总和标签的报错问题

你遇到的报错是因为position = "fill"会把y轴转换为0-1的比例尺度,但stat="summary"计算的是原始hp的总和(连续数值),两者尺度不兼容导致的。直接预计算分组总和再绘图就能解决这个问题:

完整代码示例

library(tidyverse)

# 提前计算每个分组的hp总和
testPlot_sum <- mtcars %>% 
  select(hp, vs, gear) %>% 
  mutate(gearFactor = factor(gear)) %>% 
  # 按vs和gear分组计算hp总和
  group_by(vs, gearFactor) %>% 
  summarise(hp_sum = sum(hp), .groups = "drop")

# 绘制堆叠比例条形图并添加总和标签
ggplot(testPlot_sum, aes(x = vs, y = hp_sum, fill = gearFactor)) +
  geom_col(position = "fill") +
  # 用position_fill对齐标签到分段中间,显示预计算的总和
  geom_text(aes(label = hp_sum), 
            size = 3, colour = "white", 
            position = position_fill(vjust = 0.5)) +
  scale_y_continuous(name = "Share of Power", labels = scales::percent) +
  scale_fill_viridis_d(name = "Classification") +
  theme_minimal()

关键说明

  • 先通过group_by()和summarise()计算出每个vs-gearFactor组合的hp总和,避免在绘图时动态计算导致的尺度冲突。
  • geom_text直接使用预计算的hp_sum作为标签内容,通过position_fill(vjust=0.5)将标签定位到每个堆叠分段的垂直居中位置,完美匹配比例条形图的布局。

内容的提问来源于stack exchange,提问作者JenB

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 00:52:45