I am trying to combine two ggplot objects using cowplot::plot_grid()
and vertically align them. This is normally quite simple using align = "v"
.
dat1 <- data.frame(x = rep(1:10, 2), y = 1:20)
dat2 <- data.frame(x = 1:10, y = 1:10)
plot1 <- ggplot(dat1, aes(x = x, y = y)) + geom_point()
plot2 <- ggplot(dat2, aes(x = x, y = y)) + geom_point()
cowplot::plot_grid(plot1, plot2, ncol = 1, align = "v")
However, this approach fails when the ggplots use coord_equal()
because plot_grid()
cannot modify the axes when the aspect ratio is forced. Instead, the default is to keep the heights of each plot the same.
plot1 <- ggplot(dat1, aes(x = x, y = y)) + geom_point() + coord_equal()
plot2 <- ggplot(dat2, aes(x = x, y = y)) + geom_point() + coord_equal()
cowplot::plot_grid(plot1, plot2, ncol = 1, align = "v")
I can force my objective by playing with and getting the rel_heights
argument just right, but this is not a viable solution as I have many, dynamic plots to build. Here, the y-axes are aligned, and the coordinates of all axes are still equal.
cowplot::plot_grid(plot1, plot2, ncol = 1, align = "v", rel_heights = c(2, 1.07))
I've seen many approaches to similar questions that utilize ggplot2::ggplotGrob()
and grid::grid_draw()
, but nothing quite gets at this issues when coord_equal()
is used. Perhaps the best solution doesn't use cowplot::plot_grid()
at all, or perhaps the solution is somehow dynamically determining and passing the right values to rel_heights
. I think I would prefer the later option so as to be able to easily use the other features that come with cowplot::plot_grid()
. Perhaps some useful inspiration can be found in this related approach.
egg::ggarrange(plot1, plot2)
the sort of thing you want? – Formicaryegg::ggarrange(plot1, plot2, ncol = 1)
and it does indeed do the vertical alignment, but the y-axis coordinates are not maintained as equal to that of the x-axis. The y-axis gets stretched a bit in the top plot. Also, I can't seem to findegg
on github anymore - worries me that it might not be maintained anymore. – Saviouregg
doesn't develop on github, but the library is well maintained at this time. – Feudatory