1

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?

steveb
  • 5,382
  • 2
  • 27
  • 36
Juan
  • 13
  • 2
  • 1
    You are expected to provide a starting point for coding in the form of both data and code. – IRTFM Oct 01 '18 at 02:14
  • Please see [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). You should provide a reproducible example. – steveb Oct 01 '18 at 04:24

1 Answers1

1

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) 
Grubbmeister
  • 857
  • 8
  • 25
  • Given the attempt of OP to use the `arrows` command, that suggests that `ggplot2` is not being used. However, when the OP provides a more complete question, providing a more complete `ggplot2` answer will be good. – steveb Oct 01 '18 at 04:28
  • Ah, yes - I forgot the arrow is called from inside geom_segment in ggplot2... Been making too many graphs lately – Grubbmeister Oct 01 '18 at 04:31