Wednesday, 11 May 2011

Bar Plots with Error Bars in R

I've given up on Sigmaplot and dove back into plotting my results in R. This is a document of a process to plot means + standard error of the means (SEM).

First off, here's an example data set (FreeF.csv) in .csv format:
Sample,FreeF,State
1,63.46,A
2,0.5,B
3,0.33,C
4,0.16,B
5,0.45,C
6,0.1,C
7,0.18,B
8,0.6,A
9,2.01,A
10,16.84,C
11,1.27,C
12,0.14,B
13,1.75,C
14,5.13,B
15,0.84,A
16,0.82,A
17,3.52,A
18,0.4,C
19,0.12,B
I'll read this file into R:
> freef = read.csv(file="FreeF.csv",head=T,sep=",")
Next, we'll enter a function that I've borrowed and altered that will plot error bars for me from Monkey's Uncle. This function will plot a positive error bar only, unlike the original function.
> error.bar = function(x, y, upper, length=0.1,...){
+ arrows(x,y+upper, x, y, angle=90, code=1, length=length, ...) 
+ }
For this example data set, I have 3 states: A, B, and C. We'll have to calculate and store the FreeF means and standard errors for each state. We'll use the aggregate() function to do so:
> freef.mean = aggregate(freef$FreeF,by=list(freef$State),FUN=mean)
> freef.sd = aggregate(freef$FreeF,by=list(freef$State),FUN=sd)
> freef.n = aggregate(freef$FreeF,by=list(freef$State),FUN=length)
> freef.sem = freef.sd$x / sqrt(freef.n$x)
 We can now plot the data. First, we plot the means:
> freef.bp = barplot(freef.mean$x, main="FreeF By State", ylab="FreeF", xlab="State", ylim=range(0,25),  names.arg=freef.mean$Group.1, axis.lty=1)
This will plot a vertical bar plot for the FreeF means aggregated by State. I'll explain the arguments in the command:
main: Sets the title of the plot
ylab: Sets the y-axis label
xlab: Sets the x-axis label
ylim: Sets the y-axis limits
names.arg: Sets the x-axis labels for each State (A, B, and C)
axis.lty=1: Displays the x-axis in the same style as the y-axis (otherwise, it won't show the x-axis at all)
 Now to add the error bars:
> error.bar(freef.bp,freef.mean$x,freef.sem)
 Those are some massive-looking error bars. Oh well, back to lab.

No comments:

Post a Comment