#### Density function, fixed bin histogram, moving histogram and kernel density estimator ####
#### for a sample of size n=100 from a chi-squared distribution with 6 degrees of freedom ####

library(ks)
x<-rchisq(100,6) 
y<-seq(-0.1,25,length=400)
plot(y,dchisq(y,6),type="l",xlab="N=100",xlim=c(0,25),ylim=c(0.00,0.16),col=2,lwd=3,main="Density function (chi^2 6 d.f.)")
abline(h=0.00)
rug(x)
lines(density(x,bw="nrd0"),col=4)
lines(density(x,bw="bcv"),col=1)
bandwidth<-hscv(x)
lines(density(x,bw=bandwidth),lwd=2,col=3)
legend("top",legend=c("Underlying density function","Kernel estimator (rule of thumb)","Kernel estimator (h_BCV)","Kernel estimator (h_SCH)"),lwd=c(3,1,1,1,2),col=c(2,4,1,3))

