Specify widths and heights of plots with grid.arrange

Chika picture Chika · Mar 24, 2016 · Viewed 80k times · Source

I have three plots and I try to combine them with grid.arrange. The last plot should have a smaller height than the first two plots and all the plots should have the same width.

A working example:

p1 <- qplot(mpg, wt, data=mtcars)
p2 <- p1
p3 <- p1 + theme(axis.text.y=element_blank(), axis.title.y=element_blank())

grid.arrange(arrangeGrob(p1,p2, ncol=1, nrow=2),
         arrangeGrob(p3, ncol=1, nrow=1), heights=c(4,1)) 

enter image description here

Here, the last plot has a larger width than the first two. In my real data, even if I keep the text and the title on the y-axis, I still have a different width for the third plot.

I tried to add "widths":

 grid.arrange(arrangeGrob(p1,p2, ncol=1, nrow=2),
         arrangeGrob(p3, ncol=1, nrow=1), heights=c(4,1), widths=c(2,1))

But it turns into a two column plot...

enter image description here

I also tried another code:

p1 <- ggplotGrob(p1)
p2 <- ggplotGrob(p2)
p3 <- ggplotGrob(p3)
# 
stripT <- subset(p2$layout, grepl("spacer", p2$layout$name))
p3 <- p3[-stripT$t, ]

grid.draw(rbind(p1, p2, p3, size = "first")) 

I have the same widths but now I don't know how to change the heights...

enter image description here

Well, can someone help me to combine both the height and width aspects for a final plot?

Answer

lukeA picture lukeA · Mar 24, 2016

Try plot_grid from the cowplot package:

library(ggplot2)
library(gridExtra)
library(cowplot)
p1 <- qplot(mpg, wt, data=mtcars)
p2 <- p1
p3 <- p1 + theme(axis.text.y=element_blank(), axis.title.y=element_blank())
plot_grid(p1, p2, p3, align = "v", nrow = 3, rel_heights = c(1/4, 1/4, 1/2))

enter image description here