How to create plots dynamically in grid.arrange in

2019-05-18 20:10发布

问题:

I have a function get.single.plot, which takes one character argument and returns a ggplot2 plot object. I would like to build a grid.arrange object with n plots on it, where the n is the size of vector of (mentioned) character arguments.

E.g., I woould like something like this to work:

character.argument.vector <- c("12", "1", "2")
grid.arrange(unlist(lapply(character.argument.vector, function(n) get.single.plot(n))),
         ncol = 1)

Such thing does not work - I receive the following information:

Error in arrangeGrob(..., as.table = as.table, clip = clip, main = main,  : 
input must be grobs!

How should I do it?

回答1:

With gridExtra v>=2.0 you can simply pass a list of grobs (or plots) to grid.arrange,

grid.arrange(grobs = lapply(...), ncol=1)