Carmen Sandoval
Carmen Sandoval

Reputation: 2356

How do I specify the number of rows and columns to print multiple plots per page with gridExtra?

I have created a number of plots through a for loop using ggplot, and saved each plot into a list plots.

plots <- list()

for (i in 1:238)

{

    gene <- row.names(geneExpression)[i]

    df.sub <- df[ , c("source", gene)]

    names(test.sub) <- c("source", "exp")

    plots[[i]] <- ggplot() + geom_violin(data=test.sub, aes(source, exp, fill=source, color=source), alpha=.4, trim=F, environment = environment()) + coord_flip() + ggtitle(gene) + theme(legend.position="none") + labs(x="")

}

I am using the gridExtra function as suggested elsewhere, but when I do this, it prints all of the plots (240 plots) in a single page.

pdf("violinPlots.pdf")
do.call(grid.arrange, plots)
dev.off()

Is there a way I can specify that I want 24 plots per page? (i.e. 6 rows x 4 columns?)

I tried this but it returns an error...

grid.arrange(plots, ncol=4, newpage = T )

Upvotes: 1

Views: 1294

Answers (1)

David Robinson
David Robinson

Reputation: 78630

You can use gridExtra's marrangeGrob function:

pdf("violinPlots.pdf")
ml <- marrangeGrob(grobs = plots, nrow = 6, ncol = 4)
print(ml)
dev.off()

Upvotes: 2

Related Questions