Search code examples
rggplot2errorbar

Using ggplot2 to plot geom_errorbar for Date in R


In many cases, we need to demonstrate the standard error. In ggplot2, we can do it using the geom_errorbar function. I find that when the x variable is of the Date type, ggplot2 could not plot the error bar completely. See the R script below for more information.

library(gcookbook) # For the data set
# Take a subset of the cabbage_exp data for this example
ce <- subset(cabbage_exp, Cultivar == "c39")
# With a line graph

p1 = ggplot(ce, aes(x=Date, y=Weight)) +
  geom_line(aes(group=1)) +
  geom_point(size=4) +
  geom_errorbar(aes(ymin=Weight-se, ymax=Weight+se), width=.2)

ce$Date = as.Date(c('01/01/2001', '01/01/2002', '01/01/2003'), "%m/%d/%Y") 

p2 = ggplot(ce, aes(x=Date, y=Weight)) +
  geom_line(aes(group=1)) +
  geom_point(size=4) +
  geom_errorbar(aes(ymin=Weight-se, ymax=Weight+se), width=.2)

p1
p2

enter image description here


Solution

  • Simply following RHA's directions (code below). @RHA, please feel free to copy my answer into a new one as it's more yours then it's mine.

    geom_errorbar of width

    # install.packages("gcookbook", dependencies = TRUE)
    library(gcookbook) # For the data set
    # Take a subset of the cabbage_exp data for this example
    ce <- subset(cabbage_exp, Cultivar == "c39")
    # With a line graph
    
    # install.packages("ggplot2", dependencies = TRUE)
    require(ggplot2)
    
    ce$Date = as.Date(c('01/01/2001', '01/01/2002', '01/01/2003'), "%m/%d/%Y") 
    
    (p2 = ggplot(ce, aes(x=Date, y=Weight)) +
      geom_line(aes(group=1)) +
      geom_point(size=4) +
      geom_errorbar(aes(ymin = Weight- se, ymax= Weight + se), width=45)))