Controlling the size and number of graphs per pdf page generated by ggplot loop in R markdown
ggplot2, gridextra, knitr, pandoc, r
Solution
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))
`
Problem
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) } `` ````