#### Density function, fixed bin histogram, moving histogram and kernel density estimator ####
#### for a sample of size n=100 from a N(0,1)                                             ####
x<-rnorm(100,0,1) 
y<-seq(-4,4,length=400)
plot(y,dnorm(y),type="l",xlab="N=100",xlim=c(-4,4),ylim=c(0.0,0.5),col=2,lwd=3,main="N(0,1) density function")
abline(h=0.00)
rug(x)
hist(x,freq=FALSE,add=TRUE)
lines(density(x,kernel="rectangular"),col=4,xlim=c(-4,4),ylim=c(0.0,0.5))
lines(density(x),lwd=2,xlim=c(-4,4),ylim=c(0.0,0.5),col=3)
legend("top",legend=c("Underlying density","Histogram","Moving histogram","Parzen-Rosenblatt kernel estimator"),lwd=c(3,1,1,2),col=c(2,1,4,3))



#### Density function, fixed bin histogram, moving histogram and kernel density estimator ####
#### for a sample of size n=100 from an exponential distribution with mean 1              ####
x<-rexp(100,rate=1) 
y<-seq(-0.1,6,length=400)
plot(y,dexp(y),type="l",xlab="N=100",xlim=c(0,6),ylim=c(0.0,1.0),col=2,lwd=3,main="exp(1) density function")
abline(h=0.00)
rug(x)
hist(x,freq=FALSE,add=TRUE)
lines(density(x,kernel="rectangular"),col=4)
lines(density(x),lwd=2,col=3)
legend("top",legend=c("Underlying density","Histogram","Moving histogram","Parzen-Rosenblatt kernel estimator"),lwd=c(3,1,1,2),col=c(2,1,4,3))



#### 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 ####
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="chi^2 with 6 d.f. density function")
abline(h=0.00)
rug(x)
hist(x,freq=FALSE,add=TRUE)
lines(density(x,kernel="rectangular"),col=4)
lines(density(x),lwd=2,col=3)
legend("top",legend=c("Underlying density","Histogram","Moving histogram","Parzen-Rosenblatt kernel estimator"),lwd=c(3,1,1,2),col=c(2,1,4,3))

