geom_errorbar and geom_ribbon working together

404 Views Asked by At

I want to plot error bars and a ribbon shaded area to mark the average of the values of the error bars:

enter image description here

For some reason I cannot make geom_errorbar and geom_ribbon work together. A sample code:

group <- c("Group 1", "Group 1", "Group 2", "Group 2", 
           "Group 3", "Group 3", "Group 4", "Group 4")
subgroup <- c("High", "Low", "High", "Low", "High", "Low", "High", "Low")
value <- c(0.1,-0.1,0.4,0.5,0.25,0.6,-0.25,0.05)
sd <- c(0.1,0.1,0.05,0.05,-0.05,-0.05,-0.01,-0.01)
value_avg <- c(0.33,0.33,0.33,0.33, 0.33, 0.33,0.33,0.33)
sd_avg <- c(0.07,0.07,0.07,0.07,0.07,0.07,0.07,0.07)

df <- data.frame(group, subgroup,value,sd)

#Plot
ggplot(df, aes(group, value)) +
  geom_errorbar(
    aes(ymin = value-sd, ymax = value+sd, color = subgroup),
    position = position_dodge(0.3), width = 0.3
  )+
  geom_point(aes(color = subgroup), position = position_dodge(0.3))+
  geom_ribbon(aes(ymin = value_avg-sd_avg, ymax = value_avg+sd_avg), 
              fill = "grey70") 

Edit 1: Showing Stefan's suggestion:

geom_ribbon(aes(ymin = value_avg-sd_avg, ymax = value_avg+sd_avg, group = 1)

enter image description here

0

There are 0 best solutions below