Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arranging multiple ggplot2 plots

Tags:

r

ggplot2

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

like image 685
Ecognium Avatar asked Feb 24 '23 03:02

Ecognium


1 Answers

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()
}
like image 113
Ecognium Avatar answered Feb 26 '23 20:02

Ecognium