使用R中的pairs()命令在相关图中添加标识行

时间:2013-07-22 17:26:58

标签: r correlation scatter-plot

prevous post类似,我想修改以下代码(from example in the R documentation for pairs() command):

## put (absolute) correlations on the upper panels,
## with size proportional to the correlations.
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 <- abs(cor(x, y))
    txt <- format(c(r, 0.123456789), digits = digits)[1]
    txt <- paste0(prefix, txt)
    if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
    text(0.5, 0.5, txt, cex = cex.cor * r)
}
pairs(USJudgeRatings, lower.panel = panel.smooth, upper.panel = panel.cor)

我想要每个情节都有一条身份线,而不是黄土线。秘密在于$“panel.smooth”功能,但我不知道如何修改它。

2 个答案:

答案 0 :(得分:6)

我认为你的意思是:

my_line <- function(x,y,...){
    points(x,y,...)
    abline(a = 0,b = 1,...)
}
pairs(USJudgeRatings, lower.panel = my_line, upper.panel = panel.cor)

答案 1 :(得分:1)

或者,如果你想绘制拟合的线性线,那么你可以修改joran的答案:

my_line <- function(x,y,...){
    points(x,y,...)
    abline(a = lm(y ~ x)$coefficients[1] , b = lm(y ~ x)$coefficients[2] , ...)
}

但是,如果你确实使用了对,那么看起来黄土会更合适,因为你可能正在探索一个数据集,并且保证在这一点上将线性线拟合为无关的。