14

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.

tastycanofmalk
  • 628
  • 7
  • 23
  • 2
    You seem to be looking for `mget`. That you need it indicates that your real problem is how you generate the plots. They should be put in a list when they are generated and not be saved as separate objects. – Roland May 09 '14 at 17:27
  • Thanks Roland, I had come across mget before and unfortunately used it without full understanding it. It seems like my process may be incorrect? Is there a similar example that you might be able to point me to? – tastycanofmalk May 09 '14 at 17:33
  • 1
    Have you done a search on `[r] mget ggplot`? I'm pretty sure you will find worked examples. – IRTFM May 09 '14 at 17:37
  • Thanks BondedDust, I'm not sure what confused me before about mget, looking at ?mget now the explanation seems very obvious. – tastycanofmalk May 09 '14 at 18:12

1 Answers1

17

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)
Roland
  • 127,288
  • 10
  • 191
  • 288
  • Thanks Roland. I'm reminded everyday how much I have to learn in R. The use of mget was what I was asking for, but thanks for including information on how to put the plots themselves into a list. I've seen this explanation come up before and seems to be the best practice. – tastycanofmalk May 09 '14 at 17:46