如何在GGally的ggpairs图中用WRS2添加稳健相关性及显著性值/星号?
给ggpairs图替换稳健相关性(pbcor/wincor)并添加显著性标记
1. 加载依赖包和示例数据
library(ggplot2) library(GGally) library(WRS2) # 用iris数据集做演示,可替换为自身数据 data(iris)
2. 自定义稳健相关计算函数
这个函数会调用WRS2包的pbcor或wincor计算稳健相关,返回带显著性星号的文本,用来替换ggpairs默认的相关系数显示:
robust_cor_func <- function(data, mapping, method = "pbcor", ...) { # 提取x、y变量 x <- eval(mapping$x, data) y <- eval(mapping$y, data) # 选择稳健相关方法 if (method == "pbcor") { cor_res <- pbcor(x, y, ...) } else if (method == "wincor") { cor_res <- wincor(x, y, ...) } else { stop("仅支持pbcor或wincor两种方法") } # 格式化相关值与显著性星号 cor_val <- round(cor_res$cor, 2) p_val <- cor_res$p.value # 显著性星号规则(可自行调整阈值) sig_stars <- ifelse(p_val < 0.001, "***", ifelse(p_val < 0.01, "**", ifelse(p_val < 0.05, "*", ""))) # 组合显示文本 display_text <- paste0(cor_val, sig_stars) # 返回文本标注图层 ggplot(data, mapping) + annotate("text", x = mean(x, na.rm = TRUE), y = mean(y, na.rm = TRUE), label = display_text, size = 4) + theme_void() }
3. 在ggpairs中调用自定义函数
将上三角的相关系数显示替换为我们的稳健相关函数即可:
# 使用pbcor方法的示例 ggpairs(iris[, 1:4], upper = list(continuous = wrap(robust_cor_func, method = "pbcor")), lower = list(continuous = "smooth")) # 下三角保留平滑散点图 # 换成wincor方法仅需修改method参数 ggpairs(iris[, 1:4], upper = list(continuous = wrap(robust_cor_func, method = "wincor")), lower = list(continuous = "smooth"))
额外调整建议
- 若需同时显示p值,修改
display_text即可:display_text <- paste0(cor_val, sig_stars, "\np=", round(p_val, 3)) - 函数已处理缺失值(
na.rm=TRUE),含NA的数据也能正常计算 - 显著性星号的阈值可根据需求自行修改
内容的提问来源于stack exchange,提问作者Barun
相关产品推荐
相关产品推荐

