4
votes

I am trying to create a lot of plots (simple x-y bar graphs) that I would like to display in the form of a grid. When I use the gridExtra package's grid.arrange, as the number of plots grow, each individual plot shrinks. Is there a way to create the plot canvas so that it spans over multiple pages without shrinking each individual plot?

A simple example from gridExtra:

require(ggplot2)
require(gridExtra)
plots = lapply(1:50, function(.x) qplot(1:10,rnorm(10),main=paste("plot",.x)))
do.call(grid.arrange,  plots)

The above code generates 50 plots but they get shrunk to fit the canvas. Is there a way to avoid that? i.e., make them span over multiple pages and each page will have about say 9 or so plots? I am ok with PNG or PDF file formats.

Before trying grid.arrange, I played around with the code sample from this site: http://gettinggeneticsdone.blogspot.com/2010/03/arrange-multiple-ggplot2-plots-in-same.html and ran into the same issue.

I have not yet tried combining the different data frames into one giant data frame with a plot identifier. Then I was thinking of faceting with the plot identifier but I am not sure if it will also have the same issue of shrinking each plot.

Hope my question is clear...

Thanks, -e

1
Can you you faceting? You can make a new faceting variable in groups of nine and make a multi-page pdf out of it.Chase
@Andrie, Thanks! I was looking for the wrong keywords and didn't spot that link. Using pdf() and printing inside the loops works great. I will put that pseudo code in the answer. @Chase, that's very good idea. For my situation, I was not storing things in a data frame and so I just printed it directly to the pdf inside the loop. If I had a rolled-up data frame, your suggestion will work better as I wouldn't need grid.arrange. Thanks!Ecognium

1 Answers

8
votes
library(gridExtra)
library(ggplot2)
my_func = function (d,filename = "filename.pdf") {
    pdf(filename,width=14) # width = 14 inches
    i = 1
    plot = list() 
    for (n in names(d)) {
        ### process data for plotting here ####
        plot[[i]] = qplot(x, y, geom="bar", data = my_data,)
        if (i %% 9 == 0) { ## print 9 plots on a page
            print (do.call(grid.arrange,  plot))
            plot = list() # reset plot 
            i = 0 # reset index
        }
        i = i + 1
    }
    if (length(plot) != 0) {  ## capture remaining plots that have not been written out
        print (do.call(grid.arrange,  plot))
    }
    dev.off()
}