# Animating the effect of changing kernel width in R

I have some data in R, stored in a list. Think

d <- c(1,2,3,4)


although this is not my data. If I then enter the command

 plot(density(d, kernel="gaussian", width=1))


then I get the kernel probability density estimate, where the kernel is standard normal. If I replace 1 with other numbers, of course the picture changes.

What I would like to do is create a video or animation in which each frame is such a plot, but the bandwidth of the kernel varies from frame to frame, thereby showing the effect of changing the bandwidth. How can I do this?

(My apologies if this is not the right place to ask questions about R.)

-

It depends a little bit on what your end goal is.

Quick and dirty hack for real-time demonstrations

Using Sys.sleep(seconds) in a loop where seconds indicates the number of seconds between frames is a viable option. You'll need to set the xlim and ylim parameters in your call to plot to make things behave as expected.

Here's some simple demonstration code.

# Just a quick test of Sys.sleep() animation

x <- seq(0,2*pi, by=0.01)
y <- sin(x)
n <- 5
pause <- 0.5

ybnds <- quantile(n*y, probs=c(0,1))
x11()

# Draw successively taller sinewaves with a gradually changing color
for( i in 1:n )
{
plot(x, i*y, type="l", lwd=2, ylim=ybnds, col=topo.colors(2*n)[i])
Sys.sleep(pause)
}


This works pretty well, especially using X-Windows as the windowing system. I've found that Mac's quartz() does not play nice, unfortunately.

Animated GIFs

If you need something that can be redistributed, posted on a webpage, etc., look at the write.gif function in the caTools package. Displaying help on write.gif gives several nice examples, including a couple of animations—one with a quite nice example using the Mandelbrot set.

More fine-tuned control and fancier animations

There is an animation package that looks pretty capable. I haven't used it myself, though, so I can't give any real recommendations either way.

I have seen a few good examples of output from this package and they look pretty nice. Perhaps one of the "highlights" is the ability to embed an animation in a PDF.

-
 That seems to work. I am mostly looking for a quick and dirty hack to use for demonstrations in a class I'm teaching, but if I can post it on a webpage so much the better. – Michael Lugo May 8 '11 at 2:28 For quartz, it's faster to draw a white rectangle over the existing plot and then just redraw the lines. See tourr:animate_dist for an example of this approach. – hadley May 9 '11 at 1:34

One way to go is to use the excellent animation package by Yihui Xie. I uploaded a very simple example to my public dropbox account: densityplot (I will remove this example in 3 days). Is this what you are looking for?

The animation was created using the following R code:

library(animation)
density.ani <- function(){
i <- 1
d <- c(1,2,3,4)
while (i <= ani.options("nmax")) {
plot(density(d, kernel="gaussian", bw = i), ylim = c(0, 0.25))
ani.pause()
i <- i + 1
}
}

saveHTML({
par(mar = c(5, 4, 1, 0.5))
density.ani()
}, nmax = 30, title = "Changing kernel width")

-
 Thanks. This is basically what I'm looking for. – Michael Lugo May 8 '11 at 2:32

Here is another approach:

library(TeachingDemos)

d <- c(1,2,3,4)

tmpfun <- function(width=1, kernel='gaussian'){
plot(density(d, width=width, kernel=kernel))
}

tmplst <- list( width=list('slider', init=1, from=.5, to=5, resolution=.1),
"epanechnikov","rectangular","triangular","biweight","cosine",
"optcosine")))

tkexamp( tmpfun, tmplst, plotloc='left' )

-

Just for the sake of completeness, if you need this for a class demonstration, I would also mention the manipulate package which comes with RStudio. Note that this package is dependent on RStudio interface, so it won't work outside of it.

manipulate is quite cool because it allows to quickly create some sliders to manipulate any element in the plot. This would allow to do some easy and real-time demonstration in class.

manipulate(
plot(density(1:10, bw)),
bw = slider(0, 10, step = 0.1, initial = 1))


Other examples here

-