Uneven widths/ heights in patchwork when number of plots is less than ncol x nrow

23 Views Asked by At

I am trying to plot a large list of plots using patchwork to multiple pages with the same layout as specified by ncol and nrow arguments.

But the widths and heights are not unifrom across pages when the number of plots is less than the number of regions in the ncol x nrow grid.

How to get the same widths and heights when number of plots is less than ncol x nrow ?

Widths in page1 and page 2 are different

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + geom_point(aes(mpg, disp))

wrap_plots(p1, p1, p1, p1, p1, p1, ncol = 3, nrow = 2) + 
  patchwork::plot_annotation(title = "page1") &
  theme(plot.background = element_rect(fill = 'grey'))

wrap_plots(p1, p1, ncol = 3, nrow = 2) + 
  patchwork::plot_annotation(title = "page2") &
  theme(plot.background = element_rect(fill = 'grey'))

Heights in page1 and page 2 are different


wrap_plots(p1, p1, p1, p1, p1, p1, ncol = 2, nrow = 3)  + 
  patchwork::plot_annotation(title = "page1") &
  theme(plot.background = element_rect(fill = 'grey'))


wrap_plots(p1, p1, ncol = 2, nrow = 3)  + 
  patchwork::plot_annotation(title = "page2") &
  theme(plot.background = element_rect(fill = 'grey'))

Created on 2024-02-23 with reprex v2.1.0

1

There are 1 best solutions below

0
stefan On BEST ANSWER

One option would be to fill up the list of plots for the second page with empty plots using plot_spacer() and importantly to wrap all plots in free() (requires patchwork >= 1.2.0):

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) +
  geom_point(aes(mpg, disp))

page1 <- replicate(6, p1, simplify = FALSE)
page2 <- c(
  replicate(2, free(p1), simplify = FALSE),
  replicate(4, free(
    plot_spacer() +
      # Remove plot border
      theme(plot.background = element_rect(color = NA))
  ), simplify = FALSE)
)

page1 |>
  wrap_plots(nrow = 2) +
  patchwork::plot_annotation(title = "page1") &
  theme(plot.background = element_rect(fill = "grey"))


page2 |>
  wrap_plots(
    nrow = 2
  ) +
  patchwork::plot_annotation(title = "page2") &
  theme(plot.background = element_rect(fill = "grey"))


page1 |>
  wrap_plots(nrow = 3) +
  patchwork::plot_annotation(title = "page1") &
  theme(plot.background = element_rect(fill = "grey"))


page2 |>
  wrap_plots(
    nrow = 3
  ) +
  patchwork::plot_annotation(title = "page2") &
  theme(plot.background = element_rect(fill = "grey"))