Reputation: 729
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.)
Upvotes: 2
Views: 229
Reputation: 729
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.
Upvotes: 4