[R] plot(x,y) with errors

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Mar 3 12:00:12 CET 2004


Spencer Graves <spencer.graves at pdf.com> writes:

>       Does the following do what you want: > x<-c(1,2,3,4,5,6,7,8,9,10)
>  > y<-c(1.3,2.5,4.6,5.3,5.9,6.7,7.4,8.5,9.4,10.4)
>  > erry<-c(0.2,0.3,0.2,0.1,0.4,0.2,0.3,0.4,0.3,0.2)
>  >
>  > plot(x, y)
>  >
>  > n <- length(x)
>  > Y <- array(c(y-erry, y+erry), dim=c(n,2))
>  > for(i in 1:n)
> +  lines(rep(x[i],2), Y[i,])

(Actually, segments(x,y-erry,x,y+erry) would be a more direct way.)

>       Others may have more elegant solutions, but this is simple
> enough for me to understand AND produces essentially the same result
> in R 1.8.1 and S-Plus 6.2.     hope this helps.  spencer graves

There are a number of fine points to get right, though, esp. if the
bars get longer than in this example.

I think there are special "plot with errorbars" in some of the "misc"
packages on CRAN (their authors are likely to chime in any moment
now), but for a relatively simple solution, I think I'd do

plot(x, y, type="n", ylim=range(y+erry,y-erry))
arrows(x,y-erry,x,y+erry,code=3,length=.005*diff(range(x)),angle=90)
points(x,y,pch=21,bg="white")


-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list