You are on page 1of 3

01/08/2015

r - Scatter plot with error bars - Stack Overflow

help

Scatterplotwitherrorbars

HowcanIgeneratethefollowingplotinR?Points,shownintheplotaretheaverages,andtheirrangescorrespondtominimaland
maximalvalues.Ihavedataintwofiles(belowisanexample).
xy
10.8773
10.8722
10.8816
10.8834
10.8759
10.8890
10.8727
20.9047
20.9062
20.8998
20.9044
20.8960
.....

r plot

editedOct23'12at15:10
Roland
51.7k

askedOct23'12at14:29
s_sherly

39

72

98

12

Sinceyouclearlydon'twantaboxplot,Ichangedthetitleofyourquestioninordertoreflectwhatyoureally
want.RolandOct23'12at15:11
1 also plotrix::plotCI, gplots::plotCI, library("sos")findFn("{errorbar}")
BenBolkerOct23'12at17:29

5Answers

Firstofall:itisveryunfortunateandsurprisingthatRcannotdrawerrorbars"outofthe
box".
Hereismyfavouriteworkaround,theadvantageisthatyoudonotneedanyextrapackages.
Thetrickistodrawarrows(!)butwithlittlehorizontalbarsinsteadofarrowheads(!!!).Thisnot
sostraightforwardideacomesfromtheRWikiTipsandisreproducedhereasaworkedout
example.
Let'sassumeyouhaveavectorof"averagevalues" avgandanothervectorof"standard
deviations" sdev,theyareofthesamelength n.Let'smaketheabscissajustthenumberof

http://stackoverflow.com/questions/13032777/scatter-plot-with-error-bars

1/3

01/08/2015

r - Scatter plot with error bars - Stack Overflow

these"measurements",so x<1:n.Usingthese,herecometheplottingcommands:
plot(x,avg,
ylim=range(c(avgsdev,avg+sdev)),
pch=19,xlab="Measurements",ylab="Mean+/SD",
main="Scatterplotwithstd.deverrorbars"
)
#hack:wedrawarrowsbutwithveryspecial"arrowheads"
arrows(x,avgsdev,x,avg+sdev,length=0.05,angle=90,code=3)

Theresultlookslikethis:

answeredFeb26'14at9:30
user465139
1,182

13

#someexampledata
set.seed(42)
df<data.frame(x=rep(1:10,each=5),y=rnorm(50))
#calculatemean,minandmaxforeachxvalue
library(plyr)
df2<ddply(df,.(x),function(df)c(mean=mean(df$y),min=min(df$y),max=max(df$y)))
#ploterrorbars
library(Hmisc)
with(df2,errbar(x,mean,max,min))
grid(nx=NA,ny=NULL)

answeredOct23'12at16:09
Roland
51.7k

39

72

Youcaneasilyfindsomethingtodothisinthe"CookbookforR":
Plottingmeansanderrorbars(ggplot2)
Anothergoodreferenceis"R:basicgraphs2(withggplot2)".
editedOct23'12at17:26

answeredOct23'12at14:33

nibot
6,429

ifreak
2

25

45

344

18

1 It'salwaysbettertoputthesolutionhere,becauseanylinksmaygobrokeninthefuture)RodrigoMar
10at14:26

Using ggplotandalittle dplyrfordatamanipulation:


set.seed(42)
df<data.frame(x=rep(1:10,each=5),y=rnorm(50))
library(ggplot2)
library(dplyr)
df.summary<df%>%group_by(x)%>%

http://stackoverflow.com/questions/13032777/scatter-plot-with-error-bars

2/3

01/08/2015

r - Scatter plot with error bars - Stack Overflow

summarize(ymin=min(y),
ymax=max(y),
ymean=mean(y))
ggplot(df.summary,aes(x=x,y=ymean))+
geom_point(size=2)+
geom_errorbar(aes(ymin=ymin,ymax=ymax))

Ifthere'sanadditionalgroupingcolumn(OP'sexampleplothastwoerrorbarsperxvalue,
sayingthedataissourcedfromtwofiles),thenyoushouldgetallthedatainonedataframeat
thestart,addthegroupingvariabletothe dplyr::group_bycall(e.g., group_by(x,file)if
fileisthenameofthecolumn)andadditasa"group"aestheticintheggplot,e.g., aes(x=
x,y=ymean,group=file).
editedApr23at16:21

answeredApr23at16:16
Gregor
14.7k

26

58

Iputtogetherstarttofinishcodeofahypotheticalexperimentwithtenmeasurementreplicated
threetimes.Justforfunwiththehelpofotherstackoverflowers.Thankyou...Obviouslyloops
areanoptionas applycanbeusedbutIliketoseewhathappens.
#Createfakedata
x<rep(1:10,each=3)
y<rnorm(30,mean=4,sd=1)
#Looptogetstandarddeviationfromdata
sd.y=NULL
for(iin1:10){
sd.y[i]<sd(y[(1+(i1)*3):(3+(i1)*3)])
}
sd.y<rep(sd.y,each=3)
#Looptogetmeanfromdata
mean.y=NULL
for(iin1:10){
mean.y[i]<mean(y[(1+(i1)*3):(3+(i1)*3)])
}
mean.y<rep(mean.y,each=3)
#Puttogetherthedatatoviewitsofar
data<cbind(x,y,mean.y,sd.y)
#Makeanemptymatrixtofillwithshrunkdata
data.1=matrix(data=NA,nrow=10,ncol=4)
colnames(data.1)<c("X","Y","MEAN","SD")
#Looptoputdataintoshrunkformat
for(iin1:10){
data.1[i,]<data[(1+(i1)*3),]
}
#Createatomicvectorsforarrows
x<data.1[,1]
mean.exp<data.1[,3]
sd.exp<data.1[,4]
#Plotthedata
plot(x,mean.exp,ylim=range(c(mean.expsd.exp,mean.exp+sd.exp)))
abline(h=4)
arrows(x,mean.expsd.exp,x,mean.exp+sd.exp,length=0.05,angle=90,code=3)

editedApr23at15:47

answeredApr23at15:38
ComputerNoob
4

http://stackoverflow.com/questions/13032777/scatter-plot-with-error-bars

3/3

You might also like