0

I want to add error bars to all the bars in my waterfall plots.

Here is a sample data and the code I am using to create the plots:

library(dplyr)
library(ggplot2)
set.seed(100)

df<-tibble(Year= c(2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003), Vals = abs(rnorm(12)*5), Affil = as.factor(c(1,2,1,2,1,2,1,2,1,2,1,2)), SD=rnorm(12, 1, 0.5))
df[c(T, T, F, F),]$Vals <- -(df[c(T, T, F, F),]$Vals)


p <- ggplot(data = df, aes(Year,Vals)) + 
  geom_bar(stat = "identity", aes(fill=Affil), position=position_dodge()) + 
  geom_errorbar(aes(ymin=Vals-SD, ymax=Vals+SD), width=.2, position=position_dodge(.9))
p + theme_bw(base_size = 16) + geom_hline(aes(yintercept=0), size=1.25) 

For each year, there should be 2 pairs of error bars. Two for each Affil and 2 for the positive and negative values associated with each Affil each year. I have tried inline filtering suing dplyr to add the error bars step by step but the solution is getting cumbersome and not working.

DotPi
  • 3,977
  • 6
  • 33
  • 53

1 Answers1

1

I was able to do it by assigning a color aesthetic to the errorbar:

p <- ggplot(data = df, aes(Year,Vals)) + 
  geom_bar(stat = "identity", aes(fill=Affil), position=position_dodge()) + 
  geom_errorbar(aes(ymin=Vals-SD, ymax=Vals+SD, color=Affil), width=.2, position=position_dodge(0.9))
p + theme_bw(base_size = 16) + geom_hline(aes(yintercept=0), size=1.25) +
  scale_color_manual(values=c("firebrick4","darkblue"))

enter image description here

To avoid overlapping the error bars you could use position_jitterdodge, but that creates some weird lines that for what i searched you can solve by doing this: align points and error bars in ggplot when using `jitterdodge`

  • This is a very elegant solution. I am getting the result I want. Thanks! However, in you figure, you do not seem to get any negative bars. Is that a artifact of your random data? – DotPi Nov 09 '20 at 13:59
  • Oh i forgot to run `df[c(T, T, F, F),]$Vals <- -(df[c(T, T, F, F),]$Vals)`, i think that that's why – Ricardo Semião e Castro Nov 09 '20 at 14:45