Skip to content

Instantly share code, notes, and snippets.

@tungwaiyip
Created October 29, 2012 04:25
Show Gist options
  • Select an option

  • Save tungwaiyip/3971506 to your computer and use it in GitHub Desktop.

Select an option

Save tungwaiyip/3971506 to your computer and use it in GitHub Desktop.
Plot the PDF and CDF of chi-square distribution
# install the RColorBrewer package
#install.packages("RColorBrewer")
library(RColorBrewer)
cols <- brewer.pal(8, "OrRd")
cols = cols[3:8]
cols <- brewer.pal(8, "Set1")
x=seq(0,8,0.1)
k_lst=c(1,2,3,4,6,9)
k_label = c("k=1", "k=2", "k=3", "k=4", "k=6", "k=9") # there should be a better way to do this
# The output looks really ugly on Windows without antialiasing
# Uncomment the the line below much nicer PDF output. Uncomment the mathcing dev.off() at the end also.
#pdf(file="out_graph.pdf",width=7,height=12)
par(mfrow=c(2,1))
# The PDF
par(mar=c(2, 5, 4, 3))
plot(c(0,8),c(0,0.7),type="n",
ylab="PDF",
main=title(expression(chi[k]^2))
)
for (i in 1:length(k_lst)) {
k = k_lst[i]
col = cols[i]
lines(x,dchisq(x,df=k),col=col,lwd=2)
}
legend(6.5, 0.65,
lty=c(1,1), # gives the legend appropriate symbols (lines)
k_label,
lwd=c(2.5,2.5),
col=cols
)
# The CDF
par(mar=c(4, 5, 2, 3))
plot(c(0,8),c(0,1),type="n",
xlab="x",
ylab="CDF",
)
for (i in 1:length(k_lst)) {
k = k_lst[i]
col = cols[i]
lines(x,pchisq(x,df=k),col=col,lwd=2)
}
legend(6.5, 0.3,
lty=c(1,1), # gives the legend appropriate symbols (lines)
k_label,
lwd=c(2.5,2.5),
col=cols
)
# Uncomment this if you use PDF output
#dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment