Ernie
Ernie

Reputation: 1153

How to save multiple ggplot charts in loop for using grid.arrange

I have a for loop that creates a different ggplot for a different set of parameters each time through the loop. Right now I am printing N different charts one at a time. I would like to save them so I can use grid.arrange to put them all on one page. This doesn't work:

p <- vector(length = N)
for(i in 1:N)
   p[i] <- ggplot( ........
...
...
grid.arrange(p[1], p[2], .. p[N], nrow = 4)

Is there a way to save the plots for later plotting a grid of plots on a page outside the loop, or is there a way to set up the grid specification before the loop and and produce the gridded plot on the fly as the loop is executed (e.g., the way par is used with plot)?

Upvotes: 2

Views: 1030

Answers (2)

Bastian Schiffthaler
Bastian Schiffthaler

Reputation: 268

You rarely want to use for loops in R. In R's lapply(). In a single step:

do.call(
  grid.arrange,
  lapply(data, function(f){
    ggplot(f, ...)
  }
)

EDIT: If you want to store the list for later plotting:

plot_objects <- lapply(data, function(f) {
  ggplot(f, ...)
})

do.call(grid.arrange, plot_objects)

Upvotes: 3

akrun
akrun

Reputation: 887118

This could be solved by initiating a list to store the plot objects instead of vector

p <- vector('list', N)
for(i in seq_len(N)) {
  p[[i]] <- ggplot(...)
 }

grid.arrange(p[[1]], p[[2]], ..., p[[N]], nrow = 4)

Upvotes: 1

Related Questions