4

I would like to generate a pdf document, using R markdown, to display a series of plots made using ggplot in a for loop. Is it possible to control number of plots on each page so there is, for example, a 2 X 2 grid of plots per page?

I'd like to maintain the flexibility so that I can change the total number of graphs, so that it splits across the appropriate number of pages.

My attempt using ggplot2 and gridExtra packages is below, but I can't control the number of graphs per page, it seems to want to squeeze them on to a sinlge page only. I've tried changing the ncol,nrow,heights,widths arguments in grid.arrange but it doesn't seem to help.

    ---
    title: "ggplot Layout"
output: pdf_document
    ---

    ```{r,figure2 fig.height=8, fig.width=6,echo=FALSE,message=FALSE}


    library(ggplot2)
    library(gridExtra) 

    graphlist<-list()
    count <- 1
    colnums<-c(1,5,6,7,8,9,10)

    for (i in colnums) {
    plot.x.name<-names(diamonds[i])
    p <- ggplot(data=diamonds,aes_string(x = plot.x.name)) + geom_histogram() 
    graphlist[[count]]<-p
    count <- count+1

    }

    do.call("grid.arrange",c(graphlist,ncol=2))



    ```

The type of thing I'm looking for is demonstrated by this code (adapted from http://kbroman.github.io/knitr_knutshell/pages/figs_tables.html), but this doesn't work with ggplot, unfortunately.

---
title: "Example Layout"
output: pdf_document
---


```{r bunch_o_figs,fig.height=8, fig.width=6, message=FALSE,echo=FALSE}
n <- 100
x <- rnorm(n)
par(mfrow=c(2,2), las=1)
for(i in 1:20) {
  y <- i*x + rnorm(n)
  plot(x, y, main=i)
}
``
Damian
  • 516
  • 1
  • 4
  • 20

1 Answers1

6

You could try marrangeGrob

---
title: "ggplot Layout"
output: pdf_document
---

```{r figure2 , fig.height=8, fig.width=6,echo=FALSE,message=FALSE}


    library(ggplot2)
    library(gridExtra) 

    graphlist <- replicate(10, qplot(1,1), simplify = FALSE)

    do.call("marrangeGrob",c(graphlist,ncol=2,nrow=2))
```
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • 1
    Thanks, that works exactly as wanted. One thing that was/is causing me some confusion is that when I try to decrease the size of the page margins (by adding "geometry:margin=0.5in" to the front matter of the markdown), the plot arrangement changes and some of the graphs end up off the page. – Damian Jul 08 '14 at 21:14
  • I observed the same behaviour. As soon as the geometry settings are changed in the yaml header the plots are drawn on one page instead if multiple pages. Thus, all graphs except the first one tend to end up off the page. – alexander keth Apr 13 '16 at 15:34