Suwas Ghimire
Suwas Ghimire

Reputation: 35

Equal panel height in different facet_grid plots, ggplot2 R

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

a 3x3 facet plot same size as a 2x3 facet plot

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

Answers (1)

efz
efz

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)

the output looks like enter image description here

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.

the plot will loook like: enter image description here

Upvotes: 1

Related Questions