[R] Shading area under density curves

AA aa2007r at gmail.com
Fri Oct 5 16:35:12 CEST 2007


I found the link below very helpful in explaining the use of polygon.
http://www.feferraz.net/en/shaded.html
good luck
AA.


----- Original Message ----- 
From: <rominger at stanford.edu>
To: <r-help at r-project.org>
Sent: Wednesday, October 03, 2007 5:21 PM
Subject: [R] Shading area under density curves


> Hello,
>
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list