0

I was wondering if someone could help me get this code to return multiple graphs. I would like each graph to be labelled "plot_i" (plot_G1, plot_G2). I am at a loss as to how to get my function to return this. Any help would be appreciated!

library(lubridate)
library(tidyverse)

#Dummy Data Frame
DateTime <- c("1999/01/01 11:00","1999/01/02 11:00","1999/01/03 11:00","1999/01/01 11:00","1999/01/02 11:00","1999/01/03 11:00","1999/01/01 11:00","1999/01/02 11:00","1999/01/03 11:00")
Step <- c("Condition1","Condition1","Condition1","Condition2","Condition2","Condition2","Condition3","Condition3","Condition3")
G1 <- runif(9)
G2 <- runif(9)
G3 <- runif(9)
G4 <- runif(9)
test_df <- data.frame(DateTime = DateTime, Step = Step, G1 = G1, G2 = G2, G3 = G3, G4 = G4)
test_df$DateTime.lub <- ymd_hm(test_df$DateTime)
test_df

#Want to create a function that will provide graphs for every G1, G2, G3 and G4 and return them! 
list <- colnames(test_df)
list <- list[-c(1,2,7)]
list

#test plot - works
ggplot(data = test_df, aes(x= DateTime.lub, y = G1))+
               geom_line(aes(size = Step))

#Function does not return graph
for (i in list){
    ggplot(data = test_df, aes(x= DateTime.lub, y = i))+
        geom_line(aes(colour = Step))
}
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
Angela C
  • 146
  • 1
  • 9
  • You've got a `for` loop, not a function. Loops don't return anything. You can explicitly `print()` the plot inside the loop to get it to display. If you want to keep the plots as R objects, you'll need to assign them inside the loop, e.g., before the loop `my_plots <- list()`, and inside the loop `my_plots[[i]] <- ggplot ...`. – Gregor Thomas Jan 21 '21 at 15:25
  • 1
    Also, you'll need to modify the `y = i` to work inside the loop - Duck's answer provides a nice example of this. – Gregor Thomas Jan 21 '21 at 15:25

2 Answers2

3

Try with this:

library(ggplot2)
#Function does not return graph
for (i in list){
  var <- sym(i)
  print(ggplot(data = test_df, aes(x= DateTime.lub, y = !!var))+
    geom_line(aes(colour = Step))+
    ggtitle(paste0('plot_',i)))
}
Duck
  • 39,058
  • 13
  • 42
  • 84
0

For anyone else using this, if you want to export graphs see below:

plot_list = list()
for (i in list) {
    var <- sym(i)    
    p = ggplot(test_df, aes(x=DateTime.lub, y=!!var)) +
        geom_line(aes(colour=Step))
    print(p)
    plot_list[[i]] = p
}

setwd("~/WD")
for (i in list) {
    file_name = paste("plot_", i, ".tiff", sep="")
    tiff(file_name)
    print(plot_list[[i]])
    dev.off()
}
Angela C
  • 146
  • 1
  • 9