ggplot2: coloring under empiric density curve using geom_area

References

geom_area

## Create data
dat <- with(density(rnorm(100)), data.frame(x, y))
head(dat)
       x         y
1 -3.233 0.0001355
2 -3.220 0.0001522
3 -3.207 0.0001711
4 -3.194 0.0001918
5 -3.180 0.0002142
6 -3.167 0.0002398

## Load ggplot2
library(ggplot2)

## Color the area under the curve between -1.2 and 1.1
ggplot(data = dat, mapping = aes(x = x, y = y)) +
    layer(geom = "line") +
    layer(geom = "area", mapping = aes(x = ifelse(x>-1.2 & x<1.1 , x, 0)),
          geom_params = list(fill = "red", alpha = 0.5)) +
    scale_y_continuous(limits = c(0, max(dat$y)))

plot of chunk unnamed-chunk-2