Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

r - grid.arrange using list of plots

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...