Left align two graph edges (ggplot)
I wanted to generalize this for any number of plots. Here is a step-by-step solution using the approach by Baptiste:
plots <- list(A, B, C, D)
grobs <- list()
widths <- list()
collect the widths for each grob of each plot
for (i in 1:length(plots)){
grobs[[i]] <- ggplotGrob(plots[[i]])
widths[[i]] <- grobs[[i]]$widths[2:5]
}
use do.call to get the max width
maxwidth <- do.call(grid::unit.pmax, widths)
asign the max width to each grob
for (i in 1:length(grobs)){
grobs[[i]]$widths[2:5] <- as.list(maxwidth)
}
plot
do.call("grid.arrange", c(grobs, ncol = 1))
Try this,
gA <- ggplotGrob(A)
gB <- ggplotGrob(B)
maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
gA$widths[2:5] <- as.list(maxWidth)
gB$widths[2:5] <- as.list(maxWidth)
grid.arrange(gA, gB, ncol=1)
Edit
Here's a more general solution (works with any number of plots) using a modified version of rbind.gtable
included in gridExtra
gA <- ggplotGrob(A)
gB <- ggplotGrob(B)
grid::grid.newpage()
grid::grid.draw(rbind(gA, gB))