Search code examples
riterationgraphing

How to iteratively build and export multiple graphs from 1 data set based on a factor


Say I have a data file (WQ_data_forMultipleStations.csv) with three variables: StationName, Time_hr, and DO_mgL. This file includes data for 50 stations (station1, station2, station3... station50).

I would like to create and export 50 separate graphs, one graph per station, each graph exported as a separate image file.

Each graph would have the same format: Time_hr on the x-axis, DO_mgL on the y-axis, StationName as the graph title, and exported in JPG format with the file name StationName.jpg.

I'm new to R, and I've figured out to make one giant plot with 50 subplots using facets (see code below), but I would very much appreciate help making each subplot a separate graph and then exporting the 50 graphs as 50 separate and clearly-named image files. Thanks!

library ("ggplot2")
WQ_byStation <- read.csv("WQ_data_forMultipleStations.csv")
WQ_byStation_plots <- ggplot(WQ_byStation, aes(x = Time_hr, y = DO_mgL)) + 
  geom_point() +
  geom_line() +
  facet_wrap(~ StationName)
ggsave(filename="WQ_byStation_plots.jpg", plot=WQ_byStation_plots)

Solution

  • Here is a small example of how it could be done using for loops with the mtcars dataset

    for(g in unique(mtcars$gear)) {
      f <- filter(mtcars, gear == g)
      
      p <- ggplot(f, aes(disp, hp)) +
        geom_point()
      
      ggsave(paste0('plot_', g,'.jpg'), p)
    }
    

    In your case it would something like this

    for(s in unique(WQ_byStation$StationName)){
      
      f <- filter(WQ_byStation, StationName == s)
      
      p <- ggplot(f, aes(x = Time_hr, y = DO_mgL)) + 
        geom_point() +
        geom_line() +
        ggtitle(s)
      
      ggsave(paste0(s,'.jpg'), p)
      
    }
    

    Note you can save to a folder by specifying the path in ggsave. E.g. my_folder/WQ_bySation...