0

I would like to fill or color a portion of the normal distribution. I fould an example of how to do that here:

http://msenux.redwoods.edu/math/R/StandardNormal.php

x=seq(-4,4,length=200)
y=dnorm(x)
plot(x,y,type="l", lwd=2, col="blue")
x=seq(-1,1,length=100)
y=dnorm(x)
polygon(c(-1,x,1),c(0,y,0),col="gray")

However, if I try to generalize the above code for any portion of the x-axis the best I can come up with is:

sigma <- 1
mu    <- 0

lower.x <- -0.0
upper.x <-  2.1

x  <- seq(-4, 4, length = 200)
y  <- ( 1/(sigma * sqrt(2*pi)) ) * ( exp(1)^( (-1 * ((x - mu)^2)) / (2*(sigma^2)) ) )
plot(x,y,type="l", lwd=2, col="blue")

x=seq(lower.x, upper.x, length=100)
y  <- ( 1/(sigma * sqrt(2*pi)) ) * ( exp(1)^( (-1 * ((x - mu)^2)) / (2*(sigma^2)) ) )
polygon(c(lower.x,x,1), c(0,y,0), col="gray")

I think the error involves the second length statement, but I cannot figure out how to correct the mistake. Also, I would prefer that the blue line of the normal distribution curve not be covered by the border of the shaded region. Although that is of less concern. Thank you for any advice.

Mark Miller
  • 12,483
  • 23
  • 78
  • 132

2 Answers2

4

More or less from: http://www.fernandohrosa.com.br/en/P/shaded_areas_in_r/

lower.x <- 0
upper.x <- 2.1
step <- (upper.x - lower.x) / 100
sigma <- 1
mu <- 0
bounds <- c(mu-3*sigma, mu+3*sigma)
cord.x <- c(lower.x,seq(lower.x,upper.x,step),upper.x)
cord.y <- c(0,dnorm(seq(lower.x,upper.x,step),mu,sigma),0)
curve(dnorm(x,mu,sigma),xlim=bounds) 
polygon(cord.x,cord.y,col='skyblue')

Also refer to http://www.r-bloggers.com/functions-for-plotting-and-getting-greek-in-labels/ and for future reference: How to shade a region under a curve using ggplot2

Community
  • 1
  • 1
t-student
  • 414
  • 2
  • 16
1

The code below seems to do what I want, or virtually so.

I use by statements below instead of length statements. I am not certain, but I suspect the second sequence of x values must be a subset of the first sequence of x values.

I then redraw the normal distribution curve to cover the top gray border of the polygon. The only aspect of the result that perhaps I would like to improve is that the blue is a little darker where it covers the gray. But that seems minor at this point.

sigma <- 1
mu    <- 0

lower.x <- -0.0
upper.x <-  2.1

x  <- seq(-4, 4, by = 0.1)
y  <- ( 1/(sigma * sqrt(2*pi)) ) * ( exp(1)^( (-1 * ((x - mu)^2)) / (2*(sigma^2)) ) )
plot(x,y,type="l", lwd=2, col="blue")

x=seq(lower.x, upper.x, by = 0.1)
y  <- ( 1/(sigma * sqrt(2*pi)) ) * ( exp(1)^( (-1 * ((x - mu)^2)) / (2*(sigma^2)) ) )
polygon(c(lower.x,x,upper.x), c(0,y,0), col="gray")
lines(x, y, col="blue", lwd=2)
Mark Miller
  • 12,483
  • 23
  • 78
  • 132