'Overlay the standard deviation of a group while maintaining the yearly y axis

I have three groups (Program): Stream, Lake, and Wetland, two scenarios (RefTest): Reference and Test, and eight years of data (2014-2021), I have been able to calculate the standard deviation of each group and scenarios. I want to plot the standard deviation as an error bar on each of the three groups.

  data_summary <- function(data, varname, groupnames) {
  require(plyr)
  summary_func <- function(x, col) {
    c(mean=mean(x[[col]], na.rm=TRUE),
      sd = sd(x[[col]], na.rm = TRUE))
  }
  data_sum <- ddply(data, groupnames, .fun=summary_func, varname)
  data_sum <- rename(data_sum, c("mean" = varname))
  return(data_sum)
} 

pH_summary <- data_summary(trigger_data, varname = "pH", groupnames = c("RefTest", "Program"))

The above function yields a dataset seen below.

RefTest Program pH sd
Reference Stream 7.854 0.66
Reference Wetland 7.015 0.74
Reference Lake 6.597 1.20
Test Lake 7.214 0.645
Test Stream 7.194 0.987
Test Wetland 6.842 0.790

I'm able to use this dataset to obtain a barplot showing two standard deviations away from the mean in both directions in ggplot.

 pHPlot <- ggplot(data=pH_summary, aes(x=RefTest, y=pH, colour=RefTest)) +
    geom_point() +
    geom_errorbar(aes(ymin=pH-(sd*2),ymax=pH+(sd*2)), width=.2) +
    geom_text(aes(label=round(pH-(sd*2),digits=2), y=pH-0.1-(sd*2))) +
    geom_text(aes(label=round(pH+(sd*2),digits=2), y=0.1+pH+(sd*2))) +
    facet_wrap("Program") 

pH sd plot

Is there anyway I can add these standard deviation error bars to each group, coloured by their respective scenario? I understand that I need to merge the standard deviation data to my existing dataset with all the pH data, I'm just unsure how it can be done.

Below is my existing code showing the entire pH dataset.

ggplot(waterqual, aes(x=Year,y=pH,fill=Treatment)) +
  scale_fill_manual(name='Scenario',values=c("seagreen3","cornflowerblue")) +
  geom_boxplot() +
  facet_wrap(~Program) +
  labs(x='Location',y='pH')

pH plot all data

Thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source