【问题标题】:Plot scatterplot matrix with partial correlation coefficients in R在 R 中绘制具有偏相关系数的散点图矩阵
【发布时间】:2016-02-24 00:27:18
【问题描述】:

我使用pairs 函数的修改版本来生成散点图矩阵:

pairs.cor <- function (x,y,smooth=TRUE, digits=2,  ...)
{
  panel.cor <- function(x, y, ...)
  {
    usr <- par("usr"); on.exit(par(usr))
    par(usr = c(0, 1, 0, 1))
    r.obj = cor.test(x, y,use="pairwise",...)
    r = as.numeric(r.obj$estimate)
    p = r.obj$p.value
    mystars <- ifelse(p < .05, "* ", " ")
    txt <- format(c(r, 0.123456789), digits=digits)[1]
    txt <- paste(txt, mystars, sep="")
    text(0.5, 0.5, txt)
  }
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")
  }
pairs(x,diag.panel=panel.hist,lower.panel=panel.cor,upper.panel=panel.smooth, ...)
} 

pairs.cor(iris[,1:4])

看起来像这样:

我想做的是将偏相关系数而不是成对的 Pearson's r 放入下面板。

我可以很容易地计算出偏相关系数:

library(ppcor)
pcor(iris[,1:4])$estimate

但我不知道如何修改下方面板函数panel.cor 使其显示这些值。问题似乎是下面板函数处理成对的xy 值,而偏相关函数pcor 需要整个数据帧(或矩阵)。

【问题讨论】:

    标签: r plot


    【解决方案1】:

    看起来pairs 并没有让这很容易。我能想到的最简单的事情是让panel.cor 查看父 data.frame 以找到当前面板的行/列索引,然后您可以使用它来索引预先计算的值。这是更新后的panel.cor 函数

    panel.cor <- function(x, y, ...) {
        env <- parent.frame(2)
        i <- env$i
        j <- env$j
        usr <- par("usr"); on.exit(par(usr))
        par(usr = c(0, 1, 0, 1))
        r = as.numeric(pp[i,j])
        txt <- format(c(r, 0.123456789), digits=digits)[1]
        text(0.5, 0.5, txt)
    }
    

    这里使用parent.frame(2)pairs.default 函数中实际获取局部变量ij。我们假设pp 包含来自pcor 的值。因此,您将在调用 pairs.cor

    之前定义该变量
    pp <- ppcor::pcor(iris[,1:4])$estimate
    pairs.cor(iris[,1:4])
    

    这给出了以下结果

    【讨论】:

      猜你喜欢
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 2018-12-05
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 2015-10-20
      相关资源
      最近更新 更多