ggplot2:在百分比条形图顶部添加绝对数值标签报错求助
解决堆叠百分比条形图顶部显示绝对总计数的问题
核心问题是stat='summary'仅会对绘图时指定的y变量(此处为百分比freq)进行汇总,无法直接调用conteo列。解决思路是提前计算每个codigo组的总计数,再在绘图时直接调用该数值。
方法一:在现有数据集新增总计数列
先通过dplyr给vgene_group添加每组的总计数列,之后直接在绘图时映射该列作为文本标签:
library(dplyr) library(ggplot2) # 给vgene_group新增每组的总计数列 vgene_group <- vgene_group %>% group_by(codigo) %>% mutate(total_conteo = sum(conteo)) %>% ungroup() # 绘制堆叠百分比条形图并添加顶部总计数 ggplot(vgene_group, aes(x = codigo, y = freq, fill = vgene)) + geom_bar(stat = "identity", position = "fill") + # 放置顶部总计数,y=1对应百分比堆叠的顶部(100%) geom_text(aes(y = 1, label = total_conteo), stat = "identity", position = position_fill(vjust = 1.05), # 调整文本位置避免重叠 size = 4) + scale_y_continuous(labels = scales::percent_format()) + labs(x = "Codigo", y = "百分比", fill = "Vgene") + theme_minimal()
方法二:单独创建总计数汇总数据集
如果不想修改原数据集,可单独生成仅包含codigo和对应总计数的数据集,绘图时指定该数据集给geom_text:
# 单独生成总计数汇总表 total_df <- vgene_group %>% group_by(codigo) %>% summarise(total_conteo = sum(conteo)) %>% ungroup() # 绘图 ggplot(vgene_group, aes(x = codigo, y = freq, fill = vgene)) + geom_bar(stat = "identity", position = "fill") + # 使用单独的总计数数据集添加文本 geom_text(data = total_df, aes(x = codigo, y = 1, label = total_conteo), position = position_nudge(y = 0.02), # 向上微调位置 size = 4) + scale_y_continuous(labels = scales::percent_format()) + labs(x = "Codigo", y = "百分比", fill = "Vgene") + theme_minimal()
报错原因说明
使用geom_text(stat='summary')时,该统计变换仅会处理绘图中指定的y变量(即freq),不会自动识别conteo列,因此after_stat(conteo)会提示找不到对象。提前计算总计数后,直接通过原始数据或汇总数据映射标签,就能绕过这个限制,正确显示绝对数值。
内容的提问来源于stack exchange,提问作者Gerald Vasquez Aleman
相关产品推荐
相关产品推荐

