thomasp85 / patchwork

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

Possible bug when adding plot_layout(heights=c(x,x)) #330

Closed smouksassi closed 9 months ago

smouksassi commented 10 months ago

Hi I used to have older code that works as expected but now I am getting white space when using plot_layout and relative heights

library(patchwork)
library(ggplot2)
library(egg)
#> Loading required package: gridExtra
p1 <-   ggplot(mtcars) + geom_boxplot(aes(disp, as.factor(gear), group = gear,fill=as.factor(gear)))+
  theme(legend.position = "top")+
  theme(axis.title.x.bottom = element_blank(),
        axis.text.x.bottom = element_blank(),
        axis.ticks.x =  element_blank() )
p2 <- ggplot(mtcars) + geom_point(aes(y=as.factor(gear),x=disp)) 
p1 /p2 # 1 1 all good

# p1 /p2 &  plot_layout(heights=c(1,1))  # why the extra white space
p1 /p2 &
    plot_layout(heights=c(2.5,1)) # why the extra white space


# The same can be specified as a character string:
design <- "
  11
  11
  22
"
p1+p2+
  plot_layout(design = design) # not sure how we can specify fractional relative height


ggarrange(p1,p2,heights=c(2.5,1)) # works as expected

Created on 2023-09-04 with reprex v2.0.2

teunbrand commented 9 months ago

You're getting weird heights because p2 & plot_layout(...) is evaluated before p1 / p2. The p2 & plot_layout(...) gives the unexpected spacing:

library(ggplot2)
library(patchwork)

p1 <-   ggplot(mtcars) + geom_boxplot(aes(disp, as.factor(gear), group = gear,fill=as.factor(gear)))+
  theme(legend.position = "top")+
  theme(axis.title.x.bottom = element_blank(),
        axis.text.x.bottom = element_blank(),
        axis.ticks.x =  element_blank() )
p2 <- ggplot(mtcars) + geom_point(aes(y=as.factor(gear),x=disp)) 

p2 & plot_layout(heights = c(2.5, 1))

But you can solve this by just using + plot_layout(...):

p1 / p2 +
  plot_layout(heights=c(2.5,1))

Created on 2023-10-18 with reprex v2.0.2

smouksassi commented 9 months ago

thanks @teunbrand I was reusing old code with & I will stick to +

thomasp85 commented 9 months ago

For plot layout + is probably the right operator since you generally only want it applied to the current nesting level. The prime use case for & is for applying themes to all plots in the patchwork