You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何旋转geom_histogram中每个柱子顶部的计数标签

解决方案

修改核心逻辑如下:

  • 给stat_bin补充和geom_histogram完全一致的分箱参数boundary = 0、binwidth = 5,避免分箱规则不一致导致标签和柱子错位
  • 文本旋转90度后对齐方向会互换,将原有对齐参数替换为hjust = 0、vjust = 0.5:hjust=0保证文本底部紧贴柱子顶端,vjust=0.5保证文本在柱子宽度方向居中。如果需要调整标签和柱子的间距,可适当调低hjust的数值(比如设置为-0.2即可增加空隙)

修改后完整代码如下:

library(ggplot2)
set.seed(123) # 固定随机种子方便结果复现
ex_tfdp = data.frame(x=rnorm(1000,10,10))

ggplot(ex_tfdp) +
  geom_histogram(aes(x = x), boundary = 0, binwidth = 5, color="black", fill="#FFC857") +
  stat_bin(geom="text", colour="black", size=3.5,
           aes(x = x, label=..count..), 
           boundary = 0, binwidth = 5,
           angle = 90, hjust = 0, vjust = 0.5) +
  theme(axis.text.x = element_text(angle = 90, hjust = .5),
        panel.background = element_blank(),
        legend.position="bottom",
        legend.title=element_blank(),
        axis.ticks.y=element_blank())

如果使用3.0.0及以上版本的ggplot2,推荐将..count..替换为更规范的after_stat(count),避免语法过时问题。

内容的提问来源于stack exchange,提问作者DR15

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 16:06:07