Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grid.arrange using list of plots

Tags:

r

I feel I'm always asking a variation of the same question :(

I recently got a list of plots + table to display on grid.arrange using the do.call function

library(grid)
library(ggplot2)
library(gridExtra)

g1 <- ggplot(data.frame(x=c(0, 10)), aes(x)) + stat_function(fun=sin)
g2 <- ggplot(data.frame(x=c(0, 10)), aes(x)) + stat_function(fun=tan)
g3 <- ggplot(data.frame(x=c(0, 10)), aes(x)) + stat_function(fun=cos)
g4 <- tableGrob(data.frame(x <- 1:10, y<-2:11, z<-3:12))

plist <- list(g1,g2,g3,g4)
do.call("grid.arrange", c(plist))

This works but I need "plist" to be generated based on the variable "numruns" I've tried this, but it does not work:

plist2 <- list(paste0("g", seq_len(numruns+1)))
do.call("grid.arrange", c(plist2))

I believe what I'm doing is calling grid.arrange("g1","g2", ...) rather than grid.arrange(g1,g2, ...). I solved a similar problem before using lapply, but that doesn't seem to help me in this case, or else I'm using it incorrectly.

Thanks for any help.

like image 850
tastycanofmalk Avatar asked May 09 '14 17:05

tastycanofmalk


People also ask

What is Grid Arrange function 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.

How do I arrange multiple Ggplots?

To arrange multiple ggplots on one single page, we'll use the function ggarrange()[in ggpubr], which is a wrapper around the function plot_grid() [in cowplot package]. Compared to the standard function plot_grid(), ggarange() can arrange multiple ggplots over multiple pages.

How do you make a grid plot in R?

Creating a Grid of Plots To do this, you use the parameter value mfrow=c(x,y) where x is the number of rows that you wish to have in your plot and y is the number of columns. When you plot, R will place each plot, in order by row within the grid that you define using mfrow .


1 Answers

You could use mget like this:

plist2 <- mget(paste0("g", 1:4))
do.call(grid.arrange, plist2)

But it would be better to put the plots into a list when creating them, like this:

funs <- c(sin, tan, cos)
DF <- data.frame(x=c(0, 10))

g <- lapply(funs, function(fun, df) {
  ggplot(df, aes(x)) + stat_function(fun=fun)
}, df=DF)

#g[[4]] <- tableGrob(data.frame(x = 1:10, y = 2:11, z = 3:12))
#better for programmatic use:
g <- c(g, list(tableGrob(data.frame(x = 1:10, y = 2:11, z = 3:12))))

do.call(grid.arrange, g)
like image 110
Roland Avatar answered Oct 13 '22 23:10

Roland