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

如何为ggpubr stat_compare_means()的p值标签添加自定义前缀

R ggpubr 箱线图自定义p值前缀解决方法

你尝试的写法不生效,是因为部分版本的ggpubr在使用comparisons参数做多组比较时,会默认覆盖aes中的label映射,以下两种写法均可实现p值前添加p = 前缀的需求:

方法1:适配ggpubr v0.4.0及以上版本

library(ggpubr)
my_comparisons <- list(c("0.5", "1"), c("1", "2"), c("0.5", "2"))

ggboxplot(ToothGrowth, x = "dose", y = "len") + 
  stat_compare_means(
    comparisons = my_comparisons, 
    method = "wilcox.test",
    aes(label = paste0("p = ", ..p.format..)),
    tip.length = 0.01 # 可选,调整显著性标记竖线长度,避免和p值重叠
  )

方法2:全版本兼容写法

使用label.func参数自定义p值输出格式,不受版本差异影响。format.pval是R内置的p值格式化函数,会自动处理p < 2e-16这类极小值的显示,不需要额外判断:

library(ggpubr)
my_comparisons <- list(c("0.5", "1"), c("1", "2"), c("0.5", "2"))

ggboxplot(ToothGrowth, x = "dose", y = "len") + 
  stat_compare_means(
    comparisons = my_comparisons, 
    method = "wilcox.test",
    # 自定义格式,可按需调整digits参数修改保留位数
    label.func = function(p) paste0("p = ", format.pval(p, digits = 2)),
    tip.length = 0.01
  )

如果需要用科学计数法显示p值,把label.func替换为以下内容即可:

label.func = function(p) paste0("p = ", scales::scientific(p, digits = 2))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 21:24:04