3

I have 12 plots generated by a loop and I want to plot them with 3 rows and 2 columns on one page (2 pages in total). I know how to do it in R

pdf("1.pdf")
par(mfrow = c(3, 2))
for (i in 1:12) {
  x <- 1:10
  y <- 2*x + rnorm(x)
  plot(x, y)
}
dev.off()

But how to do this using ggplot?

library(ggplot2)
library(grid)
library(gridExtra)
for (i in 1:12) {
  x <- 1:10
  y <- 2*x + rnorm(x)
  qplot(x, y)
}

I think I have to use grid.arrange but need some help on that. Thanks.

Mike Wise
  • 22,131
  • 8
  • 81
  • 104
JACKY88
  • 3,391
  • 5
  • 32
  • 48

2 Answers2

5

You might want to take a look at the cowplot package that allows more flexibility than just using a naked grid.arrange.

This works - albeit a bit inelegantly:

library(ggplot2)
library(grid)
library(gridExtra)
lg <- list()
for (i in 1:12) {
  x <- 1:10
  y <- 2*x + rnorm(x)
  lg[[i]] <- qplot(x, y)
}
grid.arrange(lg[[1]],lg[[2]],lg[[3]],lg[[4]],lg[[5]],lg[[6]],nrow=3,ncol=2)
grid.arrange(lg[[7]],lg[[8]],lg[[9]],lg[[10]],lg[[11]],lg[[12]],nrow=3,ncol=2)

Another more elegant but somewhat obtuse way to do the grid.arrange is the following (thanks to Axeman and beetroot - note the comments).

do.call(grid.arrange, c(lg[1:6], nrow = 3))
do.call(grid.arrange, c(lg[7:12], nrow = 3))

or this:

grid.arrange(grobs = lg[1:6], ncol=2)
grid.arrange(grobs = lg[7:12], ncol=2)

They all result in this - (think two of these - they look the same anyway):

enter image description here

Mike Wise
  • 22,131
  • 8
  • 81
  • 104
  • You could do `do.call(grid.arrange, c(lg[1:6], nrow = 3))` and `do.call(grid.arrange, c(lg[7:12], nrow = 3))` – Axeman Feb 19 '16 at 12:35
  • s. [here](http://stackoverflow.com/questions/32461259/multiple-ggplots-on-one-page-using-a-for-loop-and-grid-arrange) about grid.arrange using a list: `grid.arrange(grobs = lg[1:6], ncol=2)` – erc Feb 19 '16 at 12:35
  • 1
    I am also thinking he might like `cowplot` better. – Mike Wise Feb 19 '16 at 12:35
  • Ok, thanks @Axeman and beetroot. Was surprised I got this in there, it hung around for 26 minutes before I noticed it. :) I will add those as comments as I think the way it is is more didactic. – Mike Wise Feb 19 '16 at 12:38
2

marrangeGrob is a convenient wrapper for multiple pages,

marrangeGrob(lg, ncol=2, nrow=3)

or you can call grid.arrange() explicitly twice,

grid.arrange(grobs = lg[1:6], ncol=2)
grid.arrange(grobs = lg[7:12], ncol=2)
baptiste
  • 75,767
  • 19
  • 198
  • 294