It's relatively simple using grid.arrange
in the gridExtra
package to arrange multiple plots in a matrix, but how can you arrange plots (the ones I'm working on are from ggplot2
) when some plots are intended to be larger than others? In base, I can use layout()
such as in the example below:
nf <- layout(matrix(c(1,1,1,2,3,1,1,1,4,5,6,7,8,9,9), byrow=TRUE, nrow=3)) layout.show(nf)
what is the equivalent for ggplot
plots?
Some plots for inclusion
library(ggplot2) p1 <- qplot(x=wt,y=mpg,geom="point",main="Scatterplot of wt vs. mpg", data=mtcars) p2 <- qplot(x=wt,y=disp,geom="point",main="Scatterplot of wt vs disp", data=mtcars) p3 <- qplot(wt,data=mtcars) p4 <- qplot(wt,mpg,data=mtcars,geom="boxplot") p5 <- qplot(wt,data=mtcars) p6 <- qplot(mpg,data=mtcars) p7 <- qplot(disp,data=mtcars) p8 <- qplot(disp, y=..density.., geom="density", data=mtcars) p9 <- qplot(mpg, y=..density.., geom="density", data=mtcars)
To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used. The basic solution is to use the gridExtra R package, which comes with the following functions: grid. arrange() and arrangeGrob() to arrange multiple ggplots on one page.
Combine multiple ggplot on one page.Use the function ggarrange() [ggpubr package], a wrapper around the function plot_grid() [cowplot package]. Compared to plot_grid(), ggarange() can arrange multiple ggplots over multiple pages.
You can use nested arrangeGrob
calls like this example:
library(ggplot2) library(gridExtra) p <- ggplot(data.frame(x=1, y=1), aes(x,y)) + geom_point() grid.arrange( arrangeGrob( p, arrangeGrob(p, p, nrow=2), ncol=2 ,widths=c(2,1)), arrangeGrob(p, p ,p ,ncol=3, widths=rep(1,3)), nrow=2)
Edit:
gl <- lapply(1:9, function(ii) grobTree(rectGrob(),textGrob(ii))) grid.arrange( arrangeGrob(gl[[1]], do.call(arrangeGrob, c(gl[2:5], ncol=2)), nrow=1, widths=3:2), do.call(arrangeGrob, c(gl[6:9], nrow=1, list(widths=c(1,1,1,2)))), nrow=2, heights=c(2,1))
An alternative with gtable
library(gtable) gl <- lapply(1:9, function(ii) grobTree(textGrob(ii), rectGrob())) # gl <- lapply(1:9, function(ii) ggplotGrob(qplot(1,1) + ggtitle(ii))) gt <- gtable(widths=unit(rep(1,5), "null"), heights=unit(rep(1,3), "null")) gtable_add_grobs <- gtable_add_grob # alias gt <- gtable_add_grobs(gt, gl, l=c(1,4,5,4,5,1,2,3,4), r=c(3,4,5,4,5,1,2,3,5), t=c(1,1,1,2,2,3,3,3,3), b=c(2,1,1,2,2,3,3,3,3)) grid.newpage() grid.draw(gt)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With