Tuesday, February 14, 2017

Making Barplot with Confidence Intervals


my.barplot  <- function(h, hl, hu, ...)
{ 
    ## Purpose: Template function for making Barplot with Confidence Interval.
    ##          Require R package "gplots". Refer to documentation of "gplots::barplots2". 
    ## Arguments:
    ##   h: Height Matrix. Each column is a group of heights. The dimnames will be used for labeling.
    ##   hl: Lower CI. Same dimension as "h". 
    ##   hu: Upper CI. Same dimension as "h".
    ##   ...: passed to "gplots::barplot2"
    ## Return: 
    ## Author: Feiming Chen, Date: 14 Feb 2017, 14:22
    ## ________________________________________________

    old.par <- par("mar")
    par(mar = c(5, 10, 4, 5))
    gplots::barplot2(h, beside = T, legend.text = T, horiz = T, col=rainbow(ncol(h)), border = NA, 
                     cex.axis = 2, cex.names = 1.5, cex.lab=2, las = 1, xpd = F,
                     plot.ci = TRUE, ci.l = hl, ci.u = hu, ci.width = 0.3, ci.lwd = 2, 
                     plot.grid = TRUE, 
                     ...) -> mp

    ## Put numbers on the bars 
    for (i in seq(ncol(mp))) text(1, mp[,i], labels=round(h[,i], 2), cex=2)
    par(old.par)
}
if (F) {                                # Unit Test
    x <- structure(c(9.5, 10.5, 1.2, 0.4, 7, 12, 9.8, 11.2, 8.3, 9.6, 0.8, 0.3, 6.7, 9.8, 9, 10.2), .Dim = c(8L, 2L), .Dimnames = list(c("Type R", "Type B", "R.SD", "B.SD", "Rl", "Ru", "Bl", "Bu"), c("Class 1", "Class 2")))
    h <- x[1:2,]
    hl <- x[c(5,7),]
    hu <- x[c(6,8),]
    my.barplot(h, hl, hu, main="Comparison", xlab="Average Result", xlim = c(0, 20))
}


No comments:

Post a Comment