-8

I am scratching my head for the following code.

I am following this example:

How can I arrange an arbitrary number of ggplots using grid.arrange?

I wanted to collect the plots and lay them out on a 3x9 grid and each grid with suitable labels...

But it doesn't work. The pdf generated is still one-plot-per-page - so there are 27 pages generated.

I am trying to use "grid.arrange", however, the function "plotFunctionWrittenByOtherPeople" was written by other people, and it doesn't return a handle to the plot... and it's quite complicated.

How to arrange the plots nicely?

Could anybody please shed some lights on this?

Thanks a lot!


pdf("mytry1.pdf", width = 11, height = 8.5)
par(mfrow=c(3, 9))
for (a in seq(100, 900, by=100))
    for (b in c(1, 3, 6))
    {
         plotFunctionWrittenByOtherPeople(a, b)     
    }
dev.off()
Community
  • 1
  • 1
Luna
  • 161
  • 1
  • 5
  • 7
    I'm confused, you say you're following the code in that question, but none of that code appears in your question. And how are we supposed to help with a big complicated function that we don't have the code for? – joran Jul 20 '12 at 01:06

1 Answers1

13

I think that you want to create a grid layout of a bunch of plots created by ggplot2. Unfortunately, par(mfrow=) is a base graphics function that doesn't work with ggplot2. Use grid.arrange in the gridExtra package.

library(ggplot2)
library(gridExtra)

# Completely fake plotting function.
makePlot = function(a, b) {
    dat = data.frame(x=rnorm(a), y=rnorm(a))
    p = ggplot(dat, aes(x=x, y=y)) + 
        geom_point(size=b, alpha=1/b) +
        opts(title=paste("a = ", a, ", b = ", b, sep="")) +
        opts(plot.title=theme_text(size=12))
    return(p)
}

plot_list = list() # Create an empty list to hold plots.

for (b in c(1, 3, 6)) {                   # I switched a and b loops
    for (a in seq(100, 900, by=100)) {    # to make the final layout neater.
        p = makePlot(a, b)
        plot_list = c(plot_list, list(p)) # Add new plot to list.
    }
}

pdf("mytry1.pdf", width = 14, height = 6)
do.call(grid.arrange, c(plot_list, list(nrow=3, ncol=9, main="Grid of Plots")))
dev.off()

enter image description here

Edit: Can this be made more concise?

The plot_list can be created and output to pdf much more compactly. Thanks to @baptiste for suggesting mlply, ggsave and arrangeGrob.

library(plyr)
plot_list = mlply(expand.grid(a=seq(100, 900, by=100), b=c(1, 3, 6)), makePlot)

ggsave(filename="grid_1.pdf", height=6, width=14, 
       plot=do.call(arrangeGrob, c(plot_list, nrow=3, main="Grid of Plots")))
bdemarest
  • 14,397
  • 3
  • 53
  • 56