I am trying to produce a bar graph with error bars that has multiple groupings of factors. Here is a sketch of my intended plot:
- All mean TRIG values for 2005-2006 are from male birds only.
I am having trouble adding error bars to my plot.
Here is my existing code:
# Load Data
TRIG_rawdata <- read.csv("C:\\Users\\o_tru\\OneDrive\\ARP\\Metabolites\\SUSC metabolites_TrueTRIG_2005-2006_2021.csv")
# Combine age and sex to create single ("COHORT") factor (HYF = Hatch Year Female, HYM = Hatch Year Male, AHYF = AFTER Hatch Year Female, AHYM = AFTER Hatch Year Male)
library(dplyr)
SUSC_TRIG <- mutate(TRIG_rawdata, Cohort = case_when(
Age == "HY" & Sex == "F" ~ "HYF", Age == "HY" & Sex == "M" ~ "HYM", Age == "AHY" & Sex == "F" ~ "AHYF",
Age == "AHY" & Sex == "M" ~ "AHYM"
))
# Create bar plot with error bars (for multiple subgroups)
# https://stackoverflow.com/questions/20060949/ggplot2-multiple-sub-groups-of-a-bar-chart)
library(ggplot2)
# Create sub-groups
# Create "Season" factor for past and present
SUSC_TRIG <- mutate(TRIG_rawdata, Season = case_when(
Year == "2005" | Year == "2006" ~ "2005-2006",
Year == "2021" ~ "2021"
))
# Combine Habitat.type x Cohort into single factor
SUSC_TRIG_subset <- mutate(SUSC_TRIG, Habitat_Cohort = case_when(
Habitat.Type == "Seagrass (hard-bottom)" & Year == "2005" ~ "S-HB 2005",
Habitat.Type == "Seagrass (hard-bottom)" & Year == "2006" ~ "S-HB 2006",
Habitat.Type == "Seagrass (soft-bottom)" & Year == "2005" ~ "S-SB 2005",
Habitat.Type == "Seagrass (soft-bottom)" & Year == "2006" ~ "S-SB 2006",
Habitat.Type == "Mussel (mixed substrate)" & Year == "2005" ~ "M 2005",
Habitat.Type == "Mussel (mixed substrate)" & Year == "2006" ~ "M 2006",
Habitat.Type == "Mussel (mixed substrate)" & Year == "2021" ~ "M 2021",
Habitat.Type == "Mussel (mixed substrate)" & Year == "2021" ~ "M 2021"))
# Compute summary statistics
library(dplyr)
df.summary <- SUSC_TRIG_subset %>%
group_by(Habitat_Cohort) %>%
summarise(ymin = mean(True.TRIG) - sd(True.TRIG),
ymax = mean(True.TRIG) + sd(True.TRIG),
TRIG = mean(True.TRIG))
df.summary
# Create plot
dodge <- position_dodge(width = 0.9)
ggplot(df.summary, aes(x = interaction(Habitat_Cohort, Season), y = True.TRIG, fill = factor(Month))) +
geom_bar(stat = "identity", position = position_dodge()) +
geom_errorbar(aes(ymax = ymax, ymin = ymin), position = dodge, width = 0.2)
I get the following error:
Error: unexpected ')' in:
" geom_bar(stat = "identity", position = position_dodge()) +
geom_errorbar(aes(ymax = ymax, ymin = ymin), position = dodge, width = 0.2))"
Please help!