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

使用stat_compare_means绘制分组箱线图时缺失显著性括号的问题

解决ggplot2分组箱线图显著性括号缺失问题

问题描述

用ggplot2绘制分组箱线图时,需要在每个Group的男女(Sex)对比组上方展示Wilcox检验的显著性值,但调用stat_compare_means仅能显示p值,对应的显著性括号始终无法显示。

复现数据

df <- data.frame(Group = rep(c("A", "B", "C", "D"), each = 8 ), 
           Sex = rep(c(rep("F", 5), rep("M", 3)), 4), 
           Sample = rep(1:8, 4), 
           Value = c(0, 0, 0, 0, 0, 12.55,  0,  2.42, 9.68, 5.81, 7.51, 8.23, 
                     6.42, 0, 5.30, 2.04, 34.00, 27.52, 30.72, 36.11, 34.79, 
                     13.81, 38.52, 19.03, 0, 5.13, 0, 2.72, 1.99, 0, 0, 0))

原绘图代码(存在括号缺失问题)

library(ggplot2)
library(ggpubr)

ggplot(df, aes(x = Group, y = Value, fill = Sex)) +
      stat_boxplot(geom = "errorbar", width = 0.55, position = position_dodge(width = 0.9)) +
      geom_boxplot(position = position_dodge(width = 0.9)) + theme_minimal() +
      theme(axis.text.x = element_text(hjust = 1), legend.position = "none") + 
      scale_fill_manual(values = c("F" = "#A6CEE3", "M" = "palevioletred2")) +
      stat_compare_means(aes(group = Sex), label = "p.format", method = "wilcox.test", bracket.size = 2, label.y = 42)

解决方案

问题根源是stat_compare_means默认位置未与分组箱线图对齐,且未明确指定在每个Group内部进行组间对比。改用先计算显著性结果,再手动绘制标注的方式更可靠:

修正后代码

library(ggplot2)
library(ggpubr)

# 1. 按Group分组,计算每组内Sex的Wilcox检验结果
stat_results <- compare_means(Value ~ Sex, data = df, group.by = "Group", method = "wilcox.test")
# 调整标注的坐标位置,确保对应到每个Group上方
stat_results$x <- as.integer(stat_results$Group)
stat_results$y.position <- 42

# 2. 绘制箱线图并添加带括号的显著性标注
ggplot(df, aes(x = Group, y = Value, fill = Sex)) +
  stat_boxplot(geom = "errorbar", width = 0.55, position = position_dodge(width = 0.9)) +
  geom_boxplot(position = position_dodge(width = 0.9)) +
  theme_minimal() +
  theme(axis.text.x = element_text(hjust = 1), legend.position = "none") +
  scale_fill_manual(values = c("F" = "#A6CEE3", "M" = "palevioletred2")) +
  # 用stat_pvalue_manual实现括号+ p值的标注,position与箱线图对齐
  stat_pvalue_manual(stat_results, label = "p.format", 
                     position = position_dodge(width = 0.9), bracket.size = 2)

效果说明

修正后,每个Group的男女箱线图上方会显示连接两组的显著性括号,同时标注对应的Wilcox检验p值,与期望效果一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 15:17:38