wen
wen

Reputation: 1935

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?

Upvotes: 5

Views: 4734

Answers (2)

Sandipan Dey
Sandipan Dey

Reputation: 23099

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

Upvotes: 2

J.R.
J.R.

Reputation: 3888

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

Upvotes: 7

Related Questions