Assigning plot to a variable in a loop

One possible answer with no tidyverse command added is :

library(ggplot2)

y_var <- colnames(df)
for (i in 1:2) {
  assign(paste("plot", i, sep = ""),
         ggplot(data = df, aes_string(x=y_var[1], y=y_var[1 + i])) +
           geom_line())
}

plot1
plot2

You may use aes_string. I hope it helps.

EDIT 1

If you want to stock your plot in a list, you can use this :

Initialize your list :

n <- 2 # number of plots
list_plot <- vector(mode = "list", length = n)
names(list_plot) <- paste("plot", 1:n)

Fill it :

for (i in 1:2) {
  list_plot[[i]] <- ggplot(data = df, aes_string(x=y_var[1], y=y_var[1 + i])) +
           geom_line()
}

Display :

list_plot[[1]]
list_plot[[2]]

For lines in different "plots", you can simplify it with facet_wrap():

library(tidyverse)
df %>% 
gather(variable, value, -c(Period)) %>% # wide to long format
ggplot(aes(Period, value)) + geom_line() + facet_wrap(vars(variable))

enter image description here

You can also put it in a loop if necessary and store the results in a list:

# empty list
listed <- list()
# fill the list with the plots
for (i in c(2:3)){
     listed[[i-1]] <- df[,-i]  %>%
                      gather(variable, value, -c(Period)) %>% 
                      ggplot(aes(Period, value)) + geom_line()
                 }

# to get the plots
listed[[1]]
listed[[2]]

Tags:

R

Ggplot2