Table of Contents

R Package ''animation''

This package consists of various functions for animations in statistics, covering many areas such as probability theory, mathematical statistics, multivariate statistics, nonparametric statistics, sampling survey, linear models, time series, computational statistics, data mining and machine learning. These functions might be of help in teaching statistics and data analysis.

Motivation

There is at least one significant difference between the disciplines of pure mathematics and statistics: usually statistics can be imagined in a very practical way, while it is not always true for mathematics. For example, everyone can imagine why k-Nearest Neighbor technique works, but perhaps not everyone can imagine why Taylor expansion technique works, although we can prove it!

Thus an animation package is written – just for better understanding of statistical techniques and data analysis.

Download

This package animation is available on CRAN now; the source code as well as the Windows binary can be downloaded at:

http://cran.r-project.org/package=animation

You may install by R CMD INSTALL after downloading the source or simply use install.packages() in R:

install.packages("animation")

The development is on GitHub: http://github.com/yihui/animation

Usage

Watching animations either inside R (in windows graphics devices) or outside R (in HTML pages) are OK:

  1. Inside R: just type the animation functions in the console, and watch the animations in an R windows graphics device. Usually we don't need to provide any argument values because all there are default ones for demonstration purposes. The time interval for animations can be set in ani.options() (the interval argument).
  2. Outside R: the package has also provided several ways to export animations, e.g. create HTML output containing the animations. You may use the function ani.options() to specify a series of parameters to control the output, e.g. ani.dev to select an R graphics devices such as png, jpeg, etc; ani.width and ani.height to specify the width and height of image frames. Then call saveHTML() to produce the HTML animation output.

For further information, please check corresponding help pages or learn how the HTML pages are created.

Method

How to generate an animation sequence and save it?

Generate an animation sequence

The animation method behind the package is quite naive and intuitive; here is an example showing how it works:

for (i in 1:360) {
    plot(1, ann = FALSE, type = "n", axes = FALSE)
    text(1, 1, "Animation", srt = i, col = rainbow(360)[i], cex = 7 * i/360)
    Sys.sleep(0.01)
} 

The above R code will produce an animation like this:

The rotation animation of the word "Animation"

Almost all of the animation functions in the package just follow this kind of loop to produce a sequence of image frames.

A General Schema

Here is the pseudo code for the general schema used in the package:

#---------------------------------------------------------------------------#
# Some parameters in 'ani.options()' such as 'nmax' and 'interval' have been
#   appropriately set beforehand;
#---------------------------------------------------------------------------#
ani.fun <- function(args.for.stat.method, args.for.graphics, ...) {
    {stat.calculation.for.preparation.here}
    i = 1
    while (i <= ani.options("nmax") & other.conditions.for.stat.method) {
        {stat.calculation.for.animation}
        {plot.results.in.ith.step}
        # pause for a while in this step
        ani.pause()
        i = i + 1
    }
    {return.something}
}
#---------------------------------------------------------------------------#
# To produce an HTML animation page, use 'saveHTML(ani.fun(...), ...)';
# To produce GIF/MPEG animations, use 'saveMovie(ani.fun(...), ...)';
# To produce Flash animations, use 'saveSWF(ani.fun(...), ...))';
# To produce PDF animations, use 'saveLatex(ani.fun(...), ...)'
#---------------------------------------------------------------------------#

What should be noted here is: the actual number of image frames might not be equal to the nmax set in ani.options() before, because nmax is not the sole condition to break the loop; sometimes a statistical method may have other conditions such as a threshold for error, etc. That's why we have to reset the nmax parameter in the end1).

Create an HTML page for animation

The animation in the HTML pages is actually driven by JS. For more details, please refer to the method to create an HTML animation page. To generate animations in this wiki, you should read the HTML animation examples and the animation plugin for Dokuwiki.

Create GIF animations

The package has also provided a wrapper to generate GIF animations together with ImageMagic. The method is even easier; we merely need to write some code which can produce a sequence of images, and the rest work will be done by the function saveMovie() in the package. See the example below in the “Examples” section. (Actually the GIF animation above is just made by this function.)

Create Flash animations

The SWF Tools a collection of SWF manipulation and creation utilities written by Rainer Böhme and Matthias Kramm, and the package animation has also provided a wrapper saveSWF() to generate Flash animations with the help of these tools. Currently three graphics devices are available for producing Flash animations: png, jpeg and pdf. There is also an example below.

Create PDF animations

use saveLatex() FIXME

Beyond Base Graphics

We can also create animations from other R graphics systems like ggplot2 or lattice. The only thing we need to remember is to print() the graphics, otherwise the images will not be recorded. See the ''ggplot2'' wiki for two examples.

Examples

Currently we can directly use the functions in the package to produce animations, or we can also define animation functions for ourselves.

Use internal functions

library(animation)

# inside R: windows graphics device
oopt = ani.options(interval = 0.05, nmax = 150)
brownian.motion(n = 15, pch = 21, cex = 5, col = "red", bg = "yellow")
ani.options(oopt)

# outside R: create an HTML animation page
oopt = ani.options()

saveHTML({
opar = par(mar = c(3, 3, 1, 0.5), mgp = c(2, .5, 0), tcl = -0.3,
    cex.axis = 0.8, cex.lab = 0.8, cex.main = 1)
brownian.motion(pch = 21, cex = 5, col = "red", bg = "yellow")
}, interval = 0.05, nmax = 100, 
    title = "Demonstration of Brownian Motion",
    description = "Random walk on the 2D plane: for each point (x, y), 
    x = x + rnorm(1) and y = y + rnorm(1).")

ani.options(oopt)

Check the page Brownian Motion (Random Walk) to see the results.

Define custom functions

The following code has explained how to define animation functions for yourself (please read the general schema above first):

library(animation)
# define an animation function to show the jitter effect
jitter.ani <- function(amount = 0.2, ...) {
    x <- sample(3, 300, TRUE, c(0.1, 0.6, 0.3))
    y <- sample(3, 300, TRUE, c(0.7, 0.2, 0.1))
    i <- 1
    while (i <= ani.options("nmax")) {
        plot(jitter(x, amount = amount), jitter(y, amount = amount), 
            xlim = c(0.5, 3.5), ylim = c(0.5, 3.5), xlab = "jittered x", 
            ylab = "jittered y", panel.first = grid(), ...)
        points(rep(1:3, 3), rep(1:3, each = 3), cex = 3, pch = 19)
        ani.pause()
        i <- i + 1
    }
} 

saveHTML({
par(mar = c(5, 4, 1, 0.5))
jitter.ani()
}, nmax = 30, interval = 0.5, title = "Jitter Effect")

To see the animation effects, please visit the example page for jitter effect.

GIF animation

Following the above example, we pass an expression to the function saveMovie() to create a similar animation:

library(animation)
saveMovie(jitter.ani(), interval = 0.5, outdir = getwd()) 

Flash animation

Here is a Flash animation example for the kNN algorithm:

saveSWF({
    par(mar = c(3, 3, 1, 1.5), mgp = c(1.5, 0.5, 0))
    knn.ani(test = matrix(rnorm(16), ncol = 2), cl.pch = c(16, 2))
}, interval = 1.5, nmax = 50)

Flash animation for the k-NN algorithm

Be sure your browser has the Flash plugin to view Flash animations.

Changes

See the NEWS file of the package. There are significant changes since version 1.0-0 (it has been submitted to CRAN); if you wish to know more about the old versions, please read the page package ''animation'' prior to 1.0-0.

Future Plans

Misc

I have included some miscellaneous functions in this package too, which may (may not) have something (anything) to do with animations. If you are interested, please read this page.

1) in the case when nmax is exactly the number of animation frames, we don't need to reset this option