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

使用ggpubr为箱线图加星号:ref.group下symnum.args失效问题

问题描述

使用ggplot2和ggpubr绘制箱线图时,当使用stat_compare_means的ref.group参数(以A组为对照组做两两t检验),无法通过symnum.args将p值替换为显著性星号;但改用comparisons参数时可以正常实现,请问如何解决?

原始代码如下:

set.seed(15)
xdf <- data.frame(
  values = c(
rnorm(n = 20, mean = 0, sd = .4),
rnorm(n = 20, mean = 0.3, sd = .7),
rnorm(n = 20, mean = 0.6, sd = .15),
rnorm(n = 20, mean = 0.2, sd = .4),
rnorm(n = 20, mean = 0.4, sd = .4),
rnorm(n = 20, mean = 0.7, sd = .5)
),
groups = rep(LETTERS[1:6],each=20)
)


library(ggplot2)
library(ggpubr)

ggplot(xdf, aes(x=groups, y=values, fill=groups)) +
geom_boxplot() +
scale_fill_manual(values=pals::brewer.greens(6)) +
theme_pubclean() +
theme(legend.position = 'none') +
xlab("") +
ylab("Values") +  
stat_compare_means(ref.group="A", 
                 method = "t.test", 
                 label.y = maxvals+0.1,
                 symnum.args = list(cutpoints = c(0, 0.0001, 0.001, 0.01, 0.05, 1),  
                 symbols = c("****", "***", "**", "*", "ns"))
解决方案

核心问题是使用ref.group时,stat_compare_means默认的标签输出不是星号格式,需手动指定label = "p.signif",同时修正代码中未定义maxvals的问题。修改后的完整代码如下:

set.seed(15)
xdf <- data.frame(
  values = c(
    rnorm(n = 20, mean = 0, sd = .4),
    rnorm(n = 20, mean = 0.3, sd = .7),
    rnorm(n = 20, mean = 0.6, sd = .15),
    rnorm(n = 20, mean = 0.2, sd = .4),
    rnorm(n = 20, mean = 0.4, sd = .4),
    rnorm(n = 20, mean = 0.7, sd = .5)
  ),
  groups = rep(LETTERS[1:6], each=20)
)

library(ggplot2)
library(ggpubr)
library(pals) # 显式加载pals包,避免函数找不到报错

# 计算每组最大值,用于设置标签的y轴位置
maxvals <- tapply(xdf$values, xdf$groups, max)

ggplot(xdf, aes(x=groups, y=values, fill=groups)) +
  geom_boxplot() +
  scale_fill_manual(values=brewer.greens(6)) +
  theme_pubclean() +
  theme(legend.position = 'none') +
  xlab("") +
  ylab("Values") +  
  stat_compare_means(
    ref.group="A", 
    method = "t.test", 
    label = "p.signif", # 指定输出显著性星号而非原始p值
    label.y = maxvals + 0.1,
    symnum.args = list(
      cutpoints = c(0, 0.0001, 0.001, 0.01, 0.05, 1),  
      symbols = c("****", "***", "**", "*", "ns")
    )
  )

关键修改说明

  • 添加label = "p.signif":这是让stat_compare_means在使用ref.group模式下输出自定义星号规则的核心参数,默认模式下该参数不会自动启用。
  • 定义maxvals:通过tapply计算每组数据的最大值,确保显著性标签能显示在对应箱线图的上方。
  • 显式加载pals包:避免brewer.greens函数因未加载包而报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:01:01