Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw regression line instead of lowess line in `pairs()` in R? [duplicate]

Tags:

plot

r

I'm trying to replace the panel.smooth for argument panel in pairs() with a regression line drawing function instead of lowess line, with no success.

I tried to create function reg and place it for argument panel but that does not work? Any fix?

reg <- function(x, y) abline(lm(y~x)) # made to draw regression line instead of lowess line


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)
 text(0.5, 0.5, txt, cex = 1.1, font = 4)
 }
 #EXAMPLE OF USE:
pairs(USJudgeRatings[1:5], panel = panel.smooth, # replace HERE for panel.smooth #
  cex = 1.5, pch = 19, col = adjustcolor(4, .4), cex.labels = 2, font.labels = 2, lower.panel = panel.cor)
like image 555
rnorouzian Avatar asked Sep 13 '25 01:09

rnorouzian


2 Answers

You never used your function reg. I slightly modified reg to take a color argument. Instead of using panel.smooth (which gives the loess curve) I modified it to use the linear model and your reg function.

reg <- function(x, y, col) abline(lm(y~x), col=col) 

panel.lm =  function (x, y, col = par("col"), bg = NA, pch = par("pch"), 
    cex = 1, col.smooth = "red", span = 2/3, iter = 3, ...)  {
    points(x, y, pch = pch, col = col, bg = bg, cex = cex)
    ok <- is.finite(x) & is.finite(y)
    if (any(ok)) reg(x[ok], y[ok], col.smooth)
}

pairs(USJudgeRatings[1:5], panel = panel.lm,
    cex = 1.5, pch = 19, col = adjustcolor(4, .4), cex.labels = 2, 
    font.labels = 2, lower.panel = panel.cor)

pairs

like image 144
G5W Avatar answered Sep 14 '25 16:09

G5W


You need to define the scatterplot in reg along with the lm fit line.

reg <- function(x, y, ...) {
  points(x,y, ...)
  abline(lm(y~x)) 
  }# made to draw regression line instead of lowess line

panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...)
{
  usr <- par("usr"); on.exit(par(usr = 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)
  text(0.5, 0.5, txt, cex = 1.1, font = 4)
}
#EXAMPLE OF USE:
pairs(USJudgeRatings[1:5], upper.panel = reg, # replace HERE for panel.smooth #
      cex = 1.5, pch = 19, col = adjustcolor(4, .4), cex.labels = 2, font.labels = 2, lower.panel = panel.cor)

enter image description here

like image 43
emilliman5 Avatar answered Sep 14 '25 16:09

emilliman5