Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
# Normal Distiribution
# Sequence between -4 and 4 with 0.1 steps
x <- seq(-4, 4, 0.1)
# Plot an empty chart with tight axis boundaries, and axis lines on bottom and left
plot(x, type="n", xaxs="i", yaxs="i", xlim=c(-4, 4), ylim=c(0, 0.4),
bty="l", xaxt="n", xlab="z-value", ylab="probability density")
# Function to plot each coloured portion of the curve, between "a" and "b" as a
# polygon; the function "dnorm" is the normal probability density function
polysection <- function(a, b, col, n=11){
dx <- seq(a, b, length.out=n)
polygon(c(a, dx, b), c(0, dnorm(dx), 0), col=col, border=NA)
# draw a white vertical line on "inside" side to separate each section
segments(a, 0, a, dnorm(a), col="white")
}
# Build the four left and right portions of this bell curve
polysection( 0, 1, col="#2171B5")
polysection( 1, 1.96, col="#6BAED6")
polysection(-1, 0, col="#2171B5")
polysection(-1.96,-1, col="#6BAED6")
# Black outline of bell curve
lines(x, dnorm(x))
# Bottom axis values, where sigma represents standard deviation and mu is the mean
axis(1, at=c(-3,-2,-1.96,-1,0,1,1.96,2,3), labels=expression(-3, '', -1.96, -1, 0, 1, 1.96, '', 3))
# Add percent densities to each division, between x and x+1
text( c(0,0), c(0.15,0.1), c('68%', '95%'), col=c("white","white"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment