[R] Constructing bar charts with standard error bars

Ben Bolker bolker at ufl.edu
Wed Jul 25 18:24:47 CEST 2007


John Zabroski <johnzabroski <at> gmail.com> writes:

> 
> I am new to R.
> 
> I want to graph group data using a "Traditional Bar Chart with Standard
> Error Bar", like the kind shown here:
> http://samiam.colorado.edu/~mcclella/ftep/twoGroups/twoGroupGraphs.html
> 
> Is there a simple way to do this?

   [snip]

> The best clue I have so far is Rtips #5.9:
> http://pj.freefaculty.org/R/Rtips.html#5.9 which is what I based my present
> solution off of.
> 
> However, I do not understand how this works.  It seems like there is no
> concrete way to determine the arrow drawing parameters x0 and x1 for a
> barplot.  Moreover, the bars seem to be "cut off".
> 
  
  barplot() returns the x values you need for x0 and x1.
barplot(...,ylim=c(0,xbar+se)) will set the upper y limit so
the bars don't get cut off.

Here are three ways to create such a barplot (I will add
this to the wiki once it's back on line):  (n.b.: the
with() command is just a shortcut to avoid having
to type testdata$xbar, testdata$group, etc.)

## 1. tweaked version of what you did above

testdata <- data.frame(group=c(400,200,100,50,25),
	xbar= c(0.36038 , 0.35927 , 0.35925 , 0.35712 , 0.35396), 
	se = c(0.02154,0.02167,0.02341,0.01968,	0.01931))
xvals = with(testdata,
     barplot(xbar, names.arg=group, main="a=4.0",
        xlab="Group", ylab="xbar",ylim=c(0,max(xbar+se))))
with(testdata,
     arrows(xvals, xbar, xvals, xbar+se, length=0.4, angle=90, code=3))

## 2. using the plotCI function from plotrix to draw the
##    arrows instead
library(plotrix)
xvals = with(testdata,
     barplot(xbar, names.arg=group, main="a=4.0",
        xlab="Group", ylab="xbar",ylim=c(0,max(xbar+se))))
with(testdata,
     plotCI(xvals, xbar, liw=0,uiw=se,add=TRUE,pch=NA,gap=FALSE))

## 3. the most automatic way, using barplot2() from the
## gplots package

library(gplots)
with(testdata,
     barplot2(xbar,names.arg=group,main="a=4.0",
              xlab="Group",ylab="xbar",plot.ci=TRUE,
              ci.u=xbar+se,ci.l=xbar))

  P.S. I hope you're not hoping to infer a statistically
significant difference among these groups ...

  cheers
   Ben Bolker



More information about the R-help mailing list