I am attempting to use grobs and gtable to arrange 4 (ggplot2) plots into a 2x2 grid. I don't know how to set widths, and also a non- 1xn, or nx1 arrangement.
Using this code:
data(iris)
a <- ggplot(iris, aes(x=Species, y=Petal.Width)) + geom_boxplot(color="black") + ylab(expression(Foo~Bar~(g~cm^{-3})))
b <- ggplot(iris, aes(x=Species, y=Petal.Length*100)) + geom_boxplot(color="black") + ylab("foobar (mm)")
c <- ggplot(iris, aes(x=Species, y=Sepal.Width)) + geom_boxplot(color="black") + ylab("foobar (%)")
d <- ggplot(iris, aes(x=Species, y=log10(Sepal.Length))) + geom_boxplot(color="black") + ylab("foobar (cm)")
plots <- list(a,b,c,d)
grobs = lapply(plots, ggplotGrob)
g = do.call(rbind, c(grobs, size="first"))
g$widths = do.call(unit.pmax, lapply(grobs, "[[", "widths"))
grid.newpage()
grid.draw(g)
I can create the following 1x4 arrangement.
If I use grid.arrange for two columns, on the 4 plots, the plots are of different widths.
How can I bind plots into a gtable for a 4 x 4 arrangement?
# I thought maybe I could cbind, then rbind, but this does not work
plots1 <- list(a,b)
plots2 <- list(c,d)
grobs1 = lapply(plots1, ggplotGrob)
grobs2 = lapply(plots2, ggplotGrob)
g1 = do.call(cbind, c(grobs1, size="first"))
g2 = do.call(cbind, c(grobs2, size="first"))
# g3 = do.call(rbind, c(g1,g2, size="first")) #this does not work
would this work for you
I think you already had the answer.
Your last line returns an error, but a small edit results in a combined plot where widths within columns are the same:
g3 = do.call(rbind, c(list(g1,g2), size="first")) #combine g1 and g2 into a list
A sidenote for aesthetics/reference:
If your x-axis is the same, you can drop it from the top two plots.
These StackOverflow questions are helpful in aligning plots:
rbind
in gtable to set plot width (Baptiste) [link]Pretty similar to the above, but using gtable functions*
*: actually, since gtable doesn't allow the use of pmax when comparing units, this is using a drop-in replacement from the dev version of gridExtra.