A_DK A_DK - 6 months ago 48
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:

Scatterplot matrix


you can try the following:

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

example with mtcars dataset:


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, ...)


enter image description here