Combining plots from a for loop? Use patchwork?

I have a loop that produces multiple plots. The Minimal reprex below produces 5 plots. How can I combine all plots into one single plot - with 1 row? I think this would be like using patchwork like:
p1 / p2 / p3 / p4 / p5

How can I combine them into one plot

library(ggplot2)
library(patchwork)
mylist <- list()
mtcars_short <- mtcars[1:5,]
for(i in 1:nrow(mtcars_short)){
  mydf <- mtcars[i,]
  p <- ggplot(mydf, aes(x=mpg, y=carb)) + geom_point()
  
  mylist[[i]] <- p
}

EDIT to mention that my real example has ~50 plots in a list. Can I use some method (grid.arrange /patchwork/etc) to make sure the plots are the exact same dimensions as stand-alone versions, but just all stacked on top of one another? I think in the past I've seen that combining ggplots from a list will squish everything down to an unreadable size.

You can get that with patchwork::wrap_plots(mylist, nrow = 1). You will have the "squishing" problem, because you are limited by the size of your graphical device. An easy workaround is if you intend to save your plot, you can explicitly choose the width of the combined plot:

nb_plots <- length(mylist)
basewidth <- grDevices::dev.size(units = "px")[1]
ggsave("test.png",
       width = nb_plots*basewidth,
       units = "px")

Whether it's a good idea to combine 50 plots in one gigantic row is a different question.

Do you mean like this?

myplot <- patchwork::wrap_plots(mylist, nrow=1)

nb_plots <- length(mylist)
basewidth <- grDevices::dev.size(units = "px")[1]
ggsave("test.png",
       myplot, #What to save
       width = nb_plots*basewidth,
       units = "px")

Would that just make it a super wide plot? Do I just change it to height ?

Thanks!

Yes, it would. Sorry, I thought that was what you were asking for?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.