# This script illustrates the effect of varying the span of the # smoothing window in density estimation (kernel method of R # implemented in function `density`. # This is an adaptation of the example provided in ?tkrplot. # Time-stamp: <2007-07-27 11:59:18 chl> library(tkrplot) ## will also load the `tcltk` package animate <- function (x, k="Sturges", sp) { # x : vector of values to plot # k : number of breaks required for the histogram (default # to R's settings, i.e. "Sturges" # sp : span of the smoothing window (parameter `adj` # in `density` bb <- sp xx <- seq(min(x),max(x),length=length(x)) cols <- c("gray60","blue") tt <- tktoplevel() # prepare the main panel img <-tkrplot(tt, function () { hist(x,breaks=k,proba=T,ylim=c(0,.45)) lines(xx,dnorm(xx,mean=mean(x),sd=sd(x)), col=cols[1],lwd=2) lines(density(x,adj=bb),col=cols[2],lwd=3) legend("topright", c(paste("Normal N(",round(mean(x),0),",", round(sd(x),0),")",sep=""), "Density Est."), lty=rep(1,2),lwd=c(2,3),col=cols,bty="n") }) # update graphics with new parameters # Note: # I need to fix this comparison which generates warnings f <- function (...) { b <- as.numeric(tclvalue("bb")) if (b != bb) { bb <<- b tkrreplot(img) } } # main loop s <- tkscale(tt, command=f, from=sp[1], to=sp[2], variable="bb", showvalue=TRUE, resolution=0.05, orient="horiz") tkpack(img,s) } # we generate contaminated normal observations # see Venables (2002, 4th Ed., p. 111) y <- rnorm(100,0,(1+2*rbinom(100,1,0.35))) animate(y, sp=c(.5,3))