如何在ggplot的facet_wrap/facet_grid中添加百分比geom_text标签?
解决方案
首先需要按z分组计算每个y在对应组内的百分比,再将该百分比作为标签传入geom_text。以下是完整代码:
1. 加载依赖包并处理数据
library(ggplot2) library(dplyr) # 原始数据框 df = data.frame(x = rep(1:5, 3), z = rep(1:3, each = 5), y = 100:114 ) # 按z分组计算百分比,格式化为带1位小数的百分比字符串 df <- df %>% group_by(z) %>% mutate(percent = sprintf("%.1f%%", y / sum(y) * 100)) %>% ungroup()
2. 修改ggplot代码
ggplot(df) + aes(x = x, fill = x, y = y) + geom_col(position = 'dodge') + facet_wrap(~z) + geom_text(aes(label = percent), position = position_dodge(1), vjust = -1, hjust = 0.5, # 调整hjust让文字在柱子上方居中 color = 'white') + theme_dark() + scale_fill_gradient(low = 'orange', high = 'red')
补充说明
- 若不需要百分比的小数位,可将
sprintf的格式改为"%.0f%%" - 也可以使用
scales包的percent函数替代sprintf,写法为:percent(y/sum(y), accuracy = 0.1) hjust参数可根据需求调整,原代码的hjust=0会让文字偏右,改为0.5实现居中效果
内容的提问来源于stack exchange,提问作者An116
相关产品推荐
相关产品推荐

