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

如何在R中使用ggsignif为分组箱线图添加自定义显著性标记

使用ggsignif为分组箱线图添加自定义p值标记

因为你的p值是基于外部背景分布预先计算好的,无法通过当前数据直接计算,所以需要用ggsignif的手动注释模式来添加标记,具体实现步骤如下:

1. 加载所需包

library(ggplot2)
library(ggsignif)

2. 生成数据与预先计算的p值

set.seed(123)
df <- data.frame(Category = rep(c('A', 'B'), each=200),
                 Position = rep(rep(1:4, each=50), 2),
                 Value = c(rnorm(200, mean=0), rnorm(200, mean=1)))

# 预先计算的p值(固定种子方便复现)
set.seed(456)
Pvalue <- runif(4, min=0, max=0.05)

3. 构建显著性标记的参数数据框

为每个Position指定标记的位置范围、注释文本和y轴高度:

signif_df <- data.frame(
  xmin = 1:4 - 0.4,  # 覆盖对应Position左侧箱线的x边界
  xmax = 1:4 + 0.4,  # 覆盖对应Position右侧箱线的x边界
  annotations = paste("p =", round(Pvalue, 4)), # 格式化p值为可读文本
  # 标记位置设为每个Position的最大值上方0.5,避免与箱线重叠
  y_position = tapply(df$Value, df$Position, max) + 0.5
)

4. 绘制带显著性标记的箱线图

ggplot(df, aes(x=factor(Position), y=Value, fill=Category)) +
  geom_boxplot(position = position_dodge(width=0.8)) + # 统一箱线分组宽度,与标记范围匹配
  geom_signif(
    data = signif_df,
    aes(xmin=xmin, xmax=xmax, annotations=annotations, y_position=y_position),
    manual = TRUE, # 启用手动注释模式
    tip_length = 0.01, # 调整标记竖线长度(可选)
    textsize = 3.5 # 调整注释文本大小(可选)
  ) +
  labs(x='Position', y='Value', fill='Category') +
  theme_minimal() +
  ggtitle('Boxplot of Values by Position and Category')

关键说明

  • manual=TRUE是核心参数,让ggsignif跳过自动统计检验,直接使用你提供的注释内容
  • 可通过修改geom_signif的color、textsize、tip_length等参数调整标记样式
  • y_position的取值可根据数据分布灵活调整,确保标记不被箱线或离群点遮挡

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 08:40:13