patchwork icon indicating copy to clipboard operation
patchwork copied to clipboard

Unable to collect X axes in Patchwork

Open skuchukh opened this issue 8 months ago • 2 comments

Hello! I'm trying to create a common axes for 4 plots with the same dimentions. The below does not work

(p1 | p2) / (p3 | p4) +
  plot_layout(guides = "collect", 
              axes = "collect_x") 

However below works just fine.


(p1 | p2)  +
  plot_layout(guides = "collect", 
            axes = "collect_x")

Any advice would be most appreciated!

skuchukh avatar May 11 '25 19:05 skuchukh

The issue is most likely due to the nested layout. From my understanding, patchwork will only collect axes on the top level of the patch. A possible workaround would be to use wrap_plots. (Note: If that does not work for you, you might consider providing a minimal reproducible example.)

library(ggplot2)
library(patchwork)

p <- ggplot(mtcars, aes(mpg, hp, color = factor(cyl))) +
  geom_point()

p1 <- p2 <- p3 <- p4 <- p

(p1 | p2) / (p3 | p4) +
  plot_layout(
    guides = "collect",
    axes = "collect_x"
  ) &
  plot_annotation(title = "Does not work")


# Note: plot_layout not required as wrap_plots has guides= and axes= too
wrap_plots(
  p1, p2, p3, p4,
  nrow = 2, ncol = 2,
  guides = "collect",
  axes = "collect_x"
) +
  plot_annotation(title = "Works")

trekonom avatar May 17 '25 06:05 trekonom

Thank yo us much! your suggestion worked perfectly!

skuchukh avatar May 18 '25 12:05 skuchukh