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

如何在gghistogram分组直方图的柱形顶部添加计数数值?

问题:为分组直方图添加柱顶计数标签

我已基于以下数据集绘制了不同年龄组的直方图:

> dput(Agedata[1:20,])

structure(list(samples = c("Pt1", "Pt10", "Pt101", "Pt103", "Pt106", 
"Pt11", "Pt17", "Pt18", "Pt2", "Pt24", "Pt26", "Pt27", "Pt28", 
"Pt29", "Pt3", "Pt30", "Pt31", "Pt34", "Pt36", "Pt37"), resp = c("NoResponse", 
"NoResponse", "Response", "NoResponse", "NoResponse", "NoResponse", 
"NoResponse", "Response", "NoResponse", "NoResponse", "NoResponse", 
"NoResponse", "NoResponse", "NoResponse", "Response", "Response", 
"NoResponse", "Response", "NoResponse", "NoResponse"), age = c(58, 
53, 61, 57, 57, 62, 51, 59, 58, 60, 61, 49, 52, 57, 61, 61, 60, 
56, 55, 61), age_group = structure(c(6L, 6L, 7L, 6L, 6L, 7L, 
6L, 6L, 6L, 7L, 7L, 5L, 6L, 6L, 7L, 7L, 7L, 6L, 6L, 7L), levels = c("0-9", 
"10-19", "20-29", "30-39", "40-49", "50-59", "60-69", "70-79", 
"80-89", "90-99"), class = "factor")), row.names = c(NA, 20L), class = "data.frame")

使用的绘图代码如下:

library(ggpubr)

gghistogram(Agedata, x = "age_group", bins = 8,
            rug = TRUE,
            color = "resp", fill = "resp", stat = 'count',
            palette = c("red", "green"), main = 'Age ~ Outcome') + ylim(c(0,500)) + theme_bw()

现需为该直方图的每个柱形(包括红色NoResponse组和绿色Response组)顶部添加对应的计数数值,请问该如何实现?


解决方案

你可以通过在现有绘图代码后添加geom_text()层来实现,利用stat='count'获取每个柱形的计数,并将其作为标签显示在柱顶。具体修改后的代码如下:

library(ggpubr)

gghistogram(Agedata, x = "age_group", bins = 8,
            rug = TRUE,
            color = "resp", fill = "resp", stat = 'count',
            palette = c("red", "green"), main = 'Age ~ Outcome') +
  # 添加柱顶计数标签
  geom_text(stat='count', aes(label=..count.., color=resp), 
            vjust=-0.5, size=4) +  # vjust控制标签向上偏移,避免和柱顶重叠
  ylim(c(0, 520)) +  # 扩大y轴上限,防止标签被截断
  theme_bw()

代码说明:

  • geom_text(stat='count', aes(label=..count.., color=resp)):指定使用计数统计逻辑,将柱形对应的计数数值作为显示标签,同时让标签颜色和分组(resp)保持一致,提升区分度。
  • vjust=-0.5:调整标签的垂直位置,使其向上偏移柱顶,避免重叠,数值可根据实际显示效果微调。
  • 调整ylim上限到520:原y轴上限500会导致顶部标签被截断,适当扩大范围预留显示空间。

另外,也可以使用ggpubr自带的add_text()函数,实现效果一致:

gghistogram(Agedata, x = "age_group", bins = 8,
            rug = TRUE,
            color = "resp", fill = "resp", stat = 'count',
            palette = c("red", "green"), main = 'Age ~ Outcome') +
  add_text(stat='count', aes(label=..count.., color=resp), vjust=-0.5) +
  ylim(c(0,520)) +
  theme_bw()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:05:28