Error bars on Barplots

First of all, install package Hmisc by running the code below and then load it using the next command.

# Install Hmisc
if (!"Hmisc" %in% installed.packages()) install.packages("Hmisc", repos = "http://cran.us.r-project.org", 
    dependencies = T)

# Load package Hmisc
library(Hmisc)

Then we create a dummy dataset like below. And see how it looks like.

# Create dummy dataframe
test <- data.frame(samples = c("A", "B", "C", "D"), value = c(50, 70, 20, 40), 
    high = c(55, 75, 28, 50), low = c(45, 68, 14, 30))

# View dataframe
test
##   samples value high low
## 1       A    50   55  45
## 2       B    70   75  68
## 3       C    20   28  14
## 4       D    40   50  30

We see 4 samples with the mean values as value and the confidence intervals, or standard deviation or standard error or whatever is represented by high and low. The high will the top of the error bar and low will be bottom of the error bar.

Now we make a function to plot the barplot.

barplotgrz <- function(mean, names, high, low, ...) {
    br1 <- barplot(height = mean, names.arg = names, ylim = c(0, max(high)), 
        ...)
    errbar(x = br1, y = mean, yplus = high, yminus = low, add = T, cex = 0)
}

And to plot the figure, now we use the new function we just made. The input is from the dummy dataset we made. We pass on the mean values, the sample names, high and low error limits.

barplotgrz(test$value, names = test$samples, high = test$high, low = test$low)

plot of chunk unnamed-chunk-4