[R] How to color certain area under curve

Matthieu Dubois matthdub at gmail.com
Tue Mar 10 20:45:59 CET 2009


 <guox <at> ucalgary.ca> writes:

> 
> For a given random variable rv, for instance, rv = rnorm(1000),
> I plot its density curve and calculate some quantiles:
> plot(density(rv))
> P10P50P90 = = quantile(rv,probs = c(10,50,90)/100)
> I would like to color the area between P10 and P90 and under the curve
> and mark the P50 on the curve.
> 
> > rv = rnorm(1000)
> > plot(density(rv))
> > P10P50P90 = = quantile(rv,probs = c(10,50,90)/100)
> 
> Could you please teach me how to do these using R?
> Thanks,
> -james
> 

see ?polygon

Here after is an example of the use of polygon to solve your problem: 
rv <- rnorm(1000)
drv <- density(rv)
plot(drv)

# further steps: 
# 1. compute quantiles
# 2. determine the x and y of the area that must be drawn
# 3. drawn
# 4. add q.5 info
qrv <- quantile(rv, prob=c(0.1, 0.9))
select <- qrv[1] <= drv$x & drv$x <= qrv[2]
polygon(x = c(qrv[1], drv$x[select], qrv[2]), 
y = c(0, drv$y[select], 0, col='blue')
abline(v= quantile(rv, p=0.5), lty=2)

Hope this will help. 

Matthieu




More information about the R-help mailing list