0

My data is comprised of a column of fish counts with the corresponding when and where of each catch.

data <- structure(list(year = c(2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 
                                 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 
                                 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 
                                 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2019L, 2019L, 2019L, 
                                 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 
                                 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 
                                 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 
                                 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 
                                 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 
                                 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 2020L, 
                                 2020L, 2020L, 2020L), season = structure(c(1L, 1L, 1L, 1L, 1L, 
                                                                            1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 
                                                                            2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
                                                                            1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
                                                                            2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
                                                                            1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
                                                                            2L, 2L, 2L, 2L, 2L), .Label = c("dry", "wet"), class = "factor"), 
                        site = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 
                                 5L, 5L, 5L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 
                                 5L, 5L, 5L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 
                                 5L, 5L, 5L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 
                                 5L, 5L, 5L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 
                                 5L, 5L, 5L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 4L, 
                                 5L, 5L, 5L), common_name = structure(c(68L, 92L, 105L, 68L, 
                                                                        92L, 105L, 68L, 92L, 105L, 68L, 92L, 105L, 68L, 92L, 105L, 
                                                                        68L, 92L, 105L, 68L, 92L, 105L, 68L, 92L, 105L, 68L, 92L, 
                                                                        105L, 68L, 92L, 105L, 68L, 92L, 105L, 68L, 92L, 105L, 68L, 
                                                                        92L, 105L, 68L, 92L, 105L, 68L, 92L, 105L, 68L, 92L, 105L, 
                                                                        68L, 92L, 105L, 68L, 92L, 105L, 68L, 92L, 105L, 68L, 92L, 
                                                                        105L, 68L, 92L, 105L, 68L, 92L, 105L, 68L, 92L, 105L, 68L, 
                                                                        92L, 105L, 68L, 92L, 105L, 68L, 92L, 105L, 68L, 92L, 105L, 
                                                                        68L, 92L, 105L, 68L, 92L, 105L, 68L, 92L, 105L), .Label = c("Atlantic Mud Crab", 
                                                                                                                                    "Atlantic Needlefish", "Banded Blenny", "Banded Brittle Star", 
                                                                                                                                    "Banded Killifish", "Bandtail Puffer", "Barracuda spp", "Bigclaw Snapping Shrimp", 
                                                                                                                                    "Bigeye Mojarra", "Blenny spp", "Blue Crab", "Blue Crab spp", 
                                                                                                                                    "Blue Striped Grunt", "Bluethroat Pikeblenny", "Bonefish", 
                                                                                                                                    "Brittle Star spp", "Broadback Mud Crab", "Brown Shrimp", 
                                                                                                                                    "Bryozoan Shrimp", "Chain Pipefish", "Checkered Puffer", 
                                                                                                                                    "Chub spp", "Clown Goby", "Code Goby", "Combtooth Blenny spp", 
                                                                                                                                    "Crested Blenny", "Crested Goby", "Crossbanded Grass Shrimp", 
                                                                                                                                    "Cushion Sea Star", "Daggerblade Grass Shrimp", "Darter Goby", 
                                                                                                                                    "Dusky Pipefish", "Dwarf Seahorse", "Estuarine Snapping Shrimp", 
                                                                                                                                    "False Zostera Shrimp", "Fiddler Crab spp", "Flagfin Mojarra", 
                                                                                                                                    "Flatback Mud Crab", "Florida Blenny", "Florida Grass Shrimp", 
                                                                                                                                    "Florida Grassflat Crab", "Frillfin Goby", "Fringed Pipefish", 
                                                                                                                                    "Furrowed Mud Crab", "Giant Decorator crab", "Giant Tiger Prawn", 
                                                                                                                                    "Glass Shrimp", "Goby spp", "Goby spp (Ctenogobius spp)", 
                                                                                                                                    "Goldspotted Killifish", "Grass Shrimp (H obliquimanus)", 
                                                                                                                                    "Grass Shrimp (Leander spp)", "Grass Shrimp (Nikoides schmitti)", 
                                                                                                                                    "Grass Shrimp (P mundusnovus)", "Grass Shrimp (Palaemon spp)", 
                                                                                                                                    "Grass Shrimp (Palaemonidae spp)", "Grass Shrimp (Periclimenes spp)", 
                                                                                                                                    "Grass Shrimp (Thor spp)", "Grass Shrimp Spp", "Gray Snapper", 
                                                                                                                                    "Great Barracuda", "Grunt spp", "Gulf Flounder", "Gulf Killifish", 
                                                                                                                                    "Gulf Pipefish", "Gulf Toadfish", "Halfbeak spp", "Hardhead Silverside", 
                                                                                                                                    "Harlequin Brittle Star", "Harris Mud Crab", "Highfin Blenny", 
                                                                                                                                    "Hogchoker", "Horseshoe Crab", "Iridescent Shrimp", "Jack spp", 
                                                                                                                                    "Jewel Cichlid", "Killifish spp", "Least Puffer", "Lesser Blue Crab", 
                                                                                                                                    "Lined Seahorse", "Lined Sole", "Lobate Mud Crab", "Longnose Spider Crab", 
                                                                                                                                    "Longsnout Seahorse", "Longtail Grass Shrimp", "Mangrove Gambusia", 
                                                                                                                                    "Mangrove Rivulus", "Manning Grass Shrimp", "Marsh Killifish", 
                                                                                                                                    "Marsh Shrimp", "Mayan Cichlid", "Mojarra spp", "Mud Crab spp", 
                                                                                                                                    "Mullet spp", "Needlefish spp", "Oyster Mud Crab", "Pearl Blenny", 
                                                                                                                                    "Pinfish", "Pink Shrimp", "Pink Shrimp spp", "Pipefish spp", 
                                                                                                                                    "Porgy spp", "Puffer spp", "Pugnose Pipefish", "Rainwater Killifish", 
                                                                                                                                    "Red-Algae Shrimp", "Redear Sardine", "Redfin Needlefish", 
                                                                                                                                    "Roughneck Shrimp", "Sailfin Molly", "Sailor's Choice", "Saltmarsh Mud Crab", 
                                                                                                                                    "Sargassum Fish", "Sargassum Pipefish", "Sargassum Shrimp", 
                                                                                                                                    "Sargassum Swimming Crab", "Say Mud Crab", "Schoolmaster Snapper", 
                                                                                                                                    "Sea Star spp", "Seabream", "Seahorse spp", "Sheepshead", 
                                                                                                                                    "Sheepshead Minnow", "Silver Jenny", "Silverside spp", "Slender Mojarra", 
                                                                                                                                    "Slender Sargassum Shrimp", "Small Spine Sea Star", "Smooth Mud Crab", 
                                                                                                                                    "Snapper spp", "Snapping Shrimp (A viridari)", "Snapping Shrimp (A. angulosus)", 
                                                                                                                                    "Snapping Shrimp spp", "Southern Pink Shrimp", "Southern Puffer", 
                                                                                                                                    "Southern Sennet", "Spaghetti Eel", "Speckled Worm Eel", 
                                                                                                                                    "Spider Crab spp", "Sponge Spider Crab", "Spotted Pink Shrimp", 
                                                                                                                                    "Spotted Whiff", "Squat Grass Shrimp", "Stone Crab", "Striped Mullet", 
                                                                                                                                    "Swimming Crab spp", "Timicu", "Tomtate", "Tripletail", "White Grunt", 
                                                                                                                                    "White Mullet", "Whitespotted Filefish", "Yellowfin Mojarra", 
                                                                                                                                    "Zostera Shrimp"), class = "factor"), num = c(0L, 1L, 0L, 
                                                                                                                                                                                  4L, 2L, 0L, 0L, 0L, 4L, 0L, 5L, 24L, 0L, 0L, 0L, 0L, 1L, 
                                                                                                                                                                                  5L, 0L, 2L, 3L, 0L, 0L, 38L, 25L, 0L, 14L, 0L, 0L, 0L, 0L, 
                                                                                                                                                                                  0L, 0L, 0L, 1L, 9L, 0L, 5L, 20L, 10L, 0L, 17L, 0L, 0L, 0L, 
                                                                                                                                                                                  66L, 2L, 64L, 0L, 5L, 4L, 0L, 12L, 49L, 0L, 0L, 2L, 0L, 2L, 
                                                                                                                                                                                  0L, 0L, 0L, 0L, 0L, 1L, 4L, 0L, 1L, 4L, 0L, 0L, 2L, 0L, 0L, 
                                                                                                                                                                                  0L, 0L, 0L, 0L, 0L, 0L, 0L, 16L, 12L, 12L, 0L, 0L, 26L, 2L, 
                                                                                                                                                                                  0L, 0L)), class = "data.frame", row.names = c(NA, -90L))

I want to make a function that first summarizes the data of each species and then saves a png file plot for each unique species name (or print's to the screen if filename = NULL). I've gotten this far, but not sure what to fix...

    GetMatrix=function(data, commonToSum) {
  newdat<-filter(data,common_name %in% commonToSum)
  cdata2 <- plyr::ddply(data, c("year", "season"), summarise,
                  N    = length(num),
                  n_mean = mean(num),
                  n_median = median(num),
                  sd   = sd(num),
                  se   = sd / sqrt(N))
  cdata2$year_season <- paste(cdata2$year, "_", cdata2$season, sep = "")
  cdata2 <- within(cdata2, year[year == 2005 & season == 'wet'] <- 2005.75)
  cdata2 <- within(cdata2, year[year == 2006 & season == 'wet'] <- 2006.75)
  cdata2 <- within(cdata2, year[year == 2007 & season == 'wet'] <- 2007.75)
  cdata2 <- within(cdata2, year[year == 2008 & season == 'wet'] <- 2008.75)
  cdata2 <- within(cdata2, year[year == 2009 & season == 'wet'] <- 2009.75)
  cdata2 <- within(cdata2, year[year == 2010 & season == 'wet'] <- 2010.75)
  cdata2 <- within(cdata2, year[year == 2011 & season == 'wet'] <- 2011.75)
  cdata2 <- within(cdata2, year[year == 2012 & season == 'wet'] <- 2012.75)
  cdata2 <- within(cdata2, year[year == 2013 & season == 'wet'] <- 2013.75)
  cdata2 <- within(cdata2, year[year == 2014 & season == 'wet'] <- 2014.75)
  cdata2 <- within(cdata2, year[year == 2015 & season == 'wet'] <- 2015.75)
  cdata2 <- within(cdata2, year[year == 2016 & season == 'wet'] <- 2016.75)
  cdata2 <- within(cdata2, year[year == 2017 & season == 'wet'] <- 2017.75)
  cdata2 <- within(cdata2, year[year == 2018 & season == 'wet'] <- 2018.75)
  cdata2 <- within(cdata2, year[year == 2019 & season == 'wet'] <- 2019.75)
  cdata2 <- within(cdata2, year[year == 2020 & season == 'wet'] <- 2020.75)
  cdata2 <- within(cdata2, year[year == 2005 & season == 'dry'] <- 2005.25)
  cdata2 <- within(cdata2, year[year == 2006 & season == 'dry'] <- 2006.25)
  cdata2 <- within(cdata2, year[year == 2007 & season == 'dry'] <- 2007.25)
  cdata2 <- within(cdata2, year[year == 2008 & season == 'dry'] <- 2008.25)
  cdata2 <- within(cdata2, year[year == 2009 & season == 'dry'] <- 2009.25)
  cdata2 <- within(cdata2, year[year == 2010 & season == 'dry'] <- 2010.25)
  cdata2 <- within(cdata2, year[year == 2011 & season == 'dry'] <- 2011.25)
  cdata2 <- within(cdata2, year[year == 2012 & season == 'dry'] <- 2012.25)
  cdata2 <- within(cdata2, year[year == 2013 & season == 'dry'] <- 2013.25)
  cdata2 <- within(cdata2, year[year == 2014 & season == 'dry'] <- 2014.25)
  cdata2 <- within(cdata2, year[year == 2015 & season == 'dry'] <- 2015.25)
  cdata2 <- within(cdata2, year[year == 2016 & season == 'dry'] <- 2016.25)
  cdata2 <- within(cdata2, year[year == 2017 & season == 'dry'] <- 2017.25)
  cdata2 <- within(cdata2, year[year == 2018 & season == 'dry'] <- 2018.25)
  cdata2 <- within(cdata2, year[year == 2019 & season == 'dry'] <- 2019.25)
  cdata2 <- within(cdata2, year[year == 2020 & season == 'dry'] <- 2020.25)
}



Plot<-function(data,common_name,fileName=NULL) {
  ggplot(cdata2, aes(x = year, y = n_mean, color = season)) +
  annotate(geom = "rect", xmin = 2010, xmax = 2010.5, ymin = -Inf, ymax = Inf,
           fill = "lightblue", colour = NA, alpha = 0.4) +
  annotate(geom = "rect", xmin = 2013.5, xmax = 2014, ymin = -Inf, ymax = Inf,
           fill = "lightgreen", colour = NA, alpha = 0.4) +
  annotate(geom = "rect", xmin = 2017.5, xmax = 2018, ymin = -Inf, ymax = Inf,
           fill = "#E0E0E0", colour = NA, alpha = 0.4) +
  annotate(geom = "rect", xmin = 2011.5, xmax = 2012, ymin = -Inf, ymax = Inf,
           fill = "pink", colour = NA, alpha = 0.4) +
  annotate(geom = "rect", xmin = 2015.5, xmax = 2016, ymin = -Inf, ymax = Inf,
           fill = "pink", colour = NA, alpha = 0.4) +
  annotate(geom = "rect", xmin = 2018.5, xmax = 2019, ymin = -Inf, ymax = Inf,
           fill = "orange", colour = NA, alpha = 0.4) +
  geom_errorbar(aes(ymin=n_mean-se, ymax=n_mean+se), 
                width=.2, 
                color = "black") +
  geom_point(color = "black", 
             shape = 21, 
             size = 3,
  aes(fill = season)) +
  scale_fill_manual(values=c("white", "#C0C0C0")) +   scale_x_continuous(breaks=c(2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2018,2019,2020)) +
  theme(panel.border = element_rect(fill = NA, color = "black"),
        panel.background = element_blank(), 
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank()) +
  labs(x="Year", y = "Mean count") +
  theme(plot.title = element_text(hjust = 0.5)) +
  theme(axis.text.y = element_text(size = 10, face = "bold")) +
  theme(axis.text.x = element_text(size = 10, face = "bold")) +
  theme(axis.title = element_text(size = 14, face = "bold"))

}

spSummary <- data %>%
  group_by(common_name) %>%
  dplyr::summarize(total.numbers=sum(num)) %>%
  arrange(-total.numbers)
spSummary

splist<-spSummary$common_name


dataList<-list()
filenameVal<-paste0(1:length(splist),splist,"- IBBEAM_trend_plot.png")

setwd('C:/Users/...Trend plots')

for(run in 1:length(splist)) {
  dataList[[run]]<-GetMatrix(data,splist[run])
  Plot(data=dataList[[run]],splist[run],fileName=filenameVal[run])
  print(paste(run,splist[run]))
}
Nate
  • 411
  • 2
  • 10
  • 2
    Hi, can you provide a small example dataset, so that we can reproduce your code? Just add a few rows of "counts_data.csv" including two years, two seasons (and all columns you need in the code). You can find an example e.g., [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) under the heading "Data frames". – Saskia Schirmer Sep 06 '21 at 14:46
  • I used the "dput" method and added it to my original post. Thank you for the help! – Nate Sep 06 '21 at 17:02

1 Answers1

0

Here is your program code after repair !! However, without posting the data.

library(tidyverse) ###!!!###
data

GetMatrix=function(data, commonToSum) {
  newdat<-filter(data,common_name %in% commonToSum)
  cdata2 <- plyr::ddply(data, c("year", "season"), summarise,
                        N    = length(num),
                        n_mean = mean(num),
                        n_median = median(num),
                        sd   = sd(num),
                        se   = sd / sqrt(N))
  cdata2$year_season <- paste(cdata2$year, "_", cdata2$season, sep = "")
  cdata2 <- within(cdata2, year[year == 2005 & season == 'wet'] <- 2005.75)
  cdata2 <- within(cdata2, year[year == 2006 & season == 'wet'] <- 2006.75)
  cdata2 <- within(cdata2, year[year == 2007 & season == 'wet'] <- 2007.75)
  cdata2 <- within(cdata2, year[year == 2008 & season == 'wet'] <- 2008.75)
  cdata2 <- within(cdata2, year[year == 2009 & season == 'wet'] <- 2009.75)
  cdata2 <- within(cdata2, year[year == 2010 & season == 'wet'] <- 2010.75)
  cdata2 <- within(cdata2, year[year == 2011 & season == 'wet'] <- 2011.75)
  cdata2 <- within(cdata2, year[year == 2012 & season == 'wet'] <- 2012.75)
  cdata2 <- within(cdata2, year[year == 2013 & season == 'wet'] <- 2013.75)
  cdata2 <- within(cdata2, year[year == 2014 & season == 'wet'] <- 2014.75)
  cdata2 <- within(cdata2, year[year == 2015 & season == 'wet'] <- 2015.75)
  cdata2 <- within(cdata2, year[year == 2016 & season == 'wet'] <- 2016.75)
  cdata2 <- within(cdata2, year[year == 2017 & season == 'wet'] <- 2017.75)
  cdata2 <- within(cdata2, year[year == 2018 & season == 'wet'] <- 2018.75)
  cdata2 <- within(cdata2, year[year == 2019 & season == 'wet'] <- 2019.75)
  cdata2 <- within(cdata2, year[year == 2020 & season == 'wet'] <- 2020.75)
  cdata2 <- within(cdata2, year[year == 2005 & season == 'dry'] <- 2005.25)
  cdata2 <- within(cdata2, year[year == 2006 & season == 'dry'] <- 2006.25)
  cdata2 <- within(cdata2, year[year == 2007 & season == 'dry'] <- 2007.25)
  cdata2 <- within(cdata2, year[year == 2008 & season == 'dry'] <- 2008.25)
  cdata2 <- within(cdata2, year[year == 2009 & season == 'dry'] <- 2009.25)
  cdata2 <- within(cdata2, year[year == 2010 & season == 'dry'] <- 2010.25)
  cdata2 <- within(cdata2, year[year == 2011 & season == 'dry'] <- 2011.25)
  cdata2 <- within(cdata2, year[year == 2012 & season == 'dry'] <- 2012.25)
  cdata2 <- within(cdata2, year[year == 2013 & season == 'dry'] <- 2013.25)
  cdata2 <- within(cdata2, year[year == 2014 & season == 'dry'] <- 2014.25)
  cdata2 <- within(cdata2, year[year == 2015 & season == 'dry'] <- 2015.25)
  cdata2 <- within(cdata2, year[year == 2016 & season == 'dry'] <- 2016.25)
  cdata2 <- within(cdata2, year[year == 2017 & season == 'dry'] <- 2017.25)
  cdata2 <- within(cdata2, year[year == 2018 & season == 'dry'] <- 2018.25)
  cdata2 <- within(cdata2, year[year == 2019 & season == 'dry'] <- 2019.25)
  cdata2 <- within(cdata2, year[year == 2020 & season == 'dry'] <- 2020.25)
  cdata2  ###The function has to return something###
}



Plot<-function(data,common_name,fileName=NULL) {
  ###I changed ggplot(cdata2,... to ggplot(data,...
  ggplot(data, aes(x = year, y = n_mean, color = season)) +
    annotate(geom = "rect", xmin = 2010, xmax = 2010.5, ymin = -Inf, ymax = Inf,
             fill = "lightblue", colour = NA, alpha = 0.4) +
    annotate(geom = "rect", xmin = 2013.5, xmax = 2014, ymin = -Inf, ymax = Inf,
             fill = "lightgreen", colour = NA, alpha = 0.4) +
    annotate(geom = "rect", xmin = 2017.5, xmax = 2018, ymin = -Inf, ymax = Inf,
             fill = "#E0E0E0", colour = NA, alpha = 0.4) +
    annotate(geom = "rect", xmin = 2011.5, xmax = 2012, ymin = -Inf, ymax = Inf,
             fill = "pink", colour = NA, alpha = 0.4) +
    annotate(geom = "rect", xmin = 2015.5, xmax = 2016, ymin = -Inf, ymax = Inf,
             fill = "pink", colour = NA, alpha = 0.4) +
    annotate(geom = "rect", xmin = 2018.5, xmax = 2019, ymin = -Inf, ymax = Inf,
             fill = "orange", colour = NA, alpha = 0.4) +
    geom_errorbar(aes(ymin=n_mean-se, ymax=n_mean+se), 
                  width=.2, 
                  color = "black") +
    geom_point(color = "black", 
               shape = 21, 
               size = 3,
               aes(fill = season)) +
    scale_fill_manual(values=c("white", "#C0C0C0")) +   scale_x_continuous(breaks=c(2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2018,2019,2020)) +
    theme(panel.border = element_rect(fill = NA, color = "black"),
          panel.background = element_blank(), 
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank()) +
    labs(x="Year", y = "Mean count") +
    theme(plot.title = element_text(hjust = 0.5)) +
    theme(axis.text.y = element_text(size = 10, face = "bold")) +
    theme(axis.text.x = element_text(size = 10, face = "bold")) +
    theme(axis.title = element_text(size = 14, face = "bold"))
  
}

spSummary <- data %>%
  group_by(common_name) %>%
  dplyr::summarize(total.numbers=sum(num)) %>%
  arrange(-total.numbers)
spSummary

splist<-spSummary$common_name


dataList<-list()
filenameVal<-paste0(1:length(splist),splist,"- IBBEAM_trend_plot.png")

setwd('C:/Users/...Trend plots')

for(run in 1:length(splist)) {
  dataList[[run]]<-GetMatrix(data,splist[run])
  Plot(data=dataList[[run]],splist[run],fileName=filenameVal[run])
  print(paste(run,splist[run]))
}

Although there are many things I would write much simpler. enter image description here

Update 1

OKAY. Let's see how it can be done more clearly and elegantly. For starters, I'm assuming your data is in a data frame named data. First, let's create a GetSummary summary function. This will be the equivalent of your GetMatrix.

GetSummary = function(data) data %>%
  mutate(year = year+ifelse(season=='wet',0.75,0.25)) %>%
  group_by(year, season) %>%
  summarise(
    .groups = "keep",
    N = n(),
    n_mean = mean(num),
    n_median = median(num),
    sd   = sd(num),
    se   = sd / sqrt(N)
  )

Now let's do a simple mutation by grouping the data by common_name, collapsing it with the nest function, and mapping our function over the collapsed data.

library(tidyverse)
data = data %>% 
  as_tibble() %>%
  mutate(common_name = common_name %>% fct_infreq() %>% fct_drop()) %>%
  group_by(common_name) %>% 
  nest() %>%
  mutate(summ = map(data, GetSummary))
data
#  A tibble: 3 x 3
#  Groups:   common_name [3]
#  common_name         data              summ                
#  <fct>               <list>            <list>              
#1 Hardhead Silverside <tibble [30 x 4]> <grouped_df [6 x 7]>
#2 Mojarra spp         <tibble [30 x 4]> <grouped_df [6 x 7]>
#3 Rainwater Killifish <tibble [30 x 4]> <grouped_df [6 x 7]>

This result may be a bit surprising. Note that you get data for one fish type in the variable data, and that a summary of this data is in summ. Let's see what is in summ variable for Hardhead Silverside fish.

data[1,]$summ
#  A tibble: 6 x 7
#  Groups:   year, season [6]
#   year season     N n_mean n_median    sd    se
#  <dbl> <fct>  <int>  <dbl>    <int> <dbl> <dbl>
#1 2018. dry        5    0.8        0  1.79  0.8 
#2 2019. wet        5    5          0 11.2   5   
#3 2019. dry        5    2          0  4.47  2   
#4 2020. wet        5   13.2        0 29.5  13.2 
#5 2020. dry        5    0          0  0     0   
#6 2021. wet        5    3.6        0  6.99  3.12

This is all you expected. Now let's prepare a function that creates a graph. But first, let's write the information about the colored rectangles in one tibble.

dfAnnot = tribble(
  ~year,     ~fill,
  2010,   "lightblue",
  2011.5, "pink",
  2013.5, "lightgreen",
  2015.5, "pink",
  2017.5, "#E0E0E0",
  2018.5, "orange"
)

You can easily expand such a table in the future according to your needs. Now we can create a function that creates a graph from and saves it to a png file. My makePlot function is equivalent to your Plot function.

makePlot = function(df, group, dir=""){
  data = df$summ[[1]]
  plot = data %>% ggplot(aes(year, n_mean, fill=season))+
    geom_point(color = "black", shape = 21, size = 3)+
    geom_errorbar(aes(ymin = n_mean-se, ymax = n_mean+se), width = .2)+
    annotate(xmin = dfAnnot$year, xmax = dfAnnot$year+0.5,
             ymin = -Inf, ymax = Inf, fill = dfAnnot$fill,
             geom="rect", alpha = 0.4) +
    scale_fill_manual(values=c("white", "#C0C0C0"))+
    scale_x_continuous(breaks=2005:2020)+
    theme(panel.border = element_rect(fill = NA, color = "black"),
          panel.background = element_blank(),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank()) +
    labs(x="Year", y = "Mean count") +
    theme(plot.title = element_text(hjust = 0.5)) +
    theme(axis.text.y = element_text(size = 10, face = "bold")) +
    theme(axis.text.x = element_text(size = 10, face = "bold")) +
    theme(axis.title = element_text(size = 14, face = "bold"))+
    ggtitle(group$common_name)
  ggsave(paste(dir, group$common_name,".png"), plot)
  plot
}

By creating this function, I tried to be as close to your expectations as possible. I just added a chart title. The use of this function is very simple. You only need two functions group_by and group_map.

data %>% group_by(common_name) %>%
  group_map(makePlot, dir="plots/")

Here are the results of its operation. enter image description here enter image description here enter image description here

Graphs can be seen in the Plots window and are additionally saved in files in the plots directory. I suggest working in RStudio and creating a project. You will not need to set up the directory with the setwd function.

The whole thing should work fine, even for more observations. It can also be easily expanded in the future (the dfAnnot table). I hope that my solution will work and meet your expectations.

Also remember that the filenames come directly from the common_name variable. Make sure that there are only those strings that will be valid filenames.

Marek Fiołka
  • 4,825
  • 1
  • 5
  • 20
  • Hi, thanks, but the function should creating 3 plots (one for each species I provided in the example data). Any advice about how to simplify my code is also appreciated! – Nate Sep 06 '21 at 23:19
  • @Nate you can look at all 3 plots, e.g., by writing `p[[run]] <- Plot(data=dataList[[run]],splist[run],fileName=filenameVal[run])` and in the for-loop and performing `p[[1]]`... afterwards. However, all three plots look the same, because getMatrix gives back the same values for all 3 species. Is that what you want? Maybe you want to change to dplyr (instead of dply) and use group_by on the species. – Saskia Schirmer Sep 08 '21 at 07:23
  • I see. Yes, they should be different looking plots so I think I do want group_by on the species. I'll give it a try. – Nate Sep 08 '21 at 14:33