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

如何在ggplot堆叠条形图中按轴因子变量显示各层级百分比

解决水平堆叠条形图组内百分比问题

方法1:直接在ggplot中计算组内百分比

无需提前处理数据,修改geom_text的计算逻辑,按x轴分组(Variable2)计算每个堆叠块的百分比:

ggplot(data, aes(x = Variable2, fill = Variable1)) +
  geom_bar(position = "fill") +
  coord_flip() +
  theme_classic() +
  geom_text(
    aes(
      label = paste0(round(after_stat(prop * 100), 1), "%"),
      group = Variable2
    ),
    stat = "count",
    size = 3,
    hjust = 0.7,
    position = position_fill(vjust = 0.5)
  )

这里利用after_stat(prop)获取position_fill计算出的组内比例,乘以100后转成百分比格式,group = Variable2确保比例是按每个x轴类别单独计算的。

方法2:预处理数据后绘图

先按x轴变量Variable2分组,计算每个Variable1在对应组内的占比,再基于处理后的数据绘图:

library(dplyr)

# 正确预处理数据:按Variable2分组计算组内占比
percentages <- data %>%
  group_by(Variable2, Variable1) %>%
  summarise(Count = n(), .groups = "drop_last") %>%
  mutate(Percentage = round((Count / sum(Count)) * 100, 1))

# 绘制堆叠条形图
ggplot(percentages, aes(x = Variable2, y = Percentage, fill = Variable1)) +
  geom_col(position = "fill") +
  scale_y_continuous(labels = scales::percent_format(scale = 1)) +
  coord_flip() +
  theme_classic() +
  geom_text(
    aes(label = paste0(Percentage, "%")),
    size = 3,
    hjust = 0.7,
    position = position_fill(vjust = 0.5)
  )

注意事项

  • 你之前的预处理代码错误地以Variable1为分组依据,导致计算的是每个Variable1内Variable2的占比,和需求方向相反。必须按x轴变量Variable2分组,才能保证每个条形的百分比总和为100%。
  • position = "fill"会自动将条形高度归一化到1(对应100%),position_fill(vjust = 0.5)能让文本居中显示在堆叠块内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:07:52