2

I have a list of ggplot2 plots, and I want to add the same title (Cars to each element of the list

library(ggplot2)
 l <- list(
   ggplot(data = mtcars, aes(x = mpg, y = cyl, col = am)) + geom_point(),
   ggplot(data = mtcars, aes(x = mpg, y = disp, col = am)) + geom_point(),
   ggplot(data = mtcars, aes(x = mpg, y = hp, col = am)) + geom_point()
 )

Now I can refer to each element and add the title as follows

 l[[1]] + ggtitle("Cars")
 l[[2]] + ggtitle("Cars")
 l[[3]] + ggtitle("Cars")

But is there a way to add the title to all elements in the list at once?

(Note: For one layer, this is rather silly, but I can extend such an example to multiple layers.)

phargart
  • 655
  • 3
  • 14

1 Answers1

4

User H 1 answered the question. As ggplot2 is different due to the layering, I was unsure if lapply() would work in this case. I now learned that the pipe symbol, + is a function to be applied over.

But adding a title and positioning the legend at the bottom has the desired effect:

 q <- lapply(l, function(x) x + ggtitle("Cars") + theme(legend.position = "bottom"))
 multiplot( plotlist = q, cols = 2)

where the code for multiplot() is found here.

enter image description here

phargart
  • 655
  • 3
  • 14
  • 2
    FYI, there are several packages that can do a little bit more than `multiplot()` https://stackoverflow.com/a/51220506/786542 – Tung Mar 07 '20 at 02:55