I'm trying to vertically align several ggplots
, including one that must be square (using coord_fixed or any other means). I also want to be able to control the relative heights of the different plots. The desired plot look would like this, the number of rectangular: (wanted plot). The number of rectangular plots beneath the square one can vary from 1 to 5.
I've read other SO threads, including this one (Vertically align of plots of different heights using cowplot::plot_grid() when using coord_equal()).
So far: I can align plots, including with one that is square (with egg
or patchwork
) but I don't manage to adjust the relaive heights of the panels.
Below is what I tried (using cowplot
, egg
or patchwork
packages).
Using coord_fixed
#data
a = data.frame(x = seq(0,10), y = seq(10,20), z = runif(11))
b = data.frame(x = seq(0,10), y = runif(11))
#generate ggplot
library(ggplot2)
p1 = ggplot(a, aes(x = x, y = y, fill = z)) + geom_raster() + coord_fixed()
p2 = ggplot(b, aes(x = x, y = y)) + geom_line()
#align with cowplot => alignment not working if p1 is squared.
library(cowplot)
plot_grid(p1,p2,p2, ncol = 1, align = 'v', axis = 'lr')
#align with patchwork => working with p1 squared, but can't control the relative heights
library(patchwork)
p1 + p2 + p2 + plot_layout(nrow = 3) #aligned, p1 being square
p1 + p2 + p2 + plot_layout(nrow = 3,
heights = c(3, 1, 1)) #not aligned
#same, it does not seem to work with egg.
library(egg)
egg::ggarrange(p1, p2, p2, ncol = 1)
egg::ggarrange(p1, p2, p2, ncol = 1, heights = c(3,1,1))
--
A alternative strategy would be to not use coord_fixed for p1, play with the export file dimensions and export at the "right" dimensions
p1bis = ggplot(a, aes(x = x, y = y, fill = z)) + geom_raster()
plot_grid(p1bis,p2,p2, ncol = 1, align = 'v', axis = 'lr', rel_heights = c(4,1,1))
ggsave("temp.pdf", width = 18, height = 24.5, units = "cm")
But I'm not clear on how to calculate the width:height ratio of the export PDF document in a dynamic manner. Is there a way to extract (in npc units?) the width and height of the panel.border?
--
I also came across the ggh4x
package, which, like egg, contains a function to set the panel size. But the panelsize information seems to be lost when combining with patchwork
library(ggh4x)
p1f = p1bis + force_panelsizes(rows = unit(10, "cm"), cols = unit(10, "cm"))
p2f = p2 + force_panelsizes(cols = unit(10, "cm"), rows = unit(3, "cm"))
p1f + p2f + p2f + plot_layout(nrow = 3)
Do you have any other ideas? Am I missing something trivial somewhere?
Thanks for your time !
The case of fixed aspects plots is described on the {patchwork} website:
In your case one way to do it, would be to nest the plots:
Created on 2021-05-11 by the reprex package (v0.3.0)
This gives no fine tuned control over the heights, but we could adjust the nested plots using
plot_spacer()
s:Created on 2021-05-11 by the reprex package (v0.3.0)