rggplot2gridgridextra

Aligning y-axes of gtable and regular ggplot objects


I am trying to stack three plots using ggplot where the top two have two rows of y-axis labels and the bottom on just one. In my real-world example (not the code shown below), the top two plots share something in common, so I'm trying to reduce aesthetic redundancy.

Anyway, my approach is shown in the example below. But no matter what I try I can't convince the system to align the y-axes.

If there's a better set of commands/packages than what I am trying, please share! I am not committed to these specific packages.

library(ggplot2); library(grid); library(gridExtra)

d <- mtcars

a <- ggplot(d[d$cyl==4,], aes(x=wt, y=mpg))+
  geom_point()

b <- ggplot(d[d$cyl==6,], aes(x=wt, y=mpg))+
  geom_point()

c <- ggplot(d, aes(x=qsec, y=mpg))+
geom_point()

topTwo <-plot_grid(a, b, ncol = 1, align = "v")
y.grob <- textGrob("some label for top two", gp=gpar(), rot=90)

topTwo <- grid.arrange(arrangeGrob(topTwo, left = y.grob))

plot_grid(topTwo, c, ncol = 1, align='v',axis='lr', rel_heights = c(100,50))

y-axes are not aligned.


Solution

  • Another option would be to use patchwork:

    library(ggplot2)
    library(patchwork)
    
    design <- 
    "
    DA
    DB
    #C
    "
    wrap_plots(list(a, b, c, y.grob), design = design) +
      plot_layout(widths = c(1, 100))
    

    enter image description here