Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grid of multiple ggplot2 plots which have been made in a for loop

Tags:

r

ggplot2

r-grid

as a new ggplot2 user, I am a bit lost with the amount of possibilities, and struggle to find on the net a simple answer to what I consider a simple problem.

I would like to display multiple plots from ggplot2 on a same sheet, BUT knowing that these plots come from a for loop.

Following example does not compile, it is only to illustrate :

for(i in c(1:n)){                                   
  for(j in c(1:m)){
    ..........  # some data production
    p <- ggplot(df.all) + geom_bar(aes_string(x=class.names[i],fill=var.names[j])
}}

Here, p is overwritten, but I would like to have instead a matrix or a list in which I can put all the p as they are produced, then a simple function like

display_in_a_grid(list_of_ggplot_plots)

But as far as I tried, I was not able to make a list of matrix of plot, neither to find a function that takes only one argument for input.

About things I have had a look at :

"arrangeGrob" from package gridExtra doesn't work because it requires an explicit name for each plot (e.g.: p1,p2,p3,...) like in http://code.google.com/p/gridextra/wiki/arrangeGrob

"facet" method of ggplot2 is not adapted to the organization of my data set (or the contrary :p )

Would you have a simple way to manage this ?

Thank you,

François

like image 246
fstevens Avatar asked Feb 16 '12 17:02

fstevens


People also ask

How do I show multiple Ggplots together?

To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used. The basic solution is to use the gridExtra R package, which comes with the following functions: grid. arrange() and arrangeGrob() to arrange multiple ggplots on one page.

How do I save multiple Ggplots?

For this function, we simply specify the different ggplot objects in order, followed by the number of columns (ncol) and numebr of rows (nrow). This function is awesome at aligning axes and resizing figures. From here, we can simply save the arranged plot using ggsave() .

How do you save grid arrangements?

You can use arrangeGrob function that returns a grob g that you can pass to the ggsave function to save the plot. Whereas grid. arrange draws directly on a device and by default, the last plot is saved if not specified i.e., the ggplot2 invisibly keeps track of the latest plot.


1 Answers

I would be inclined to agree with Richie, but if you want to arrange them yourself:

library(gridExtra)
library(ggplot2)
p <- list()
for(i in 1:4){
  p[[i]] <- qplot(1:10,10:1,main=i)
}
do.call(grid.arrange,p)

take a look at the examples at the end of ?arrangeGrob for ways to eliminate the for loop altogether:

plots = lapply(1:5, function(.x) qplot(1:10,rnorm(10),main=paste("plot",.x)))
require(gridExtra)
do.call(grid.arrange,  plots)
like image 197
Justin Avatar answered Sep 29 '22 06:09

Justin