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

如何在相关矩阵(Correlation matrix)中绘制显著性代码

实现带自定义显著性星号的相关矩阵可视化

需求说明

需要在相关矩阵图中,按以下规则为显著相关的系数标注星号:

  • p ≤ 0.001:***
  • 0.001 < p ≤ 0.01:**
  • 0.01 < p ≤ 0.05:*
  • 0.05 < p ≤ 0.1:.
  • p > 0.1:无标记

原代码使用ggcorrplot包时,默认的p.mat参数仅能显示显著性标记(如叉号),无法直接在相关系数旁添加星号,需自定义处理标签内容。

解决方案代码

# 加载所需包
library(ggcorrplot)
library(ggplot2)

# 1. 计算相关系数矩阵和p值矩阵
r <- cor(mtcars)
p_mat <- ggcorrplot::cor_pmat(mtcars)

# 2. 定义显著性星号转换函数
get_signif_stars <- function(p) {
  case_when(
    p <= 0.001 ~ "***",
    p <= 0.01 ~ "**",
    p <= 0.05 ~ "*",
    p <= 0.1 ~ ".",
    TRUE ~ ""
  )
}

# 3. 生成带星号的标签矩阵:保留1位小数+对应星号
lab_matrix <- matrix(
  paste0(round(r, 1), get_signif_stars(p_mat)),
  nrow = nrow(r),
  dimnames = dimnames(r)
)

# 4. 绘制带星号的相关矩阵图
ggcorrplot(
  r,
  hc.order = FALSE,
  type = "lower",
  lab = TRUE,          # 启用自定义标签
  lab_matrix = lab_matrix,  # 传入带星号的标签矩阵
  lab_size = 3,
  tl.cex = 12,
  outline.col = "white",
  legend.title = "corr",
  title = "",
  ggtheme = theme_classic(),
  colors = c("#E46726", "white", "#6D9EC1")
)

代码说明

  • 先计算基础的相关系数矩阵r和p值矩阵p_mat
  • 用get_signif_stars函数根据p值匹配对应的显著性标记
  • 将保留指定小数位数的相关系数与星号拼接,生成自定义标签矩阵lab_matrix
  • 在ggcorrplot中通过lab_matrix参数传入自定义标签,替代默认的纯系数显示,同时无需再设置p.mat参数(避免重复标记)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 08:32:38