Home > Back-end >  Control size of subplots created with patchwork - code improvement
Control size of subplots created with patchwork - code improvement

Time:01-27

I want to make a multipanel figure containing multiple labeled plots. My plots are produced in ggplot2 & I would like to arrange them with patchwork.

I want to combine two subplots in the first row, followed by two other plots arranged one plot per row:

  • plot3 plot4 - both in row #1
  • plot1 - in row #2
  • plot2 - in row #3

Here is a dummy example to illustrate the problem:

```{r, fig.width=10, fig.height=13}
library(ggplot2)
library(patchwork)

#Dummy plots
plot1 <- ggplot2::ggplot(data = mpg, aes(x = class, fill=drv))  
  geom_bar(aes(y = ..count..))   ggplot2::ggtitle("Plot1")
plot2 <- ggplot2::ggplot(data = mpg, aes(x = displ, y = hwy, color=class))  
  geom_point()  ggplot2::ggtitle("Plot2")
plot3 <- ggplot2::ggplot(data = mpg, aes(x = cty))  
  geom_density()  ggplot2::ggtitle("Plot3")
plot4 <- ggplot2::ggplot(data = mpg, aes(x = cty, y=drv, fill = fl))  
  geom_col()  ggplot2::ggtitle("Plot4")

# this works, but it is not the desired layout
final <- plot1   plot2   {plot3   plot4   patchwork::plot_layout(ncol=2)}   
  patchwork::plot_layout(ncol=1,heights = unit(c(4, 7, 2),c('cm')))
plot(final)

#this does not work
final2 <- {plot3   plot4   patchwork::plot_layout(ncol=2)}   plot1   plot2   
  patchwork::plot_layout(ncol=1, heights = unit(c(2, 4, 7),c('cm')))
print(final2)

```

This is the output I can produce, but this is not what I want:

enter image description here

And this is the picture I would like to obtain:

enter image description here

Some of my other attempts:

#this does not work either
up_patch <- plot3   plot4   patchwork::plot_layout(ncol=2)

final2 <- up_patch   plot1   plot2   patchwork::plot_layout(ncol=1, heights = unit(c(2, 4, 7),c('cm')))
print(final2)


#and this as well
up_patch <- plot3   plot4   patchwork::plot_layout(ncol=2, heights= unit(2,c('cm')))
bottom_patch <- plot1   plot2   patchwork::plot_layout(ncol=1, heights = unit(c(4, 7),c('cm')))

final2 <- up_patch   bottom_patch
print(final2)

# THIS WORKS but needs improvement
final_desired <- (plot3 | plot4) / plot1   plot2

print(final_desired)

In the last attempt I was able to produce the desired layout, however I would like to be able to control the dimensions of the subplots as in my dummy example in the beginning of this post). It is important for me to adjust the image size to the size of the page.

I would also like to know how to use a namespace qualifier while calling patchwork in the working example, so I would not call a function from another package by an accident.

I followed the instructions from these sources:

enter image description here

  • Related