1

Initially I wanted to use ggplot2 within a for loop, which didn't work because instead of saving the first graph the second graph was saved after the second iteration of the loop. The following code illustrates this. It's not necessary to use a for loop for reproducing this error. If I execute the code like this, it works:

library(ggplot2)

df <- data.frame(x = c(1,2,3,4,5),
             y1 = c(10,55,32,78,47),
             y2 = c(-1.3,-2.5,-4.1,-1.7,-3.6))

hori <- c("y1", "y2")

pmse <- list()

pmse[[1]] <- ggplot(data = df, aes(x = x, y = eval(parse(text = paste(hori[1])))))+
  geom_line()+
  labs(title = paste(hori[1]))+
  ylab(paste(hori[1]))

pmse[[2]] <- ggplot(data = df, aes(x = x, y = eval(parse(text = paste(hori[2])))))+
  geom_line()+
  labs(title = paste(hori[2]))+
  ylab(paste(hori[2]))

pmse[[1]]
pmse[[2]]

If 1 and 2 are substituted by i, whereas i = 1 and i = 2, respectively, the second graph is saved 2 times. Somehow the first plot seems to be overwritten:

pmse <- list()
i <- 1
pmse[[i]] <- ggplot(data = df, aes(x = x, y = eval(parse(text = paste(hori[i])))))+
  geom_line()+
  labs(title = paste(hori[i]))+
  ylab(paste(hori[i]))

i <- 2
pmse[[i]] <- ggplot(data = df, aes(x = x, y = eval(parse(text = paste(hori[i])))))+
  geom_line()+
  labs(title = paste(hori[i]))+
  ylab(paste(hori[i]))

pmse[[1]]
pmse[[2]]

How can I reproduce the first code snippet using a variable, (which I overwrite) instead of the numbers 1 and 2? When I use i = 1 and j = 2 and substitute the i from the second "iteration" with the j, then it's working fine. Am I missing something? How can I fix this?

yPennylane
  • 760
  • 1
  • 9
  • 27
  • 3
    Related: [Storing ggplot objects in a list from within loop in R](https://stackoverflow.com/questions/31993704/storing-ggplot-objects-in-a-list-from-within-loop-in-r) – pogibas Aug 08 '18 at 13:55

1 Answers1

0

I recommend reconsidering how you organize your data as it relates to ggplot and taking advantage of facet_wrap

df %>% 
  gather(key, value, -x) %>% 
  ggplot(., aes(x=x, y=value)) + 
  geom_line() +  
  facet_wrap(~key)
CPak
  • 13,260
  • 3
  • 30
  • 48