I frequently use kernel density plots to illustrate distributions. These are easy and fast to create in R like so:
set.seed(1)
draws <- rnorm(100)^2
dens <- density(draws)
plot(dens)
#or in one line like this: plot(density(rnorm(100)^2))
Which gives me this nice little PDF:
I'd like to shade the area under the PDF from the 75th to 95th percentiles. It's easy to calculate the points using the quantile
function:
q75 <- quantile(draws, .75)
q95 <- quantile(draws, .95)
But how do I shade the the area between q75
and q95
?
Here's another
ggplot2
variant based on a function that approximates the kernel density at the original data values:Using the original data (rather than producing a new data frame with the density estimate's x and y values) has the benefit of also working in faceted plots where the quantile values depend on the variable by which the data is being grouped:
Code used
Created on 2018-07-13 by the reprex package (v0.2.0).
Another solution:
Result:
With the
polygon()
function, see its help page and I believe we had similar questions here too.You need to find the index of the quantile values to get the actual
(x,y)
pairs.Edit: Here you go:
Output (added by JDL)
An expanded solution:
If you wanted to shade both tails (copy & paste of Dirk's code) and use known x values:
Result:
This question needs a
lattice
answer. Here's a very basic one, simply adapting the method employed by Dirk and others: