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

如何在ggpairs绘制的相关矩阵图中添加p值及95%置信区间?

问题

现有R代码ggpairs(baseline2, title="correlogram "),希望在生成的相关矩阵图文本区域中,将精确p值和/或95%置信区间添加至点估计值旁。数据集结构如下:

baseline2 <- structure(list(delta_bp = c(-21.5, 7, -17.5, -10.5, -21, -7.5, 
4.5, 3, -9, 9, -22.5, -9.5), delta_bp_05 = c(-21.5, 0, 3, -13.5, 
-13, -4, -16.5, -8, 5, -5, -12, 0.5), delta_bp_10 = c(-26.5, 
1, -6, -10.5, -9, -3, -20.5, -10, 1, -6, -22, -0.5)), row.names = c(NA, 
-12L), class = c("tbl_df", "tbl", "data.frame"), na.action = structure(c(`17` = 17L, 
`27` = 27L, `32` = 32L), class = "omit"))
解决方案

方法1:自定义GGally文本面板(保留ggpairs框架)

通过自定义文本绘制函数,在ggpairs的指定面板中显示相关系数、p值和95%置信区间:

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

# 定义函数:计算变量对的相关统计量
get_cor_stats <- function(x, y) {
  # 执行Pearson相关检验(可替换为spearman)
  cor_test <- cor.test(x, y, method = "pearson")
  # 格式化统计量
  r <- round(cor_test$estimate, 3)
  p_val <- round(cor_test$p.value, 3)
  ci_low <- round(cor_test$conf.int[1], 3)
  ci_high <- round(cor_test$conf.int[2], 3)
  # 组合显示文本
  paste0("r = ", r, "\np = ", p_val, "\n95% CI: [", ci_low, ", ", ci_high, "]")
}

# 自定义ggpairs的文本面板
cor_text_panel <- function(data, mapping, ...) {
  x <- eval(mapping$x, data)
  y <- eval(mapping$y, data)
  ggplot(data, mapping) +
    geom_text(aes(label = get_cor_stats(x, y)), size = 3.5) +
    theme_void()
}

# 生成带统计量的相关矩阵图
ggpairs(baseline2, 
        title = "correlogram",
        upper = list(continuous = cor_text_panel), # 上三角显示自定义统计文本
        lower = list(continuous = "smooth")) # 下三角保留散点+拟合线

如果只需要显示相关系数和p值,修改get_cor_stats中的文本为paste0("r = ", r, "\np = ", p_val)即可。

方法2:使用psych包的pairs.panels

若可更换工具包,psych包的pairs.panels能直接输出包含相关系数、p值和置信区间的矩阵图,代码更简洁:

# 加载包
library(psych)

# 生成带统计量的相关矩阵图
pairs.panels(baseline2, 
             method = "pearson",       # 指定相关方法
             hist.col = "#00AFBB",     # 直方图颜色
             density = TRUE,           # 显示密度曲线
             ellipses = TRUE,          # 显示置信椭圆
             pch = 19,                 # 散点形状
             lm = TRUE,                # 显示拟合线
             stars = TRUE,             # 用星号标记显著性(可选)
             ci = TRUE)                # 显示95%置信区间

该函数默认在对角线下方的相关系数旁标注p值(括号内),开启ci=TRUE后会同时显示置信区间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 11:40:20