ggplot堆叠百分比条形图N标签的图外定位问题
ggplot2堆叠百分比条形图N标签位置修正方案
问题原因
原代码中给N标签使用position_dodge(width = 1)是错误的——每个Category对应一个完整的堆叠条形,不存在分组偏移的需求,这个参数会导致标签偏离条形正上方;同时默认y轴范围是0-1,标签设置vjust=-0.5会超出绘图区域,导致显示不全或错位。
修正方案(标签放条形顶部外)
修改后的完整代码如下:
png(file="mock.png", h=1400 , w=1400, unit="px") ggplot(df, aes(x=Category, y=value, fill = variable)) + theme(text = element_text(size = 50), axis.text.x = element_text(angle = 45, hjust = 1)) + geom_bar(position = "fill", stat = "identity", color='black', width=0.9) + # 扩展y轴上方空间,让N标签能显示在图外 scale_y_continuous(labels = scales::percent, expand = expansion(mult = c(0, 0.1))) + geom_text(aes(label = paste0(round(value*100),"%")), position = position_stack(vjust = 0.5), size = 5) + # 去掉position_dodge,指定y=1(对应100%位置),调整vjust让标签在顶部外 geom_text(data = df_unique_counts_per_category, aes(y = 1, label = paste("N = ", total)), vjust = -0.2, size = 4) + labs(title = "Module composition (%)", y = "Percentage", x = "Module") dev.off()
可选方案(标签放X轴区域下方)
如果想把N标签放在X轴下方的图外区域,可调整如下:
png(file="mock.png", h=1400 , w=1400, unit="px") ggplot(df, aes(x=Category, y=value, fill = variable)) + theme(text = element_text(size = 50), axis.text.x = element_text(angle = 45, hjust = 1)) + geom_bar(position = "fill", stat = "identity", color='black', width=0.9) + # 扩展y轴下方空间 scale_y_continuous(labels = scales::percent, expand = expansion(mult = c(0.1, 0))) + geom_text(aes(label = paste0(round(value*100),"%")), position = position_stack(vjust = 0.5), size = 5) + # 设置y=0,vjust=1.2把标签移到X轴下方 geom_text(data = df_unique_counts_per_category, aes(y = 0, label = paste("N = ", total)), vjust = 1.2, size = 4) + labs(title = "Module composition (%)", y = "Percentage", x = "Module") dev.off()
关键修改点
- 移除
position_dodge:每个Category只有一个堆叠条形,不需要分组偏移,确保标签对齐条形正上方/下方 - 扩展y轴范围:通过
scale_y_continuous的expand参数增加上下边距,避免标签被裁剪 - 明确y值与vjust:设置y=1(顶部)或y=0(底部),配合vjust调整标签相对于条形的位置,确保在图外显示
内容的提问来源于stack exchange,提问作者Rodrigo Duarte
相关产品推荐
相关产品推荐

