I would like to use the patchwork
library to combine plots. but my plots are saved in a list. Consider the code below:
library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) geom_boxplot(aes(gear, disp, group = gear))
plots_list <- list(p1, p2)
if I use
patchwork::wrap_plots(plots_list )
The following figure will be generated in which I won't have any control over the space between plots
However, if I want to add space between plots, I need to run the code below:
p1 plot_spacer() p2 plot_layout(widths = c(6, -1 ,6))
Therefore, I looking for a way to extract plots from the list (plots_list) and then add " " them and combine them in the form above
CodePudding user response:
Create another list and programmatically add plot_spacer()
into the odd indices.
newlist <- vector("list", 2*length(plots_list) - 1)
newlist[seq(1, 2*length(plots_list), by=2)] <- plots_list
newlist[seq(2, 2*length(plots_list)-1, by=2)] <- replicate(length(plots_list)-1, plot_spacer(), simplify = FALSE)
### final plot
widths <- sapply(newlist, function(L) if (inherits(L, "spacer")) -1 else 6)
Reduce(` `, newlist) plot_layout(widths = widths)
CodePudding user response:
A second option would be to use the design
argument, e.g. design="A#B"
will add a spacer between your plots and of course could you do something like paste(LETTERS[seq(length(plots_list))], collapse = "#")
to create the design string programatically.
library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) geom_boxplot(aes(gear, disp, group = gear))
plots_list <- list(p1, p2)
design <- "A#B"
patchwork::wrap_plots(plots_list) plot_layout(widths = c(6, -1, 6), design = design)