简体   繁体   中英

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?

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM