PDF and CDF for normal distributions with R

Below, we give the R code to plot the PDF and the CDF for normal distributions. We wish to get charts quite similar to the ones read on Wikipedia (Normal Distribution). The resulting charts are shown at the bottom.

Notice that we don’t resort to any specific R library. Also notice that the code below was written and run using Eclipse/StatET. Some line breaks may cause difficulties depending on your GUI.

# Édouard Tallent @ TaGoMa.Tech
# September 2012
# The code below computes and draws the pdf and the cdf
# for normal distribution functions

# Displays the PDFs and CDFs at the same time
par(mfrow=c(2,1))

# Some variables defined
x <- seq(-6, 6, length = 500)
mu  <- c(0, 0, 0, -2)
sigma <- c(sqrt(0.2), sqrt(1.0), sqrt(5.0), sqrt(0.5))
colour <- c("blue", "red", "gold", "darkgreen")

labels <- c((expression(paste(mu == 0, ", ", sigma^2 == 0.2))),
		(expression(paste(mu == 0, ", ", sigma^2 == 1))),
		(expression(paste(mu == 0, ", ", sigma^2 == 5))),
		(expression(paste(mu == -2, ", ", sigma^2 == 0.5))))

# PDFs
plot(x, dnorm(x, mean = mu[1], sd = sigma[1]), lwd=2, col=colour[1], type = "l", ylim = c(0, 1),
		main = "Probability density function",
		xlab = expression(atop(~chi,"The red curve is the standard normal distribution")),
		ylab = expression(Phi[mu ~ "," ~ sigma^2](chi)))

for (i in 2:4){
	lines(x, dnorm(x, mean = mu[i], sd = sigma[i]), lwd=2, col= colour[i])
}

# Adds a grid
grid() # grids can be customized

# Adds a legend to the top-right
legend("topright", inset=.05, labels, lwd=2, lty=c(1, 1, 1, 1), cex = 0.8, col=colour)

# CDF
plot(x, pnorm(x, mean = mu[1], sd = sigma[1]), lwd=2, col=colour[1], type = "l", ylim = c(0, 1),
		main = "Cumulative distribution function",
		xlab = expression(chi),
		ylab = expression(phi[mu ~ "," ~ sigma^2](chi)))

# Adds a grid
grid()

for (i in 2:4){
	lines(x, pnorm(x, mean = mu[i], sd = sigma[i]), lwd=2, col= colour[i])
}

# Adds a legend to the top-left
legend("topleft", inset=.05, labels, lwd=2, lty=c(1, 1, 1, 1), cex = 0.8, col=colour)

 

About these ads

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s