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

如何使用stat_cor()函数在ggplot对象中设置p-value的首字母P为大写

ggpubr::stat_cor() 输出p值改为大写P的实现方法

stat_cor() 没有内置的p值大小写配置参数,可通过自定义标签模板快速实现需求,以下是两种常用实现方案:

方案1:直接构造自定义标签(最简方案)

直接在aes(label)参数中手动指定大写P的输出格式,同时可自定义保留位数:

# 加载依赖包
library(ggplot2)
library(ggpubr)

# 绘图示例(以mtcars数据集为例)
ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  stat_cor(
    aes(label = paste0("R = ", round(..r.., 2), ", P = ", round(..p.value.., 3))),
    show.legend = FALSE
  )

如果需要保留显著性星号标识,调整label内容即可:
aes(label = paste0("R = ", round(..r.., 2), ", P = ", round(..p.value.., 3), ..p.signif..))

方案2:适配科学计数法的P值格式

如果p值过小需要用科学计数法显示,可通过format()函数处理p值输出:

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  stat_cor(
    aes(label = paste0(
      "R = ", round(..r.., 2), 
      ", P = ", format(..p.value.., scientific = TRUE, digits = 2)
    )),
    show.legend = FALSE
  )

如果使用非Pearson相关(如Spearman秩相关),仅需在stat_cor()中添加method = "spearman"参数即可,标签内容可同步调整为rho适配方法命名。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 08:36:02