[R] How to shade part of a density plot

Achim Zeileis zeileis at ci.tuwien.ac.at
Sun May 19 20:47:18 CEST 2002

Stuart Luppescu wrote:
> I'm trying to shade part of a density plot. The code I'm trying (using
> the Old Faithful data as an example) is something like this:
> # The Old Faithful geyser data
> data(faithful)
> d <- density(faithful$eruptions, bw = "sj")
> plot(d)
> polygon(d[d$x>4], col = "wheat")
> I expected that the part of the curve to the right of 4 on the x axis
> should be shaded, but nothing gets shaded at all. In fact, when I just
> try to print d[d$x>4] I get many lines of
> $"NA"
> I must be mistaken in my understanding of density objects. Could someone
> clear up my mistake? Thanks very much.

That's because d is essentially a list, if you do something like

R> sub.x <- d$x[d$x > 4]
R> sub.y <- d$y[d$x > 4]
R> polygon(c(min(sub.x), sub.x), c(0, sub.y), col = "wheat")

you should get the desired result.

> --
> Stuart Luppescu       -=- s-luppescu at uchicago.edu
> University of Chicago -=- CCSR
> 才文と智奈美の父    -=- Kernel 2.4.18-xfs
> checkuary, n:  The thirteenth month of the year.  Begins New
>  Year's Day and ends  when a person stops absentmindedly
>  writing the old year on his checks.
>   ------------------------------------------------------------------------
>                        Name: signature.asc
>    signature.asc       Type: application/pgp-signature
>                 Description: This is a digitally signed message part
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list