0

I have a bunch of code that loops through a heap of data to produce a series of summary metrics. I also want to generate a series of plots that I can then put into a grid of my choosing outside the loop. Is this possible in R?

Here's a very simple example of what I mean

it = 0
while (it < 5){
  myX = runif(10)
  myY = runif(10)
  df = data.frame(x,y)
  plt[it] = ggplot(data = df, aes(myX, myY)) + geom_point(size = 2, color = "blue")
  it = it + 1
}  

I then want to organise the plt into a grid

(although this does not seem to produce the plots, not sure why)

I would then be able to display each of the plots, put them in a grid, organise them etc. by calling the plt[2] or whatever. I'm very new to ggplot and only a basic R user, so apologies if I'm missing the obvious. Not even sure what language to use to search for this.

Also happy to be told this is a bad approach and there's a better way to create the plots. I want to do it outside the loop as I want to examine the results before deciding how to arrange them.

Esme_
  • 1,360
  • 3
  • 18
  • 30

1 Answers1

1

You could store the results in a list. To correct your while loop you can do :

library(ggplot2)
plt <- vector('list', 4)
it = 1
while (it < 5){
  myX = runif(10)
  myY = runif(10)
  df = data.frame(myX,myY)
  plt[[it]] = ggplot(data = df, aes(myX, myY)) + 
                     geom_point(size = 2, color = "blue")
  it = it + 1
}  

Another approach would be to write a function and call it n times with replicate.

create_plot <- function() {
  myX = runif(10)
  myY = runif(10)
  df = data.frame(myX,myY)
  ggplot(data = df, aes(myX, myY)) + geom_point(size = 2, color = "blue")
}
plt <- replicate(4, create_plot(), simplify = FALSE)

You could access individual plots with plt[[1]], plt[[2]] and so on.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213