如何为ggplot2直方图的每个柱形添加标签并解决绘图异常问题
解决方案
核心问题原因
geom_histogram和stat_bin两个图层的分箱参数不匹配:直方图配置了boundary = 9的分箱边界规则,但文本标签图层未同步该参数,导致分箱错位出现柱形堆叠异常- 文本标签图层未指定y轴映射,导致图层额外执行冗余计算,大幅拉长绘图耗时
修正后代码
library(ggplot2) library(scales) df_2 %>% ggplot(aes(x = day_difference)) + geom_histogram( aes(y = stat(count)/sum(stat(count))), color = "darkblue", fill = "deepskyblue2", binwidth = 10, boundary = 9 ) + stat_bin( binwidth = 10, boundary = 9, # 同步分箱边界参数 geom = "text", colour = "black", size = 3.5, vjust = -0.3, # 标签上移避免与柱形顶部重叠 aes( y = stat(count)/sum(stat(count)), # 同步y轴映射规则 label = percent(stat(count)/sum(stat(count)), accuracy = 1) # 直接生成整数百分比标签 ) ) + scale_x_continuous(breaks = breaks_width(10)) + scale_y_continuous(labels = percent, breaks = breaks_width(0.1)) + labs(x = "difference (days)", y = "占比", title = "Difference between first and second invitations (2021)") + theme_bw()
可选优化
如果调整后仍存在柱形全部集中在左侧的问题,说明day_difference字段存在离群极大值,可通过xlim()限制x轴显示范围,例如仅展示0-100天的分布,添加xlim(0, 100)到绘图代码中即可。
如果数据量超过10万行,可提前用dplyr完成分箱汇总后再用geom_col绘图,进一步降低计算耗时。
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

