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

如何在ggplot中以科学计数法显示p值?

解决ggplot中p值科学计数法显示及annotate手动注释问题

一、用ggpubr::stat_cor实现p值科学计数法显示

直接通过自定义stat_cor的label参数,结合格式化函数就能实现科学计数法展示p值,示例代码如下:

# 构造示例数据
set.seed(123)
df <- data.frame(x = rnorm(50), y = rnorm(50) * 0.3 + x * 0.6)

# 绘图并设置p值科学计数法
library(ggplot2)
library(ggpubr)

ggplot(df, aes(x = x, y = y)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  # 自定义标签格式,用sprintf实现科学计数法
  stat_cor(
    aes(label = paste(..rr.label.., "p =", sprintf("%.2e", ..p.label..), sep = ", ")),
    method = "pearson",
    r.accuracy = 0.01,
    label.x = 0, label.y = 2
  )

如果需要更灵活的格式控制,也可以用format.pval函数替代sprintf:

stat_cor(
  aes(label = paste(..rr.label.., "p =", format.pval(..p.label.., digits = 2, scientific = TRUE), sep = ", ")),
  method = "pearson",
  r.accuracy = 0.01,
  label.x = 0, label.y = 2
)

二、用annotate()手动添加注释

先手动计算相关系数和p值,再用annotate()指定位置添加注释,步骤如下:

1. 提前计算统计量

# 计算皮尔逊相关系数和p值
cor_test_result <- cor.test(df$x, df$y, method = "pearson")
r_squared <- round(cor_test_result$estimate^2, 2)
p_value <- cor_test_result$p.value

2. 绘图时添加注释

ggplot(df, aes(x = x, y = y)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  # 手动添加注释,指定x、y坐标和标签内容
  annotate(
    "text",
    x = max(df$x) - 0.5,  # 自定义x位置
    y = max(df$y) - 0.5,  # 自定义y位置
    label = paste0("R² = ", r_squared, "\np = ", sprintf("%.2e", p_value)),
    size = 4,
    hjust = 1
  )

可以通过调整x、y、hjust、vjust参数控制注释的位置,size控制字体大小,color设置字体颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 07:15:57