I\'m using ggplot and have two graphs that I want to display on top of each other. I used grid.arrange
from gridExtra to stack them. The problem is I want the
I know this is an old post, and that it has already been answered, but may I suggest combining @baptiste's approach with purrr
to make it nicer-looking:
library(purrr)
list(A, B) %>%
map(ggplotGrob) %>%
do.call(gridExtra::gtable_rbind, .) %>%
grid::grid.draw()
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))
The patchwork package handles this by default:
library(ggplot2)
library(patchwork)
A <- ggplot(CO2, aes(x = Plant)) + geom_bar() + coord_flip()
B <- ggplot(CO2, aes(x = Type)) + geom_bar() + coord_flip()
A / B
Created on 2019-12-08 by the reprex package (v0.3.0)