A_DK A_DK - 2 months ago 15
R Question

how to insert trendlines in scatterplot matrix

I have made a scatterplot matrix and whish to ad trend lines to each of the plots or just to those of significans.
my R command:
cor(K4Full[,c(6:9,22:25)])
plot(K4Full[,c(6:8,22:25)])

Scatterplot matrix

Answer

you can try the following:

pairs(K4Full[,c(6:8,22:25)], panel=panel.smooth)

example with mtcars dataset:

pairs(mtcars[1:6],panel=panel.smooth)

enter image description here

To fit straight line wth lm:

panel.lm <- function (x, y,  pch = par("pch"), col.lm = "red",  ...) {   
  ymin <- min(y)
  ymax <- max(y)
  xmin <- min(x)
  xmax <- max(x)
  ylim <- c(min(ymin,xmin),max(ymax,xmax))
  xlim <- ylim
  points(x, y, pch = pch,ylim = ylim, xlim= xlim,...)
  ok <- is.finite(x) & is.finite(y)
  if (any(ok)) 
    abline(lm(y[ok]~ x[ok]), 
           col = col.lm, ...)
}

pairs(mtcars[1:6],panel=panel.lm)

enter image description here

Comments