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

R语言ggplot2使用geom_text为分组柱状图各柱子添加自定义文本方法

分组柱状图添加文本标签的修正方案

你代码的核心问题有两个:

  1. geom_text的label参数固定写为"a",没有映射到要展示的数值列
  2. 不需要用interaction(variable)做fill分组,直接用variable即可,分组逻辑和geom_bar保持一致就能让标签对应到每个柱子上

修正后的完整可运行代码如下:

library(ggplot2)
library(tidyr)
library(dplyr)

# 你的示例数据
squads <- tibble::tribble(
  ~test, ~first_res, ~second_res, ~third_res, ~fourth_res, ~fifth_res,
  "Appearance",       201L,         72L,        54L,         46L,        39L,
  "Aroma",         8L,         17L,        17L,         24L,        13L,
  "Flavor",       107L,        148L,       177L,        168L,       122L,
  "Texture",       151L,        225L,       220L,        198L,       150L,
  "Abstract",       282L,        260L,       360L,        356L,       402L
)

# 转换为长表,替代原来的melt函数
dat <- squads %>% 
  pivot_longer(cols = -test, names_to = "variable", values_to = "value")

# 绘图
ggplot(dat, aes(test, value, fill = variable)) +
  geom_col(position = position_dodge(0.9), width = 0.8) + # geom_col等价于geom_bar(stat='identity')
  ggtitle("A: General OEQ") + 
  theme_bw() + 
  theme(
    axis.text.x = element_text(angle=90, hjust=1, size = 10, face = "bold"),
    legend.position = c(.51, .80),
    legend.title=element_blank(),
    panel.border = element_blank(),
    axis.line = element_line(colour = "black"),
    legend.key.size = unit(1.0, "cm"), 
    legend.key.width = unit(0.5,"cm"),
    legend.key.height = unit(0.5,"cm"),
    legend.text = element_text(size = 7)
  ) +
  scale_fill_brewer('Open-end', palette='RdPu') +
  xlab("") + 
  ylab("Frequency") +
  # 核心修改:label映射为value,position_dodge和geom_col的宽度匹配
  geom_text(aes(label = value), 
            position = position_dodge(0.9), 
            size = 2,
            vjust = -0.25, 
            fontface="bold")

Stack Overflow分享数据的正确方式

你当前用reprex包生成示例内容的方式就是官方推荐的标准操作,遵循以下规则即可:

  • 小数据集直接粘贴dput(你的数据框)或者tribble格式的可运行代码,所有人可以直接复制运行复现你的问题
  • 大数据集取前10-20行即可,用dput(head(你的数据, 20))输出内容粘贴
  • 不要只贴截图、无格式的文本片段,要保证分享的数据可以直接赋值给变量运行
  • 完整附上你运行出错的代码、报错信息、实际输出和预期输出的差异

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:57:00