Skip to content

Instantly share code, notes, and snippets.

@grantbrown
Last active December 18, 2015 02:09
Show Gist options
  • Save grantbrown/5709109 to your computer and use it in GitHub Desktop.
Save grantbrown/5709109 to your computer and use it in GitHub Desktop.
Plots a normal curve and shaded region.
plotNormal = function(lb, ub, mu = 0, sigma = 1)
{
# Generate X an Y pairs for normal curve
X = seq(mu - 4*sigma, mu + 4*sigma, 0.1)
Y = dnorm(X, mean = mu, sd = sigma)
# Plot the normal curve line, lablel axes and plot
plot(X,Y, type = "l", main = "Normal PDF", xlab = "x", ylab = "Density(x)")
# Calculate visible bounds (no use plotting tails that are off the screen)
lb2 = min(max(lb, mu-4*sigma), min(ub, mu+4*sigma))
ub2 = max(max(lb, mu-4*sigma), min(ub, mu+4*sigma))
# Shade the region by drawing vertical lines
for (i in seq(lb2,ub2,length = 200))
{
lines(c(i,i), c(0, dnorm(i, mu, sigma)), col = "lightgrey", lwd = 2)
}
# Draw the coordinate axes
abline(h=0, lty = 2)
abline(v=0, lty = 2)
# Calculate and display the coverage
coverage = pnorm(ub, mu, sigma) - pnorm(lb, mu, sigma)
text(x = mu + 2*sigma, y = dnorm(mu + 0.5* sigma, mu, sigma), labels = paste("P(", lb, "<x<", ub, ")\n=",round(coverage,4), sep = ""))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment