## Tuesday, November 17, 2015

### Error bars on points in R

Putting error bars on figures is surprisingly complicated sometimes (even in Excel...).  I have to google it every time for R.  Various packages can do it, but base R also has some functions that will help (segments and arrows).  I like arrows() because you don't have to draw extra bits to get the nice line on the end of your error bars, which it seems you need to do if you use segments().

#Plot your center points; you could use your averages or other value here.
#Play around with the values in x and y to see what numbers move which part.
plot(x=c(1,2),
y=c(2,3),
xlim=c(0,3),
ylim=c(0,5),
xlab="x",
ylab="y",
pch=21, bg="black")

#Here are error bars on the left point at (1,2).
arrows(x0=c(1,1),
y0=c(2,2),
x1=c(1,1),
y1=c(1,3),
length=0.25,
angle=90)

#you can draw each error bar one at a time to get a better idea of how the code works.
#I show these in blue so you can see as it draws over the original bar on the plot.
arrows(x0=c(1),
y0=c(2),
x1=c(1),
y1=c(1),
length=0.25,
angle=90,
col="blue")

#top error bar.
arrows(x0=c(1),
y0=c(2),
x1=c(1),
y1=c(3),
length=0.25,
angle=90,
col="blue")

#Then let's re-do the plot and draw error bars for both points at the same time.
plot(x=c(1,2),
y=c(2,3),
xlim=c(0,3),
ylim=c(0,5),
xlab="x",
ylab="y",
pch=21, bg="black")

arrows(x0=c(1,1,2,2),
y0=c(2,2,3,3),
x1=c(1,1,2,2),
y1=c(1,3,2,4),
length=0.25,
angle=90)

#You can see you end up with a list of points,
#so you can set these values from other calculations you make of
#standard deviation, standard error, confidence intervals,
#or whatever you are using.