添加geom_text后ggplot坐标轴变形原因求助
问题原因与解决方案
核心问题
- 重复图层干扰渲染:同时使用
geom_bar(position="fill")和geom_col(position="fill")属于冗余操作——geom_col本身等价于geom_bar(stat="identity"),两者叠加会打乱图表的渲染逻辑。 - 文本位置参数不匹配:
geom_text用了position_dodge(.9),这是给分组并排柱状图设计的位置调整方式,但你的图表是堆叠百分比柱状图,该参数会让文本位置偏离堆叠区域,进而导致坐标轴范围异常变形。
修正后的完整代码
# 数据处理逻辑保留 C_df <- as.data.frame(C) C_df <- C_df %>% group_by(core) %>% mutate(percent_weight = paste0((round(Freq / sum(Freq),2) * 100),"%")) # 绘图部分修正 ggplot(C_df, aes(fill=condition, y=Freq, x=core)) + geom_col(colour = "black", position = "fill")+ # 仅保留一个图层,去掉重复的geom_bar theme_classic()+ scale_y_continuous(expand = c(0, 0), labels = scales::percent, labs(y="Proportion of Cohort (%)"))+ scale_fill_brewer(palette = "Pastel1")+ # 改用position_fill匹配堆叠逻辑,vjust=0.5让文本居中显示在堆叠块内 geom_text(aes(label = percent_weight), colour = "white", size = 3, position = position_fill(vjust=0.5))
额外优化建议
如果想让文本位置更精准,可以在数据处理时直接计算比例值,避免依赖图层的位置转换:
C_df <- C_df %>% group_by(core) %>% mutate( prop = Freq / sum(Freq), percent_weight = paste0(round(prop*100,2),"%") ) # 绘图时直接用计算好的比例值定位文本 ggplot(C_df, aes(fill=condition, y=Freq, x=core)) + geom_col(colour = "black", position = "fill")+ theme_classic()+ scale_y_continuous(expand = c(0, 0), labels = scales::percent, labs(y="Proportion of Cohort (%)"))+ scale_fill_brewer(palette = "Pastel1")+ geom_text(aes(y=prop, label = percent_weight), colour = "white", size = 3, position = position_fill(vjust=0.5))
内容的提问来源于stack exchange,提问作者user19846605
相关产品推荐
相关产品推荐

