#' add asymertric error bars to existing scatter plot
#'
#' \code{errorbars(mat,bplot=NULL,wid=max(explan/100),lty=1,brk=0,...)}
#'
#' @param mat a matrix or data frame of values to specify error bars. First column should
#' be either x-axis values or (if adding to a barplot) y-axis values of bar centres
#' (usually means). Second column should be y-axis values of bar centres or (if barplot)
#' size of error bar. Third column should be size of error bar. If an additional column
#' is given (third column for barplot, fourth column otherwise), these are size of bar
#' from centre to upper limit and the previous column used for sizes of bar from centre
#' to lower limit.
#' @param bplot the name of an existing barplot (if adding error bars to barplot)
#' @param wid width of bar ends
#' @param brk size of break in vertical bar around data point
#' @param ... further graphical parameters to pass to lines() function
#'
#' @details Add error bars to existing plots, either barplot or some other type,
#' most likely scatter. The values are supplied as a matrix (or data frame) with
#' n columns (or n-1) columns for a barplot where the x-axis values are not supplied
#' but taken from the barplot. Columns must include the y-axis mid values (usually the
#' mean values) and a size of error bar. If asymmetrical bars are required, there will
#' be an additional column of the matrix containing these.
#'
#' @examples
#' # use the library dplyr
#' Rock = rock %>% group_by(perm) %>%
#' summarise(Mn = mean(shape), CI95 = sd(shape)/length(shape)^2*2) %>%
#' as.matrix()
#' plot(Mn ~ perm, Rock, pch = 19, cex = 0.6, ylim=c(.12,.4))
#' bars(Rock, brk = 0.008)
#' # Barplot
#' MatBP = InsectSprays %>% group_by(spray) %>%
#' summarise(Mn = mean(count), SD = sd(count)) %>% as.data.frame()
#' BP = barplot(MatBP[,2], ylim=c(0,24))
#' bars(MatBP[,-1], bplot=BP, wid=0.1, brk = 0.5)
errorbars=function(mat,bplot=NULL,wid=NULL,lty=1,brk=0,...){
L=nrow(mat)
ind=1 # index for matrix column of x-axis values
if(!is.null(bplot)){
x=as.numeric(bplot) # use barplot values for x-axis
ind=ind-1
} else {x = mat[,ind]}
# get the value of mid, lower and upper of error bar.
ymid = mat[,ind+1]
ylolo = ymid - mat[,ind+2]
yhihi = ymid + mat[,ind+2]
if(ncol(mat)-ind == 3) yhihi = ymid + mat[,ind+3]
# starts of bars neareast mid after brk is incorporated:
ylohi = ymid - brk/2
yhilo = ymid + brk/2
# bar end points; left and right:
if(is.null(wid)) wid = max(x/100)
xlft = x-wid/2
xrt = x+wid/2
for (a in 1:L){
# vertical bars
lines(c(x[a],x[a]), c(ylolo[a],ylohi[a]), lend="square",...)
lines(c(x[a],x[a]), c(yhilo[a],yhihi[a]), lend="square",...)
# horizontal bar ends
lines(c(xlft[a],xrt[a]),c(ylolo[a],ylolo[a]), lend="square",...)
lines(c(xlft[a],xrt[a]),c(yhihi[a],yhihi[a]), lend="square",...)
}
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.