0

I would like to create 4 plots which show 4 different conditions in a simulation. The 4 conditions in the simulation are iterated using a for loop. What I would like to do is:

for (cond in 1:4){
1.RUN SIMULATION
2.PLOT RESULTS
}

In the end I would like to have 4 plots arranged on a grid. With plot() I can just use par(mfrow) and the plots would be added automatically. Is there a way to do the same with ggplot?

I am aware that I could use grid.arrange() but that would require storing the plots in separate objects, plot1...plot5. But its not possible to do:

for (cond in 1:4){
1. run simulation
2. plot[cond]<-ggplot(...)
}

I cannot give separate names to the plots, like plot1, plot2, plot3 within the loop.

2
  • Could do library(gridExtra) ; grid.arrange(p1, p2, p3, p4, ncol=1) Commented Jun 30, 2014 at 10:36
  • but in the loop the data from which the plot is constructed is lost on every iteration. so the plots should be ready at the end of the loop. Commented Jun 30, 2014 at 10:38

3 Answers 3

4

You could use gridExtra package:

library(gridExtra)
library(ggplot2)
p <- list()
for(i in 1:4){
  p[[i]] <- ggplot(YOUR DATA, ETC.)
}
do.call(grid.arrange,p)
Sign up to request clarification or add additional context in comments.

1 Comment

for grid arrange I would need to store the plots into separate objects first. how would I do that in a loop?
2

I would use facetting in this case. In my experience, explicitly arranging sub-plots is rarely needed in ggplot2. A mockup example will probably illustrate my point better:

run_model = function(id) {
    data.frame(x_values = 1:1000, 
               y_values = runif(1000), 
               id = sprintf('Plot %d', id))
}
df = do.call('rbind', lapply(1:4, run_model))
head(df)
  x_values  y_values     id
1        1 0.7000696 Plot 1
2        2 0.3992786 Plot 1
3        3 0.2718229 Plot 1
4        4 0.4049928 Plot 1
5        5 0.4158864 Plot 1
6        6 0.1457746 Plot 1

Here, id is the column to specifies to which model run a value belongs. Plotting it can simply be done using:

library(ggplot2)
ggplot(df, aes(x = x_values, y = y_values)) + geom_point() + facet_wrap(~ id)

enter image description here

Comments

0

Another option is to use multiplot function:

library(ggplot2)
p <- list()
for(i in 1:4){
  p[[i]] <- ggplot(YOUR DATA, ETC.)
}
do.call(multiplot,p)

More information about that - http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_%28ggplot2%29/

1 Comment

how would you give separate names to the plots, like plot1, plot2, plot3 within the loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.