如何为ggplot2百分比堆叠条形图添加百分比标注?
为百分比堆叠条形图添加百分比标注
要给你的堆叠条形图添加百分比标注,核心是先计算每个分组内的占比,再用geom_text将标注放在对应堆叠位置上。以下是修改后的完整代码:
library(ggplot2) library(dplyr) library(scales) # 用于格式化百分比显示 n <- 10000 test <- data.frame(value = sample(1:3, size = n, replace = TRUE), grp = sample(c("A", "B", "C"), size = n, replace = TRUE), item = sample(c("Item1", "Item2", "Item3", "Item4", "Item5", "Item6"), size = n, replace = TRUE)) %>% mutate(value = as.factor(value)) # 先计算每个(item, grp, value)组合的百分比 test_summary <- test %>% group_by(item, grp, value) %>% summarise(count = n(), .groups = "drop") %>% group_by(item, grp) %>% mutate(percent = count / sum(count)) # 绘制带标注的堆叠条形图 test_summary %>% ggplot(aes(x = grp, y = percent, fill = value, group = value)) + geom_bar(stat = "identity", position = 'fill') + # 添加百分比标注,vjust=0.5让标签居中在堆叠块内 geom_text(aes(label = percent(percent, accuracy = 1)), position = position_fill(vjust = 0.5), size = 3) + facet_wrap(item ~., ncol = 2) + coord_flip() + scale_fill_manual(values = c("green", "yellow", "red")) + scale_y_continuous(labels = percent) # 将y轴刻度转为百分比格式
关键说明:
- 先用
group_by(item, grp, value)统计每个子组的数量,再按item, grp分组计算占比percent geom_text的position = position_fill(vjust = 0.5)确保标签垂直居中在每个堆叠块里scales::percent()用来将小数格式的占比转为带%符号的文本,accuracy=1控制保留整数百分比- 把
geom_bar的stat显式设为"identity",因为我们已经提前计算好了y值(百分比)
内容的提问来源于stack exchange,提问作者D. Studer
相关产品推荐
相关产品推荐

