Take the 2-minute tour ×

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)     
share|improve this question
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 1:06

1 Answer 1

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.


# Completely fake plotting function.
makePlot = function(a, b) {
    dat = data.frame(x=rnorm(a), y=rnorm(a))
        geom_point(size=b, alpha=1/b) +
        opts(title=paste("a = ", a, ", b = ", b, sep="")) +

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")))

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.

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")))
share|improve this answer
FWIW one could simplify the code with mlply and ggsave –  baptiste Jul 20 '12 at 6:44
ggsave will work using arrangeGrob; grid.arrange only draws and returns nothing. –  baptiste Jul 20 '12 at 7:51

Your Answer


