4

I am plotting the standard normal distribution.

curve(dnorm(x), from=-4, to=4, 
  main = "The Standard Normal Distibution", 
  ylab = "Probability Density",
  xlab = "X")

For pedagogical reasons, I want to shade the area below a certain quantile of my choice. How can I do this?

Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
wen
  • 1,875
  • 4
  • 26
  • 43

2 Answers2

6

If you want to use curve and base plot, then you can write a little function yourself with polygon:

colorArea <- function(from, to, density, ..., col="blue", dens=NULL){
    y_seq <- seq(from, to, length.out=500)
    d <- c(0, density(y_seq, ...), 0)
    polygon(c(from, y_seq, to), d, col=col, density=dens)
}

A little example follows:

curve(dnorm(x), from=-4, to=4, 
  main = "The Standard Normal Distibution", 
  ylab = "Probability Density",
  xlab = "X")

colorArea(from=-4, to=qnorm(0.025), dnorm)
colorArea(from=qnorm(0.975), to=4, dnorm, mean=0, sd=1, col=2, dens=20)

enter image description here

J.R.
  • 3,838
  • 1
  • 21
  • 25
1

We could use the following R code too, in order to shade the regions under the standard normal curve below a certain (given) quantile:

library(ggplot2)
z <- seq(-4,4,0.01)
fz <- dnorm(z)
q <- qnorm(0.1) # the quantile
x <- seq(-4, q, 0.01)
y <- c(dnorm(x), 0, 0)
x <- c(x, q, -4)
ggplot() + geom_line(aes(z, fz)) +
           geom_polygon(data = data.frame(x=x, y=y), aes(x, y), fill='blue')

enter image description here

Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63