Home > Software design >  standard-error bars in bar plot not grouped
standard-error bars in bar plot not grouped

Time:11-19

I'm trying to do a bar plot with bars for conditions 1 and 2 in x, filled with the two levels of V2, with V3 corresponding to the counts in the y. V3 corresponds to the mean values and sds to the standard deviations.

df <- data.frame(V3 = c(0.87,0.78,0.9, 0.65),
                 V2 = c("A","B","C","D"), 
                 V1 = c("OT","OT","PL","PL"),
                 sd = c(0.3,0.4, 0.2, 0.1))

ggplot(df, aes(x=V1,y=V3, fill = V2))   
  geom_bar(stat = "identity", width = 0.2, position = "dodge") 
  ylim(0,1)   
  geom_errorbar(aes(ymin=V3-sd, ymax=V3 sd), width=.2)

This is what happens:

aqui

How can I solve this issue with the error bars? And also, change the colors of the bars? It is also not doing anything when I add a label...

labs(x = "legendX", y = "legendY") 

CodePudding user response:

You need to add position = position_dodge() inside the geom_errorbar. Also, ylim cuts values outside the limits, and several ymax are >1, so they dissapear from the graph. Added some nice colors NEJM style.

ggplot(df, aes(x=V1,y=V3, fill = V2))   
geom_bar(stat = "identity", width = 0.2, position = "dodge") 
#  ylim(0,1)   
geom_errorbar(aes(ymin=V3-sd, ymax=V3 sd), width=.2, position = position_dodge())  
scale_fill_manual(values=c("#c7533b", "#5b86c3", "#9fc66d", "#e39e3e"))

enter image description here

  • Related