[R] Error bars on barplots for only particular bars
Jim Lemon
jim at bitwrit.com.au
Fri Jan 15 10:07:46 CET 2010
On 01/15/2010 08:43 AM, kellys17 wrote:
>
> Hi,
>
> I have a data set that has columns "bird.species", "tree.species"and
> "count". I am investigating differences in tree species usge by two species
> of birds. "Count" is numerical and is a count of observations of bird
> species x using tree species x. For bird species A I have 3 different counts
> for each tree species. For bird species B I have only 1 count for each tree
> species.
>
> I have generated a barplot using the following function:
> barplot(tapply(count,list(bird.species,tree.species),mean),beside=TRUE)
>
> This graph is so far ok and gives the mean count for bird species A.
> I want to add error bars to illustrate the variance in mean of bird species
> A for each tree species.
>
> The error bar function I am using is:
> error.bars<-function(yv,z,nn){
> xv<-barplot(yv,ylim=c(0,(max(yv)+max(z))),names=nn,
> ylab=deparse(substitute(yv)))
> g<-(max(xv)-min(xv))/50
> for (i in 1:length(xv)){lines(c(xv[i],xv[i]),c(yv[i]+z[i],yv[i]-z[i]))
> lines(c(xv[i]-g,xv[i]+g),c(yv[i]+z[i],yv[i]+z[i]))
> lines(c(xv[i]-g,xv[i]+g),c(yv[i]-z[i],yv[i]-z[i]))}}
>
> I used "error.bars(ybar1,se1,labels1)" to try generate the error bars with
> se1<-rep("standard error of a mean", "no. of numbers used to calculate
> mean")
> labels1<-as.character(levels(tree.species))
> ybar1<-as.vector(tapply(count,tree.species,mean))
>
> but the it failed and the resulting warning I got was:
> Error in barplot.default(yv, ylim = c(0, (max(yv) + max(z))), names = nn, :
> incorrect number of names
>
> I was wondering If anyone could help with me this warning, or point me in
> the right direction as to how to illustrate the variance in means from bird
> species A without adding any error bars to bird species B (which has no
> variance to show)?
Hi Sean,
The easiest way I can think of is to add a test to your error bar
drawing routine so that it does nothing when the variance is NA:
for(i in 1:length(xv)) {
if(!is.na(z[i])) {
lines...
}
}
However, the error is about the number of names not being equal to the
number of "heights", so you will have to make sure that is fixed, too.
Jim
More information about the R-help
mailing list