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

如何让corrplot在shade模式下显示相关系数的尾随零?

解决corrplot shade模式下显示固定两位小数相关系数的问题

问题原因

corrplot包的number.digits参数控制的是有效数字位数,而非固定小数位数。对于0.899这类数值:

  • 设置number.digits=2时,会按有效数字规则四舍五入显示为0.9
  • 设置number.digits=3时显示完整的0.899
    无法直接通过该参数得到0.90的固定小数格式。

解决方案1:先四舍五入相关系数(最简方法)

先将计算得到的相关系数矩阵四舍五入到两位小数,再传入corrplot,此时number.digits=2会自动显示两位小数格式的数值:

library(tidyverse)
library(corrplot)

data("mtcars")

corr_df = mtcars %>%
  select(mpg, disp, hp, drat, wt, qsec)

# 计算Spearman相关系数矩阵
mat = cor(corr_df, method = "spearman")
# 四舍五入到两位小数
mat_rounded = round(mat, 2)

# 绘制带两位小数系数的shade模式热图
corrplot(mat_rounded, method = "shade",  tl.col = "black", 
         addCoef.col = "black", type = "lower",  
         order = "original" , diag = F,
         addgrid.col = "black", tl.srt = 45, number.digits = 2)

解决方案2:手动格式化并添加系数文本

如果需要保留原始计算精度但仅显示固定小数位数,可手动格式化系数为字符串,再通过text()函数添加到图中:

library(tidyverse)
library(corrplot)

data("mtcars")

corr_df = mtcars %>%
  select(mpg, disp, hp, drat, wt, qsec)

mat = cor(corr_df, method = "spearman")
# 将所有系数格式化为两位小数的字符串
mat_formatted = apply(mat, 2, function(x) sprintf("%.2f", x))

# 先绘制不带系数的shade热图
corrplot(mat, method = "shade",  tl.col = "black", 
         type = "lower",  order = "original" , diag = F,
         addgrid.col = "black", tl.srt = 45)

# 获取矩阵列数,遍历下三角区域添加文本
n_col = ncol(mat)
for (row in 1:(n_col - 1)) {
  for (col in (row + 1):n_col) {
    # corrplot坐标:列对应x轴,行对应y轴
    text(col, row, mat_formatted[row, col], col = "black", cex = 0.8)
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 01:02:17