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

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)) +
  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() +
  ggsave(paste0(s,'.jpg'), p)

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

Leave a Comment