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 left edges of the graphs to align as well as the right edges regardless of axis labels. (the problem arises because the labels of one graph are short while the other is long).
The Question:
How can I do this? I am not married to grid.arrange but the ggplot2 is a must.
What I've tried:
I tried playing with widths and heights as well as ncol and nrow to make a 2 x 2 grid and place the visuals in opposite corners and then play with the widths but I couldn't get the visuals in opposite corners.
require(ggplot2);require(gridExtra)
A <- ggplot(CO2, aes(x=Plant)) + geom_bar() +coord_flip()
B <- ggplot(CO2, aes(x=Type)) + geom_bar() +coord_flip()
grid.arrange(A, B, ncol=1)
At best this is a hack:
It feels really wrong though.
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:I wanted to generalize this for any number of plots. Here is a step-by-step solution using the approach by Baptiste:
collect the widths for each grob of each plot
use do.call to get the max width
asign the max width to each grob
plot
The
egg
package wraps ggplot objects into a standardised3x3
gtable, enabling the alignment of plot panels between arbitrary ggplots, including facetted ones.Try this,
Edit
Here's a more general solution (works with any number of plots) using a modified version of
rbind.gtable
included ingridExtra
On http://rpubs.com/MarkusLoew/13295 is a really easy solution available (last item) Applied to this problem:
you can also use this for both width and height: