How to add SE bars to bar-graph in R code?

Viewed 87

I'm new to R, and would like to add standard error bars to my bar-graph. I have the following code:

p1 <- ggplot(plot1, aes(x=factor(drink_type), y=value, fill = manipulation)) + 
  stat_summary(fun.y="mean", geom="bar", position="dodge") +
  theme_classic() +
 labs(x = 'Drink type', y = 'Evidence accumulation')

p1 + stat_summary(fun.data = mean_cl_normal, geom = "errorbar", width = .08, position = position_dodge(0.9)) 

However, I'm not sure whether this 'geom = "errorbar" produces the standard error bars (which is what I am after). This is the data I am working from. I wonder if I need to create a new column that is the SE of the 'value' column in order to present the standard error bars?

ppt | manipulation |   drink_type           |  value
1   |       n      |   avg_alcohol_drift    |  1.8854094
1   |       p      |   avg_alcohol_drift    |  1.6257274
1   |       n      |   avg_softdrink_drift  |  1.8519074
1   |       p      |   avg_softdrink_drift  |  1.8477995

Any help would be really appreciated!

1 Answers

Yes it should, you can try something like below, where I used an example dataset:

ggplot(ToothGrowth,aes(x=factor(dose),y=len,fill=supp)) + 
stat_summary(fun.y=mean,geom="bar",position=position_dodge()) + 
stat_summary(fun.data=mean_se,geom="errorbar",
position=position_dodge(0.9),width=0.2)

enter image description here

We can manually calculate it:

library(dplyr)
se_data = ToothGrowth %>% 
group_by(dose,supp) %>% 
summarise(mean=mean(len),se=sd(len)/sqrt(n()))

# A tibble: 6 x 4
# Groups:   dose [3]
   dose supp   mean    se
  <dbl> <fct> <dbl> <dbl>
1   0.5 OJ    13.2  1.41 
2   0.5 VC     7.98 0.869
3   1   OJ    22.7  1.24 
4   1   VC    16.8  0.795
5   2   OJ    26.1  0.840
6   2   VC    26.1  1.52 

ggplot(se_data,aes(x=factor(dose),y=mean,fill=supp)) + 
geom_bar(stat="identity",position="dodge") +
geom_errorbar(aes(ymin=mean-se,ymax=mean+se),
position=position_dodge(0.9),width=0.2)

enter image description here

Related