Search code examples
rploterrorbar

How to build an error bar with a fixed value in R


I have a bar plot which I need to add an error bar to. It should be an error span which is the same for each column, so a bit different from standard error bars. In former questions only error bars dependent on mean or standard deviation were discussed. enter image description here

I tried the arrow function

arrows(dat$usage_time, dat$usage_time-1, dat$usage_time, dat$usage_time+1, length=0.05, angle=90, code=3)

but it didn't really work. dat$usage_time is an integer, which is supposed to go as a coordinate. What is the problem?


Solution

  • Yes, you need to provide data and code. Nevertheless, we will work with what we have.

    The first option was modified from here: https://datascienceplus.com/building-barplots-with-error-bars/ Assuming your error bars are +/-1, and with a dummy dataset:

    x<-c(1,1,1, 1, 2,2,2)
    y<-c(4,8,12,12,5,3,3)
    d<-as.data.frame(cbind(x,y))
    library(dplyr)
    d2<- d %>%   group_by(x) %>%   summarise_at(mean, .vars = vars(y)) 
    
    barplot<-barplot(height=d2$y, ylim=c(0, max(d2$y)+3))
    
    text(x = barplot, y = par("usr")[3] - 1, labels = d2$x)
    
    arrows(barplot,  d2$y-1, barplot, d2$y+1, length=0.05, angle=90, code=3)
    

    And to plot this in ggplot2, how about:

    ggplot(data=d2, aes(x=x,  y=y)) + 
      geom_bar(fill="grey", width=.8, stat="identity") + 
      xlab("date") + ylab("usage time") + 
    
      geom_errorbar(aes(ymin=y-1, ymax=y+1),     width=.2)