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

请求修改chart.Correlation函数,使下方面板点按因子列值着色

修改后的chart.Correlation函数(支持按因子着色)

没问题!我帮你调整了chart.Correlation函数,让lower面板里的散点圆圈能根据指定的因子列(比如iris数据集里的species)着色。核心是新增了一个group参数来传入分组因子,然后在绘图逻辑里把这个因子映射到填充颜色上。

chart.Correlation <- function(R, histogram = TRUE, method = c("pearson", "kendall", "spearman"), group = NULL, ...) {
    x = checkData(R, method = "matrix")
    if(missing(method)) method = method[1]
    panel.cor <- function(x, y, digits=2, prefix="", cex.cor, ...) {
        usr <- par("usr"); on.exit(par(usr))
        par(usr = c(0, 1, 0, 1))
        r <- cor(x, y, method=method)
        txt <- format(c(r, 0.123456789), digits=digits)[1]
        txt <- paste(prefix, txt, sep="")
        if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
        text(0.5, 0.5, txt, cex = cex.cor * abs(r))
    }
    # 处理颜色:如果传入group,生成对应颜色向量
    if (!is.null(group)) {
        group <- as.factor(group)
        col_vec <- rainbow(nlevels(group))[group]
    } else {
        col_vec <- "black"
    }
    # 自定义lower面板函数,支持按group着色
    lower.panel <- function(x, y, col_vec=NULL, ...) {
        points(x, y, pch=21, bg=col_vec, ...)  # pch=21才能显示填充色
    }
    # 绘图
    pairs(x, gap=0, lower.panel=function(x,y) lower.panel(x,y,col_vec=col_vec), 
          upper.panel=panel.cor, ...)
    # 直方图部分保留原逻辑
    if(histogram) {
        par(mfrow=c(ncol(x),ncol(x)))
        for(i in 1:ncol(x)) {
            hist(x[,i], main=colnames(x)[i], col="light gray", ...)
        }
        par(mfrow=c(1,1))
    }
}

关键改动说明

  • 新增group参数:调用函数时可以传入你的因子列(比如iris$species),用来指定分组着色的依据
  • 颜色映射逻辑:把因子转换成颜色向量,用rainbow()生成区分度较好的颜色,你也可以换成hcl()或者自定义颜色向量
  • lower面板绘图优化:使用pch=21(带填充的圆圈符号),这样bg参数的填充色才会生效,把每个点的背景色设置为对应分组的颜色

测试示例

用iris数据集来验证效果:

data(iris)
# 传入数值列和species因子作为分组依据
chart.Correlation(iris[,1:4], group = iris$species, histogram = TRUE, method = "pearson")

运行后你会看到lower面板的散点圆圈按照鸢尾花的品种显示不同颜色,同时upper面板保留了相关性系数的展示,直方图也正常生成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:59:31