Search code examples
rggplot2plotgrapharea

How to shade a graph using curve() in R


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?


Solution

  • 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