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

如何使用ggplot2在箱线图指定位置添加显著性差异标记字母

标注示例图

ggplot2手动添加自定义文本/显著性字母方法

方法1:内置annotate()函数(最灵活,适合少量自定义标注)

这是ggplot2自带功能,无需安装额外包,可直接在任意坐标位置添加文本:

library(ggplot2)
# 1. 先画基础箱线图
# 以下为示例数据,可替换为你自己的数据集
data <- data.frame(
  group = rep(c("处理1", "处理2", "处理3", "处理4"), each = 50),
  value = c(rnorm(50, 8, 2), rnorm(50, 12, 2), rnorm(50, 15, 2), rnorm(50, 9, 2))
)
p <- ggplot(data, aes(x = group, y = value)) +
  geom_boxplot()

# 2. 添加自定义文本
p + 
  # x对应分组顺序:第一个分组x=1,第二个x=2,以此类推
  # y控制文本高度,数值越高位置越靠上
  annotate("text", x = 1, y = 19, label = "a", size = 5) +
  annotate("text", x = 2, y = 21, label = "b", size = 5) +
  annotate("text", x = 3, y = 24, label = "c", size = 5) +
  annotate("text", x = 4, y = 20, label = "a", size = 5)

方法2:geom_text()映射标注(适合批量标注)

如果需要添加的标注较多,可以提前整理标注数据框,批量映射:

# 提前整理标注信息:对应分组、显示高度、标注内容
label_data <- data.frame(
  group = c("处理1", "处理2", "处理3", "处理4"),
  y_pos = c(19, 21, 24, 20),
  label = c("a", "b", "c", "a")
)

p + 
  geom_text(data = label_data, 
            aes(x = group, y = y_pos, label = label),
            size = 5,
            inherit.aes = FALSE) # 关闭全局映射继承,避免报错

补充:添加显著性横线

如果需要搭配组间比较的横线,同样可以用annotate()实现:

p +
  # 添加处理1和处理2之间的比较横线
  annotate("segment", x = 1, xend = 2, y = 20, yend = 20, linewidth = 0.8) +
  # 添加显著性标记
  annotate("text", x = 1.5, y = 20.5, label = "**", size = 6) +
  # 保留分组字母标注
  annotate("text", x = 1, y = 19, label = "a", size = 5) +
  annotate("text", x = 2, y = 19, label = "b", size = 5)

你可以根据自己的图表坐标范围,灵活调整x、y的数值,就能把文本放到任意你需要的位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 17:15:03