Adding line of identity to correlation plots using pairs() command in R

╄→尐↘猪︶ㄣ 提交于 2019-12-18 09:04:59

问题


Similar to a prevous post, I'd like to modify the following code (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)

Instead of a loess line, I want a line of identity for each plot. The secret lies in the $"panel.smooth" function, but I don't know how to modify it.


回答1:


I think you just mean something like this:

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



回答2:


Or, if you want to plot a fitted, linear line, then you could modify joran's answer:

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

If you are indeed using pairs, however, it seems like loess would be more appropriate since you are likely exploring a dataset and would warrant the fitting of a linear line as extraneous at that point.



来源:https://stackoverflow.com/questions/17793690/adding-line-of-identity-to-correlation-plots-using-pairs-command-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!