Home > Blockchain >  Save plots generated within a loop in R
Save plots generated within a loop in R

Time:09-27

I am looking for a way to save ggplots and flextables to the workspace and later combine these objects that were generated within a loop.

Here is a simple example:

for (i in 1:3) {x<-rnorm(20, 5, 5-i); hist(x)}

In this example, x is overwritten every time and a new histogram is generated. I would want to store each histogram that is generated within the loop in the current workspace and later combine those histograms in one plot (without having to actually save each one of them). How can I go about that best? Thanks a lot in advance!

CodePudding user response:

We could set the par and get the plots into a single page

par(mfrow = c(3, 1))
for (i in 1:3) {
    x<-rnorm(20, 5, 5-i)
     hist(x)
  }

If we want to store the plots and print, then create a NULL list to store the objects, and then do the plotting later

p1 <- vector('list', 3)
for(i in seq_along(p1)) {
    x<- rnorm(20, 5, 5-i)
    p1[[i]] <- hist(x)
}
par(mfrow = c(3, 1))
for(p in p1) plot(p)
  • Related