[英]Plot scatterplot matrix with partial correlation coefficients in R
I use a modified version of the pairs
function to produce a scatterplot matrix: 我使用
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])
which looks like this: 看起来像这样:
What I would like to do is to put the partial correlation coefficients instead of the pairwise Pearson's r into the lower panel. 我想做的是将部分相关系数而不是成对的皮尔逊r放到下面的面板中。
I can calculate the partial correlation coefficients easily: 我可以很容易地计算出偏相关系数:
library(ppcor)
pcor(iris[,1:4])$estimate
But I couldn't figure out how to modify the lower panel function panel.cor
so that it shows these values. 但是我不知道如何修改下部面板功能
panel.cor
以便显示这些值。 The problem seems to be that the lower panel function handles the pairwise x
and y
values, whereas the partial correlation function pcor
requires the entire data frame (or matrix). 问题似乎在于下部面板函数处理成对的
x
和y
值,而部分相关函数pcor
需要整个数据帧(或矩阵)。
Looks like pairs
doesn't make this very easy. 看起来像这样
pairs
并不容易。 Simplest thing I could come up with is to have panel.cor
peek into the parent data.frame to find the row/col index for the current panel and then you can use that to index into pre-calculated values. 我能想到的最简单的事情是让
panel.cor
窥视父data.frame来查找当前面板的行/列索引,然后可以使用它来索引预先计算的值。 Here's the updated panel.cor
function 这是更新的
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)
}
Here use use parent.frame(2)
to actually grab the local variables i
and j
from the pairs.default
function. 在这里,使用use
parent.frame(2)
来真正地获取pairs.default
函数中的局部变量i
和j
。 And we assume that pp
contains the values from pcor
. 并且我们假定
pp
包含pcor
中的值。 So you would define that variable before calling pairs.cor
因此,您将在调用
pairs.cor
之前定义该变量。
pp <- ppcor::pcor(iris[,1:4])$estimate
pairs.cor(iris[,1:4])
This gives the following result 这给出了以下结果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.