如何在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
相关产品推荐
相关产品推荐

