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

如何修改R语言chart.Correlation函数添加轴标签并统一相关系数字号

R语言chart.Correlation函数自定义修改方案

核心修改点

  • 移除原函数对角线处的列名展示,改为在图表矩阵的左侧(y轴)和底部(x轴)对应位置展示列名,对角线区域保留直方图+密度线的可视化内容
  • 固定上三角区域相关系数的展示字号为12pt,取消原逻辑中字号随显著性变化的设置

自定义修改后的完整代码

library(PerformanceAnalytics)

# 自定义修改后的相关系数矩阵绘图函数
my_chart.Correlation <- function (R, histogram = TRUE, method = c("pearson", "kendall", 
    "spearman"), cor_fontsize = 12, ...) 
{
    x = checkData(R, method = "matrix")
    if (missing(method)) 
        method = method[1]
    panel.cor <- function(x, y, digits = 2, prefix = "", use = "pairwise.complete.obs", 
        method = method, cex.cor, ...) {
        usr <- par("usr")
        on.exit(par(usr))
        par(usr = c(0, 1, 0, 1))
        r <- cor(x, y, use = use, method = method)
        txt <- format(c(r, 0.123456789), digits = digits)[1]
        txt <- paste(prefix, txt, sep = "")
        # 固定字号为设置的cor_fontsize,转换为cex相对值
        cex <- cor_fontsize / par("ps")
        text(0.5, 0.5, txt, cex = cex)
    }
    if (histogram) {
        panel.hist <- function(x, ...) {
            usr <- par("usr")
            on.exit(par(usr))
            par(usr = c(usr[1:2], 0, 1.5))
            h <- hist(x, plot = FALSE)
            breaks <- h$breaks
            nB <- length(breaks)
            y <- h$counts
            y <- y/max(y)
            rect(breaks[-nB], 0, breaks[-1], y, col = "cyan", ...)
            # 已移除原对角线处列名展示的代码
        }
    }
    panel.smooth <- function (x, y, bg = NA, pch = par("pch"), cex = 1, 
        col.smooth = "red", span = 2/3, iter = 3, ...) 
    {
        points(x, y, pch = pch, bg = bg, cex = cex)
        ok <- is.finite(x) & is.finite(y)
        if (any(ok)) 
            lines(stats::lowess(x[ok], y[ok], f = span, iter = iter), 
                col = col.smooth, ...)
    }
    # 保留pairs默认的侧边列名展示逻辑
    pairs(x, lower.panel = panel.smooth, upper.panel = panel.cor, 
        diag.panel = if (histogram) panel.hist, ...)
}

调用示例

# 测试用例1:全mtcars数据集
my_chart.Correlation(mtcars, cor_fontsize = 12)

# 测试用例2:指定列子集
my_chart.Correlation(mtcars[,c(1,2,5,7)], cor_fontsize = 12)

其他实用相关分析函数推荐

  • corrplot::corrplot():专门用于相关系数矩阵可视化的包,支持自定义颜色、布局、显著性标记等多种配置,灵活性极高
  • GGally::ggpairs():基于ggplot2实现的相关矩阵绘图函数,支持对下三角、上三角、对角线的可视化形式做高度自定义,适合需要统一ggplot2绘图风格的场景
  • psych::corr.test():可以同时输出相关系数、显著性p值、置信区间等统计结果,适合需要做严谨相关统计检验的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:36:04