First, it is necessary to summarize the data. This can be done in a number of ways, as described on this page. In this case, we’ll use the summarySE() function defined on that page, and also at the bottom of this page. (The code for the summarySE function must be entered before it is called here).

Line graphs

After the data is summarized, we can make the graph. These are basic line and point graph with error bars representing either the standard error of the mean, or 95% confidence interval.

# Standard error of the mean
ggplot(tgc,aes(x=dose,y=len,colour=supp))+geom_errorbar(aes(ymin=len-se,ymax=len+se),width=.1)+geom_line()+geom_point()# The errorbars overlapped, so use position_dodge to move them horizontally
pd<-position_dodge(0.1)# move them .05 to the left and right
ggplot(tgc,aes(x=dose,y=len,colour=supp))+geom_errorbar(aes(ymin=len-se,ymax=len+se),width=.1,position=pd)+geom_line(position=pd)+geom_point(position=pd)# Use 95% confidence interval instead of SEM
ggplot(tgc,aes(x=dose,y=len,colour=supp))+geom_errorbar(aes(ymin=len-ci,ymax=len+ci),width=.1,position=pd)+geom_line(position=pd)+geom_point(position=pd)# Black error bars - notice the mapping of 'group=supp' -- without it, the error
# bars won't be dodged!
ggplot(tgc,aes(x=dose,y=len,colour=supp,group=supp))+geom_errorbar(aes(ymin=len-ci,ymax=len+ci),colour="black",width=.1,position=pd)+geom_line(position=pd)+geom_point(position=pd,size=3)

A finished graph with error bars representing the standard error of the mean might look like this. The points are drawn last so that the white fill goes on top of the lines and error bars.

Bar graphs

The procedure is similar for bar graphs. Note that tgc$size must be a factor. If it is a numeric vector, then it will not work.

# Use dose as a factor rather than numeric
tgc2<-tgctgc2$dose<-factor(tgc2$dose)# Error bars represent standard error of the mean
ggplot(tgc2,aes(x=dose,y=len,fill=supp))+geom_bar(position=position_dodge(),stat="identity")+geom_errorbar(aes(ymin=len-se,ymax=len+se),width=.2,# Width of the error bars
position=position_dodge(.9))# Use 95% confidence intervals instead of SEM
ggplot(tgc2,aes(x=dose,y=len,fill=supp))+geom_bar(position=position_dodge(),stat="identity")+geom_errorbar(aes(ymin=len-ci,ymax=len+ci),width=.2,# Width of the error bars
position=position_dodge(.9))

Error bars for within-subjects variables

When all variables are between-subjects, it is straightforward to plot standard error or confidence intervals. However, when there are within-subjects variables (repeated measures), plotting the standard error or regular confidence intervals may be misleading for making inferences about differences between conditions.

The method below is from Morey (2008), which is a correction to Cousineau (2005), which in turn is meant to be a simpler method of that in Loftus and Masson (1994). See these papers for a more detailed treatment of the issues involved in error bars with within-subjects variables.

One within-subjects variable

Here is a data set (from Morey 2008) with one within-subjects variable: pre/post-test.

The value and value_norm columns represent the un-normed and normed means. See the section below on normed means for more information.

Understanding within-subjects error bars

This section explains how the within-subjects error bar values are calculated. The steps here are for explanation purposes only; they are not necessary for making the error bars.

The graph of individual data shows that there is a consistent trend for the within-subjects variable condition, but this would not necessarily be revealed by taking the regular standard errors (or confidence intervals) for each group. The method in Morey (2008) and Cousineau (2005) essentially normalizes the data to remove the between-subject variability and calculates the variance from this normalized data.

# Use a consistent y range
ymax<-max(dfw_long$value)ymin<-min(dfw_long$value)# Plot the individuals
ggplot(dfw_long,aes(x=condition,y=value,colour=subject,group=subject))+geom_line()+geom_point(shape=21,fill="white")+ylim(ymin,ymax)# Create the normed version of the data
dfwNorm.long<-normDataWithin(data=dfw_long,idvar="subject",measurevar="value")# Plot the normed individuals
ggplot(dfwNorm.long,aes(x=condition,y=value_norm,colour=subject,group=subject))+geom_line()+geom_point(shape=21,fill="white")+ylim(ymin,ymax)

The differences in the error bars for the regular (between-subject) method and the within-subject method are shown here. The regular error bars are in red, and the within-subject error bars are in black.

Two within-subjects variables

If there is more than one within-subjects variable, the same function, summarySEwithin, can be used. This data set is taken from Hays (1994), and used for making this type of within-subject error bar in Rouder and Morey (2005).

Note about normed means

The summarySEWithin function returns both normed and un-normed means. The un-normed means are simply the mean of each group. The normed means are calculated so that means of each between-subject group are the same. These values can diverge when there are between-subject variables.

Helper functions

The summarySE function is also defined on this page. If you only are working with between-subjects variables, that is the only function you will need in your code. If you have within-subjects variables and want to adjust the error bars so that inter-subject variability is removed as in Loftus and Masson (1994), then the other two functions, normDataWithin and summarySEwithin must also be added to your code; summarySEwithin will then be the function that you call.

## Gives count, mean, standard deviation, standard error of the mean, and confidence interval (default 95%).
## data: a data frame.
## measurevar: the name of a column that contains the variable to be summariezed
## groupvars: a vector containing names of columns that contain grouping variables
## na.rm: a boolean that indicates whether to ignore NA's
## conf.interval: the percent range of the confidence interval (default is 95%)
summarySE<-function(data=NULL,measurevar,groupvars=NULL,na.rm=FALSE,conf.interval=.95,.drop=TRUE){library(plyr)# New version of length which can handle NA's: if na.rm==T, don't count them
length2<-function(x,na.rm=FALSE){if(na.rm)sum(!is.na(x))elselength(x)}# This does the summary. For each group's data frame, return a vector with
# N, mean, and sd
datac<-ddply(data,groupvars,.drop=.drop,.fun=function(xx,col){c(N=length2(xx[[col]],na.rm=na.rm),mean=mean(xx[[col]],na.rm=na.rm),sd=sd(xx[[col]],na.rm=na.rm))},measurevar)# Rename the "mean" column
datac<-rename(datac,c("mean"=measurevar))datac$se<-datac$sd/sqrt(datac$N)# Calculate standard error of the mean
# Confidence interval multiplier for standard error
# Calculate t-statistic for confidence interval:
# e.g., if conf.interval is .95, use .975 (above/below), and use df=N-1
ciMult<-qt(conf.interval/2+.5,datac$N-1)datac$ci<-datac$se*ciMultreturn(datac)}

## Norms the data within specified groups in a data frame; it normalizes each
## subject (identified by idvar) so that they have the same mean, within each group
## specified by betweenvars.
## data: a data frame.
## idvar: the name of a column that identifies each subject (or matched subjects)
## measurevar: the name of a column that contains the variable to be summariezed
## betweenvars: a vector containing names of columns that are between-subjects variables
## na.rm: a boolean that indicates whether to ignore NA's
normDataWithin<-function(data=NULL,idvar,measurevar,betweenvars=NULL,na.rm=FALSE,.drop=TRUE){library(plyr)# Measure var on left, idvar + between vars on right of formula.
data.subjMean<-ddply(data,c(idvar,betweenvars),.drop=.drop,.fun=function(xx,col,na.rm){c(subjMean=mean(xx[,col],na.rm=na.rm))},measurevar,na.rm)# Put the subject means with original data
data<-merge(data,data.subjMean)# Get the normalized data in a new column
measureNormedVar<-paste(measurevar,"_norm",sep="")data[,measureNormedVar]<-data[,measurevar]-data[,"subjMean"]+mean(data[,measurevar],na.rm=na.rm)# Remove this subject mean column
data$subjMean<-NULLreturn(data)}

## Summarizes data, handling within-subjects variables by removing inter-subject variability.
## It will still work if there are no within-S variables.
## Gives count, un-normed mean, normed mean (with same between-group mean),
## standard deviation, standard error of the mean, and confidence interval.
## If there are within-subject variables, calculate adjusted values using method from Morey (2008).
## data: a data frame.
## measurevar: the name of a column that contains the variable to be summariezed
## betweenvars: a vector containing names of columns that are between-subjects variables
## withinvars: a vector containing names of columns that are within-subjects variables
## idvar: the name of a column that identifies each subject (or matched subjects)
## na.rm: a boolean that indicates whether to ignore NA's
## conf.interval: the percent range of the confidence interval (default is 95%)
summarySEwithin<-function(data=NULL,measurevar,betweenvars=NULL,withinvars=NULL,idvar=NULL,na.rm=FALSE,conf.interval=.95,.drop=TRUE){# Ensure that the betweenvars and withinvars are factors
factorvars<-vapply(data[,c(betweenvars,withinvars),drop=FALSE],FUN=is.factor,FUN.VALUE=logical(1))if(!all(factorvars)){nonfactorvars<-names(factorvars)[!factorvars]message("Automatically converting the following non-factors to factors: ",paste(nonfactorvars,collapse=", "))data[nonfactorvars]<-lapply(data[nonfactorvars],factor)}# Get the means from the un-normed data
datac<-summarySE(data,measurevar,groupvars=c(betweenvars,withinvars),na.rm=na.rm,conf.interval=conf.interval,.drop=.drop)# Drop all the unused columns (these will be calculated with normed data)
datac$sd<-NULLdatac$se<-NULLdatac$ci<-NULL# Norm each subject's data
ndata<-normDataWithin(data,idvar,measurevar,betweenvars,na.rm,.drop=.drop)# This is the name of the new column
measurevar_n<-paste(measurevar,"_norm",sep="")# Collapse the normed data - now we can treat between and within vars the same
ndatac<-summarySE(ndata,measurevar_n,groupvars=c(betweenvars,withinvars),na.rm=na.rm,conf.interval=conf.interval,.drop=.drop)# Apply correction from Morey (2008) to the standard error and confidence interval
# Get the product of the number of conditions of within-S variables
nWithinGroups<-prod(vapply(ndatac[,withinvars,drop=FALSE],FUN=nlevels,FUN.VALUE=numeric(1)))correctionFactor<-sqrt(nWithinGroups/(nWithinGroups-1))# Apply the correction factor
ndatac$sd<-ndatac$sd*correctionFactorndatac$se<-ndatac$se*correctionFactorndatac$ci<-ndatac$ci*correctionFactor# Combine the un-normed means with the normed results
merge(datac,ndatac)}

Cookbook for R

This site is powered by knitr and Jekyll. If you find any errors, please email winston@stdout.org