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

如何用stat_compare_mean在同一括号中同时显示p.format与p.signif标签?

在ggplot2中用stat_compare_means同时显示精确p值和显著性星号

对于刚接触R的你,只需自定义stat_compare_means()的label参数,把精确p值和星号拼接在一起即可,不用分开设置两个label参数。以下是具体操作步骤:

1. 安装并加载所需包

首先确保你安装了ggpubr(stat_compare_means来自这个包)和ggplot2:

# 首次使用先安装
install.packages(c("ggpubr", "ggplot2"))
# 加载包
library(ggpubr)
library(ggplot2)

2. 用示例数据演示(以mtcars为例)

我们用mtcars数据集的mpg(油耗)和am(变速箱类型:0=自动,1=手动)做两组比较:

# 绘制箱线图并添加统计信息
ggplot(mtcars, aes(x = factor(am), y = mpg)) +
  geom_boxplot() +
  # 核心:用paste0拼接精确p值和星号
  stat_compare_means(
    label = paste0("p = ", ..p.format.., " ", ..p.signif..),
    method = "t.test" # 根据你的研究需求更换检验方法,比如wilcox.test
  )

关键说明

  • ..p.format..是stat_compare_means生成的格式化精确p值(例如p=0.0012)
  • ..p.signif..是对应的显著性星号(规则:***对应p<0.001,**对应0.001≤p<0.01,*对应0.01≤p<0.05,ns对应p≥0.05)
  • 用paste0()将两个值拼接,中间加空格分隔,就能同时显示两者

多组比较的情况(如ANOVA)

如果是多组比较(比如比较mtcars中不同cyl(气缸数)的mpg),代码可调整为:

ggplot(mtcars, aes(x = factor(cyl), y = mpg)) +
  geom_boxplot() +
  stat_compare_means(
    label = paste0("p = ", ..p.format.., " ", ..p.signif..),
    method = "anova"
  )

这样就能在论文图表中同时展示精确p值和对应显著性星号了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:23:18