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

如何在ggplot2分组条形图的条形上方对齐显示均值标签?

解决ggplot2条形图均值标签显示问题

问题症结

你的代码里有几个影响效果的问题:

  • geom_text的position_dodge()未指定宽度,导致标签和对应条形错位
  • 标题的hjust=1.5设置错误,会把标题推到绘图区域外
  • 最高的标签可能因y轴范围不足被截断

修正代码

library(ggplot2)

# 创建数据框
data <- data.frame(
  ModeOfExpression = rep(c("Pour (less deliberate)", "Type (more deliberate)"), each = 2),
  Group = rep(c("In-group cue present", "Out-group cue present"), 2),
  Candies = c(2.24, 3.81, 2.59, 2.61)
)

# 生成条形图
p <- ggplot(data, aes(x = ModeOfExpression, y = Candies, fill = Group)) +
  # 指定条形的dodge宽度,保持默认的0.9
  geom_bar(stat = "identity", position = position_dodge(width = 0.9), colour = "black") +
  # 匹配条形的dodge宽度,同时上移标签避免重叠
  geom_text(aes(label = sprintf("%.2f", Candies)),
            y = data$Candies + 0.1,
            position = position_dodge(width = 0.9),
            vjust = 0) +
  labs(title = "Number of Candies Taken by Mode of Expression",
       y = "Number of candies taken (Log + 1)",
       x = "") +
  scale_fill_manual(values = c("grey", "white")) +
  # 扩展y轴上限,确保所有标签都能显示
  ylim(0, max(data$Candies) + 0.5) +
  theme_classic() +
  theme(legend.position = "bottom",
        legend.title = element_blank(),
        # 让标题居中显示
        plot.title = element_text(hjust = 0.5))

# 输出图形
print(p)

修改要点

  1. 统一geom_bar和geom_text的position_dodge(width = 0.9),保证标签和条形一一对应对齐
  2. 把标签的y坐标设为Candies + 0.1,和条形顶部拉开距离,避免重叠
  3. 用ylim扩展y轴的上限,防止最高的标签被裁剪
  4. 将标题的hjust改为0.5,让标题居中显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:26:02