ima
ima

Reputation: 155

Create loops to write multiple graphs

I want to use a loop in order to create multiple plots for different values of DPC. The data I have looks like:

 df <- data.frame (c ("Results", "Capacity", "Power", "LDI","LDE", "LB", "PDC","D", CostPerkWh)

As output I would like multiple graphs with graphs for each unique value of PDC. The following plot work:

 plot1 <- ggplot(subset(df, df$PDC=='PDC0'),
   aes(Capacity, CostPerkWh))+ geom_point()+geom_line()
  plot2 <- ggplot(subset(df, df$PDC=='PDC0.25'),
            aes(Capacity, CostPerkWh))+ geom_point()+geom_line()
   plot3 <- ggplot(subset(df, df$PDC=='PDC0.5'),
            aes(Capacity, CostPerkWh))+ geom_point()+geom_line()
   plot4 <- ggplot(subset(df, df$PDC=='PDC0.75'),
            aes(Capacity, CostPerkWh))+ geom_point()+geom_line()
  plot5 <- ggplot(subset(df, df$PDC=='PDC1'),
            aes(Capacity, CostPerkWh))+ geom_point()+geom_line()

All these plots work,however I would like to create a loop since I have a large amount of parameters and I found this example.

So I tried to implement it into my own model:

#plot data
StoreResults <- "/Users/IMA/Documents/Results/"
    PDC.graph <- function(df, na.rm = TRUE, ...){
      PDClist <- unique(df$PDC) 
      for (i in seq_along(PDClist)){
        plot <- 
          ggplot(subset(df, df$PDC==PDClist[i]),
                 aes(Capacity, CostPerkWh)) + geom_point()+
          ggtitle(paste(PDClist, 'PDC, Power  \n', "Capacity \n", sep='')) + 
          geom_line() 
        print(plot)
        #save plot as PNG 
        ggsave(plot, file= paste(StoreResults, '/projection_graphs/PDCgraph/',
                                 PDClist[i], ".png", sep=''), scale=2)
      }
    }

The code does not give me an error message, but I don't see any graphs and nothing gets stored into the folder that is defined; how to resolve this? Or is there a better way to export many graph for different values of PDC?

Upvotes: 0

Views: 381

Answers (1)

timfaber
timfaber

Reputation: 2070

Didn't you forget running the function you created? This minimal version works for me:

df = iris

StoreResults <- "/Users/timfaber/Desktop"
PDC.graph <- function(df, na.rm = TRUE, ...){
  PDClist <- unique(df$Species) 
  for (i in seq_along(PDClist)){

      ggplot(subset(iris, df$Species==PDClist[i]),
      aes(Sepal.Length, Sepal.Width)) + geom_point() +
      ggtitle(paste(PDClist[i], 'PDC, Power  \n', "Capacity \n", sep=''))

    #save plot as PNG 
    ggsave(plot = last_plot(), file= paste(StoreResults, '/etc/',
                             PDClist[i], ".png", sep=''), scale=2)
  }
}

PDC.Graph(df)

Upvotes: 1

Related Questions