thomasp85 / patchwork

The Composer of ggplots
https://patchwork.data-imaginist.com
Other
2.42k stars 157 forks source link

Layout when one plot has exceptionally tall labels? #323

Closed bbimber closed 11 months ago

bbimber commented 1 year ago

Hello,

I have a layer where I'd like to align 3 plots. One of the plots has exceptionally tall x-axis labels. The layout is:

patchwork::plot_layout(design = 'ACC\nBCC') 

You will see in the bottom-left there is wasted whitespace. Is there a way to get patchwork to align the left two plots such that they take up the entire vertical space? Thanks for any help.

image

thomasp85 commented 11 months ago

You are correct that the reasons are the x-axis text. patchwork in general will try to align axes. In case this is not what you want you have to treat the left-hand side as a single plot using the wrap_elements() function.

Some fiddling must be done to remove the margin around the left-hand patchwork so the top of the two plots aligns

e.g. this doesn't look nice at the top:

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp)) + 
  ggtitle('Plot 1')

p2 <- ggplot(mtcars) + 
  geom_boxplot(aes(gear, disp, group = gear)) + 
  ggtitle('Plot 2')

p3 <- ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3') + theme(axis.text.x = element_text(size = 30))

wrap_elements(full = p1 / p2) | p3

Created on 2023-08-07 by the reprex package (v2.0.1)

however, removing the margin around the two stacked plots makes it all looks better but is a bit more fiddly

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + 
  geom_point(aes(mpg, disp)) + 
  ggtitle('Plot 1')

p2 <- ggplot(mtcars) + 
  geom_boxplot(aes(gear, disp, group = gear)) + 
  ggtitle('Plot 2')

p3 <- ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3') + theme(axis.text.x = element_text(size = 30))

wrap_elements(full = p1 / p2 + plot_annotation(theme = theme(plot.margin = margin()))) | p3

Created on 2023-08-07 by the reprex package (v2.0.1)