Search code examples
rlistplotlapplycowplot

R rbind and display multiple plot()


I am fitting several simple linear regression models

data("mtcars")
head(mtcars)

mtcars_lm <- plyr::dlply(mtcars,
                           "cyl",
                             function(x) 
                                lm(mpg ~ hp + wt + cyl, data =x, na.action = na.omit))

I can plot the diagnostics plot from these model fits individually like this.

par(mfrow = c(3,4), mar = c(1,1,1,1)
plot(mtcars_lm[[1]], las = 1, pch=20, cex=1)
plot(mtcars_lm[[2]], las = 1, pch=20, cex=1)
plot(mtcars_lm[[3]], las = 1, pch=20, cex=1)

I am trying to make the plotting more efficient by

  1. calling plot() iteratively for each lm() fit object.
  2. Store the output from plot() in an object
  3. rbind the plot() objects
  4. Display all the three plot() from each of the lm() fit , rowwise.

Not necessary in this order but my main objective is to generate these diagnostic plots more efficiently instead of doing this manually one by one for each model.

The end goal is something like this. Any suggestions or help is much appreciated. Thanks. enter image description here


Solution

  • You could use walk() from {purrr}, and set a 3 x 4 grid:

    par(mfrow=c(3,4))
    purrr::walk(.x = mtcars_lm, .f = ~plot(.x, las = 1, pch=20, cex=1))
    

    giving:

    grid of plots