Search code examples
rggplot2tidyversebar-charterrorbar

How can I modify and improve the visualization of my error bars?


How to customize my error in the way that they are located at the middle of my bar instead of the awkward alignment as shown in attached image? I've tried to google search but couldn't find any solution.

My data frame:

data.frame(Exp1_fv)

growth_condition time  N        fv          sd          se         ci
Normal              0.0 3 0.8066667 0.005773503 0.003333333 0.01434218
Normal              0.5 3 0.8033333 0.011547005 0.006666667 0.02868435
Normal              8.0 3 0.8100000 0.010000000 0.005773503 0.02484138
Normal              24.0 3 0.8166667 0.005773503 0.003333333 0.01434218
Normal              48.0 3 0.8100000 0.010000000 0.005773503 0.02484138
High light+Chilled  0.0 3 0.8133333 0.005773503 0.003333333 0.01434218
High light+Chilled  0.5 3 0.6766667 0.068068593 0.039299420 0.16909176
High light+Chilled  8.0 3 0.4433333 0.095043850 0.054873592 0.23610201
High light+Chilled  24.0 3 0.3900000 0.045825757 0.026457513 0.11383749
High light+Chilled  48.0 3 0.6966667 0.035118846 0.020275875 0.08724005

My scripts:

Exp1_fv <- summarySE(data = Exp1, measurevar = "fv", groupvars = c("growth_condition", "time"))

ggplot(data = Exp1_fv, mapping = aes(x = factor(time), y = fv)) +
  geom_bar(stat = "identity", aes(fill = growth_condition), position = "dodge") +

  labs(title = "Fv/Fm", x = "Time (hours)",  y = "Fv/Fm", fill= "Growth condition") +
  ylim(0,1.0) +
  geom_errorbar(aes(ymin = fv - se, ymax = fv + se), width = 0.1, position = position_dodge(0.1))

enter image description here


Solution

  • errorbars do not have a width. As per position_dodge() help, when you want to dodge two different geoms with variable width (in your case geom_bar and geom_errorbar), you need to explicitly provide width argument for position_dodge(). In your case the solution should be:

    Exp1_fv<-summarySE(data=Exp1, measurevar="fv", groupvars=c("growth_condition","time"))
    
    ggplot(
      data=Exp1_fv,
      mapping = aes(x = factor(time), y = fv, fill = growth_condition)
    )+
      geom_bar(stat = "identity", position = position_dodge())+
      labs(title="Fv/Fm", x= "Time (hours)", y="Fv/Fm", fill= "Growth condition")+
      ylim(0,1.0)+
      geom_errorbar(
        aes(ymin=fv-se, ymax=fv+se),
        width=.2,
        position = position_dodge(width = 0.9)
      )
    

    Since the data is not provided, it is difficult to test and verify if this would solve your problem.

    Output: