Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I arrange a variable list of plots using grid.arrange?

Tags:

r

ggplot2

library(ggplot2) df <- data.frame(x=1:10, y=rnorm(10)) p1 <- ggplot(df, aes(x,y)) + geom_point() plist <- list(p1,p1,p1,p1,p1) # In my real example,a plot function will fit a ggplot to a list of datasets  #and return a list of ggplots like the example above. 

I'd like to arrange the plots using grid.arrange() in gridExtra.

How would I do this if the number of plots in plist is variable?

This works: grid.arrange(plist[[1]],plist[[2]],plist[[3]],plist[[4]],plist[[5]])

but I need a more general solution. thoughts?

like image 384
Maiasaura Avatar asked May 22 '12 17:05

Maiasaura


People also ask

Can you make a list of plots in R?

Using the results from split() function, we can create a list of plots, ggplot objects, using map() function in purrr R package. In this example, map() makes a scatter plot for each species.

What does Grid Arrange do in R?

If layout parameters are ommitted altogether, grid. arrange() will calculate a default number of rows and columns to organise the plots. More complex layouts can be achieved by passing specific dimensions (widths or heights), or a layout matrix defining the position of each plot in a rectangular grid.

What are Grobs in R?

A grid graphical object (“grob”) is a description of a graphical item. These basic classes provide default behaviour for validating, drawing, and modifying graphical objects.


Video Answer


1 Answers

How about this:

library(gridExtra) n <- length(plist) nCol <- floor(sqrt(n)) do.call("grid.arrange", c(plist, ncol=nCol)) 

enter image description here

like image 105
Josh O'Brien Avatar answered Oct 31 '22 04:10

Josh O'Brien