[R] plot graph with error bars trouble
hadley wickham
h.wickham at gmail.com
Sun Sep 30 21:15:16 CEST 2007
On 9/30/07, Ben Bolker <bolker at ufl.edu> wrote:
> Marcelo Laia <marcelolaia <at> gmail.com> writes:
>
> >
> > Hi,
> >
> > I have a data set like this:
> >
>
> [snip]
>
> > I need to plot a graph OD over the time for each one mutant with error bars.
> >
> >
>
>
> ## I put your data in a temporary file, this reads it
> x = read.table("tempdata.txt",header=TRUE)
>
>
> ## compute means and standard errors
> ## (no built-in function for standard error, so create one)
> ## also see ?aggregate, ?by
> means = with(x,tapply(OD,list(Time,Mutant),mean))
> se = function(x) sd(x)/sqrt(length(x))
> ses = with(x,tapply(OD,list(Time,Mutant),se))
>
> ## time vector -- could also be unique(x$Time)
> times = as.numeric(rownames(means))
>
> ## plot the means
> matplot(times,means,type="b",lty=1,col=1:2,pch=1:2)
> library(plotrix)
> ## have to create the x-vector and color-vector "by hand"
> ## it would be nice if there were a matplotCI, but there
> ## isn't (yet) ...
> plotCI(rep(times,2),means,ses,pch=NA,add=TRUE,
> col=rep(1:2,each=nrow(means)))
I'd do this a little differently, using the reshape
(http://had.co.nz/reshape) and ggplot2 (http://had.co.nz/ggplot2)
packages:
library(reshape)
library(ggplot2)
# Get data in format required for reshape
df <- rename(df, c("OD" = "value"))
# Summarise and compute errors
se <- function(x) sd(x)/sqrt(length(x))
means <- cast(df, Mutant + Time ~ ., c(mean, se))
qplot(Time, mean, data=means, colour=Mutant, min = mean - se, max =
mean + se, geom=c("point","errorbar"))
# or maybe
qplot(Time, mean, data=means, colour=Mutant, min = mean - se, max =
mean + se, geom=c("line","errorbar"))
# or even
qplot(Time, mean, data=means, fill=Mutant, min = mean - se, max = mean
+ se, geom=c("ribbon", "line"))
Depending on the purpose of the error bars, you will want to adjust
their length.
Hadley
--
http://had.co.nz/
More information about the R-help
mailing list