Add error bars to a plot in R

download R script here.

### Plotting function to plot y- or x-axis error bars
### Filename: Plot_ErrorBars.R
### Notes:
############################################################################

# INPUTS:
# x: x-axis data
# y: y-axis data
# x.err: error bars for x-axis data
# y.err: error bars for y-axis data
# xbar: Whether error bars for x-axis values should be plotted (Default is F)
# ybar: Whether error bars for y-axis values should be plotted (Default is F)
# cap.scaling: scaling factor for size of error bar caps. Default is 50.
# xcolor: line color. (Default is black)
# ycolor: line color. (Default is black)
# lwidth: line width (Default is 1)

# OUTPUTS:
# error bars for x-axis data, y-axis data, or both.

# FUNCTION:
Plot_ErrorBars<-function(x, y, x.err, y.err, xbar = F,
                         ybar = F, cap.scaling = 50, xcolor = "black",
                         ycolor = "black", lwidth = 1, ...){
  ycap.width <- (par("usr")[4] - par("usr")[3])/cap.scaling
  xcap.width <- (par("usr")[2] - par("usr")[1])/cap.scaling
  if(xbar == T){
    for(i in 1:length(x.err)){
      segments(x0 = x[i] + x.err[i], y0 = y[i], 
               x1= x[i] - x.err[i],  y1 = y[i],
               lwd = lwidth, col = xcolor)
      segments(x0 = x[i] + x.err[i], y0 = y[i] + ycap.width,
               x1=x[i] + x.err[i],   y1 = y[i] - ycap.width,
               lwd = lwidth, col = xcolor)
      segments(x0 = x[i] - x.err[i], y0 = y[i] + ycap.width,
               x1=x[i] - x.err[i],   y1 = y[i] - ycap.width,
               lwd = lwidth, col = xcolor)
    }
  } 
  if(ybar == T){
    for(i in 1:length(y.err)){
      segments(x0 = x[i], y0 = y[i] + y.err[i], 
               x1= x[i],  y1 = y[i] - y.err[i],
               lwd = lwidth, col = ycolor)
      segments(x0 = x[i] + xcap.width, y0 = y[i] + y.err[i],
               x1=x[i] - xcap.width,   y1 = y[i] + y.err[i],
               lwd = lwidth, col = ycolor)
      segments(x0 = x[i] + xcap.width, y0 = y[i] - y.err[i],
               x1=x[i] - xcap.width,   y1 = y[i] - y.err[i],
               lwd = lwidth, col = ycolor)
    }
  }
} 
# END OF FUNCTION

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s