All of the patchwork documentation describes building a plot with p1+p2+p3+p4 (or p1 | p2 | ...)
I would like to build a patchwork plot from a list of ggplot objects, where I do not know the number of plots in advance.
I can make a list of plots, and make the final page with:
final.plot <- p_list[[1]] | p_list[[2]] | p_list[[3]]
But I have not figured out how to make a plot with
final.plot <- NULL
for (i in 1:length(p_list)){
final.plot <- final.plot | p_list[[i]]
}
Is there a way to do this?
To programmatically create a patchwork
from a list
of plots the patchwork
package provides patchwork::wrap_plots()
:
library(ggplot2)
library(patchwork)
p_list <- replicate(4, ggplot(mtcars, aes(hp, mpg)) +
geom_point(), simplify = FALSE)
p_list |>
wrap_plots(ncol = 2, nrow = 2)
Or instead of a for
loop use Reduce
but I don't see any reason to so as we have wrap_plots()
:
p_list |>
Reduce(`|`, x = _) +
plot_layout(ncol = 2, nrow = 2)