Sunday, April 3, 2011

How to Shade Under a Normal Density in R

The easiest-to-find method for shading under a normal density is to use the polygon() command. That link is to the first hit on Google for "Shading Under a Normal Curve in R." It works (like a charm), but it is not the most intuitive way to let users produce plots of normal densities.

In response to the standard polygon() approach, I wrote a function called shadenorm() that will produce a plot of a normal density with whatever area you want shaded. The code is available here (in a newer post; I updated the function slightly).

Copy into an R script and run all of it if you want to use the shadenorm() command. To show you how to use it, I also recorded a video tutorial in R to demonstrate how to use the shadenorm() command.




Here is the code I use in the video:

## ---------------------- ##
## Shading under a Normal ##
## in R ##
## ---------------------- ##
shadenorm() ## Defaults mu = 0, sig = 1, pcts = c(0.025, 0.975)
## Below, Above, Outside and Between
shadenorm(below=-1.5) ## Sets lower endpoint at -1.5
shadenorm(below=-1.5,justbelow=TRUE) ## Just plots the lower tail
shadenorm(above=1.5) ## Sets upper endpoint at 1.5
shadenorm(above=1.5, justabove=TRUE) ## Similar to below
shadenorm(below=-1.5,above=1.5) ## Plots "outside" of -1.5 and 1.5
shadenorm(outside = c(2.5, -2.5)) ## Alternative "outside" plotter
shadenorm(outside = c(1, 2, -1, -0.2, 2.4)) ## works by taking min and max
shadenorm(between = c(2.5, -2.5)) ## Plots between specified points
shadenorm(between = c(-1.75, 0, 2, 0.5, -1)) ## Plots between specified points
## Can specify different means and standard deviations with mu and sig arguments
shadenorm(mu=2, sig=10)
shadenorm(mu=2, sig=10, between=c(-2, 14)) ## works with between and outside
shadenorm(mu=2, sig=10, outside=c(-5, 14))
## Can Apply different colors and densities... color and dens
shadenorm(mu=2, sig=10, outside=c(-3, 12), col="blue")
shadenorm(mu=2, sig=10, outside=c(-3, 12), col="blue",dens=15) ## Dens default is 40
shadenorm(mu=2, sig=10, outside=c(-3, 12), col="blue",dens=150)
## Can plot one and then another ontop of it using lines = TRUE
shadenorm(mu=2, sig=10, outside=c(-3, 12), dens=15)
shadenorm(mu=2, sig=15, between=c(-3, 12),lines=TRUE, col="blue",dens=15)
## Example: Plotting a Hypothesis Test for the mean
## Truth: mu.true = 8
## Hypothesis: mu.ho = 6
## Generate Data Under Truth
mu.true = 5 ## Alternative Mean
mu.ho = 6
sig = 8
N = 250 ## Sample Size
std.err = sig/sqrt(N)
crits = qnorm(c(0.025,0.975),mean=mu.ho, sd = std.err)
shadenorm(outside = crits, mu = mu.ho, sig = std.err,dens=15)
shadenorm(between = crits, mu = mu.true, sig = std.err, lines=TRUE, color="green",dens=15)


There are a lot of applications where you may want to produce a plot with a normal density with some region shaded. I hope you find this function useful.

No comments:

Post a Comment