ggplot绘制百分比直方图添加标签后y轴刻度异常如何解决
问题原因
- ggplot2的图层默认会自动扩展坐标系范围以适配所有图层的取值范围,你只给
geom_histogram层指定了百分比格式的y轴映射,stat_bin层没有显式指定y轴映射时,默认使用统计计算得到的原始计数count作为y值,导致y轴范围被原始计数的大数值撑开,最终出现y轴刻度异常(比如显示为百分之几百、几千)的问题。 - 额外优化点:两份图层重复定义
binwidth参数,后续维护容易出现参数不一致的问题。
修复方法
给stat_bin层补充和直方图层一致的y轴百分比映射即可,也可以将公共参数提到全局映射中简化代码:
# 兼容旧版ggplot2的写法 data_impact_final %>% ggplot(aes(x = time_to_treat_month, y = ..count../sum(..count..))) + geom_histogram(binwidth = 6) + stat_bin( binwidth = 6, geom = "text", color = "white", aes(label = scales::percent(..count../sum(..count..))), position = position_stack(vjust = 0.5) ) + scale_y_continuous(labels = scales::percent)
如果你使用的是ggplot2 3.4.0及以上版本,更推荐使用官方推荐的after_stat()语法替代已被废弃的..count..双点写法:
# 新版ggplot2推荐写法 data_impact_final %>% ggplot(aes(x = time_to_treat_month, y = after_stat(count / sum(count)))) + geom_histogram(binwidth = 6) + stat_bin( binwidth = 6, geom = "text", color = "white", aes(label = scales::percent(after_stat(count / sum(count)))), position = position_stack(vjust = 0.5) ) + scale_y_continuous(labels = scales::percent)
内容的提问来源于stack exchange,提问作者KateS
相关产品推荐
相关产品推荐

