I'm trying to stack multiple plots that are combined in a list and are coming from purrr::map
.
The conditions are:
- no use of
facet_wrap
orfacet_grid
- I understand this can be done with these function but I have another limiting factor which does not allow for their use - the number of plots in the list might vary - so it is not a constant
A reproducible example to recreate the problem:
library(dplyr)
library(tidyr)
library(purrr)
# a sample dataframe
df <- data.frame(gr = c(1, 1, 1, 2, 2, 2, 3, 3, 3, 3),
a = rnorm(10, 5, 3),
b = rnorm(10, 5, 3)) %>%
group_by(gr) %>%
nest()
# a plotting function
plotting <- function(x) {
ggplot(x) + geom_point(aes(a,b))
}
# getting the list of the plots
lst <- map(df$data,plotting)
I can solve the problem manually by using the patchwork
package:
library(patchwork)
lst[[1]] + lst[[2]] + lst[[3]] + patchwork::plot_layout(nrow = 1)
or the gridExtra
package:
library(gridExtra)
grid.arrange(lst[[1]], lst[[2]], lst[[3]],nrow = 1)
but if the number of plots varies this would not work. Grateful for any ideas on how to automate this.