user3262756
user3262756

Reputation: 679

How to store plots in a list when inside a loop?

I'm working inside a loop and I'd like to save plots in a list so I can plot them together in a .pdf. The problem is that the list is not filled up properly and re-updates with the results of the last run. So, in the end what I get is a list with five elements that are exactly the same.

I'm aware the loops may seem useless, but I just have them to create a test code (with a reproducible error) as close to the real one as possible. So, I need to leave the loops as they are.

library (ggplot)
library (gridExtra)

plist <- list()

for (z in 1:5){
  n <- 100
  k <- seq(0, to=4500+z*2000, length=n)
  tmp <- numeric(n)
  for (i in 1:n){
    tmp[i] <- (5*(i*3)^2)}

  plist[[z]] <- ggplot() +
    geom_line(aes(x = k, y = tmp)) +
    theme_bw()

  pdf(sprintf("p%s.pdf", z),
      width = 6, height = 4, onefile = T)
  plot(plist[[z]])
  dev.off()
}

do.call(grid.arrange, c(plist, ncol = 5))

Upvotes: 4

Views: 11587

Answers (1)

user3262756
user3262756

Reputation: 679

This answer is based on: Storing plot objects in a list

library(ggplot2)
library(gridExtra)

plist <- list()

for (z in 1:5){
  n <- 100
  k <- seq(0, to=4500+z*2000, length=n)
  tmp <- numeric(n)
  for (i in 1:n){
    tmp[i] <- (5*(i*3)^2)}

  data <- data.frame(n, k, tmp)

  plist[[z]] <- ggplot(data = data) + #data needs to be given!!
    geom_line(aes(x = k, y = tmp)) +
    theme_bw()

  pdf(sprintf("p%s.pdf", z),
      width = 6, height = 4, onefile = T)
  plot(plist[[z]])
  dev.off()
}

do.call(grid.arrange, c(plist, ncol = 5))

enter image description here

Upvotes: 4

Related Questions