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

如何在ggplot2分组柱状图(dodged columns)的柱子上方添加文本标签?

解决分组柱状图文本标签位置错误问题

你的代码中,分组柱状图通过position = 'dodge'实现了分柱展示,但geom_text未设置对应的位置参数,导致标签无法与对应柱子对齐,也没能显示在柱子顶部。

修改后的完整代码

df <- na.omit(n[, c("matssvaedi", "teg_eign_s_i")])
counts <- df %>%
  group_by(matssvaedi, teg_eign_s_i)%>%
  summarise(count = n(), .groups = "drop") # 显式取消分组,避免dplyr版本警告

df1 <- ggplot(counts, aes(x = matssvaedi, y = count))
df1 + 
  geom_bar(aes(fill = teg_eign_s_i), stat = "identity", position = position_dodge(width = 0.9)) + 
  geom_text(aes(label = count, group = teg_eign_s_i), 
            color="black", vjust = -0.5, size = 3, 
            position = position_dodge(width = 0.9)) + # 匹配柱状图的分柱宽度
  scale_fill_brewer(palette = "Paired") + 
  theme_classic()

关键修改说明

  • 给geom_text添加position = position_dodge(width = 0.9):该宽度与geom_bar默认宽度一致,确保标签和对应柱子精准对齐
  • 调整vjust = -0.5:将标签移至柱子顶部上方,避免与柱子填充区域重叠
  • 给geom_text的aes添加group = teg_eign_s_i:保证分组逻辑与柱状图一致,避免部分ggplot版本出现警告
  • 在summarise中加入.groups = "drop":显式取消分组,消除dplyr新版本的分组提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:15:23