[R] Shading area under density curves

rominger at stanford.edu rominger at stanford.edu
Wed Oct 3 23:21:32 CEST 2007


I have a question regarding shading regions under curves to display  
95% confidence intervals.  I generated bootstrap results for the slope  
and intercept of a simple linear regression model using the following  
code (borrowed from JJ Faraway 2005):

> attach(allposs.nine.d)
> x<-model.matrix(~log(d.dist,10))[,-1]
> bcoef<-matrix(0,1000,2)
> for(i in 1:1000){
+ newy<-predict(all.d.nine.lm)+residuals(all.d.nine.lm)[sample(1002,rep=TRUE)]
+ brg<-lm(newy~x)
+ bcoef[i,]<-brg$coef
+ }

Where "allposs.nine.d" is a data file composed of two columns: (1)  
geographical distances between sample points ("d.dist") and (2) their  
respective pairwise percent similarity in species composition  
("d.sim").  The expression "all.d.nine.lm" equals lm(d.sim~d.dist).

I saved the bootstrap results for each coefficient as:

> dist.density.b1<-density(bcoef[,2])
> dist.density.b0<-density(bcoef[,1])

Along with their 95% confidence intervals:

> dist.quant.b1<-quantile(bcoef[,2],c(.025,.975))
> dist.quant.b0<-quantile(bcoef[,1],c(.025,.975))

I then could plot smooth density curves along with their 95% CI's:

> plot(dist.density.b1)
> abline(v=dist.quant.b1)

Now finally for my question:  Instead of drawing vertical lines to  
represent the 95% CI's, I'd much prefer to somehow shade in the region  
under the curve corresponding the to 95% CI.  I tried using the  
polygon() function for this but did not get very far as I couldn't  
figure out how to define limits for x and y coordinates.

Any suggestions would be great.  Thanks very much--
Andy Romigner

More information about the R-help mailing list