Reputation: 35
I want to have two facet_grid plots side by side, one with 3 rows and another with 2 using ggplot2
in R. By default grid.arrange
tries to maintain the equal height of two facet_grids
however, I want to have equal panel height for both plots.Particularly I want to adjust the panel height of plot with least number of rows to be equal to the panel height of the plot with maximum number of rows. I don't think it should be quite complicated. Am I missing some common idea here? Since I am newbie to R any help would be kindly appreciated Thank you!
A reproducible example is here:
library(tidyverse)
library(gridExtra)
mtcars
p1 <- ggplot(mtcars,aes(x =mpg,y = disp,fill=cyl))+
geom_point()+
facet_grid(rows=vars(gear),cols=vars(cyl),scales = "free")
p2 <- ggplot(mtcars,aes(x =mpg,y = disp,fill=cyl))+
geom_point()+
facet_grid(rows=vars(am),cols=vars(cyl),scales = "free")
grid.arrange(p1,p2,ncol=2)
which produces
I want to have p2 have panel height as of p1 and use the bottom empty space from p2 (right) for the legend the remaining space empty. And yes I have to maintain scale to be free.
Upvotes: 2
Views: 426
Reputation: 435
not very elegant, but you can perhaps draw an empty rectangle, combine it vertically with your p2
and then combine with p1
:
library(grid)
empty_panel <- grid.rect(gp=gpar(col="white"))
p2t <- grid.arrange(p2,empty_panel,ncol=1, heights=c(0.7,0.3))
grid.arrange(p1,p2t,ncol=2)
If you want the extra space to be used to place, for example, your legend, an option could be to play with legend.position
and plot.margin
:
p2 <- ggplot(mtcars,aes(x =mpg,y = disp,fill=cyl))+
geom_point()+
facet_grid(rows=vars(am),cols=vars(cyl),scales = "free")+
theme(plot.margin= unit(c(0, 0, 4, 0), "cm") ,legend.position = c(0.5, -0.3))
grid.arrange(p1,p2,ncol=2)
some manual adjustment is required.
Upvotes: 1