Aligning y-axes of gtable and regular ggplot objects

56 Views Asked by At

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.

2

There are 2 best solutions below

0
stefan On BEST ANSWER

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

0
Peter On

An approach using grid and gridExtra

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


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()


lab <- textGrob(label = 'some label for top two', rot = 90)

a <- ggplotGrob(a)
b <- ggplotGrob(b)
c <- ggplotGrob(c)

grid.arrange(lab, a, b, c, layout_matrix = cbind(c(1,1,5),c(2,3,4)), widths = c(1, 30))

Created on 2023-06-20 with reprex v2.0.2