Create animated graphics with R

April 5, 2009
83 Views

In a post last week, I wondered whether it was possible to create animated data charts with R. I think I’ve found a solution.

The animations package bills itself as “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”, which makes it seem like a collection of specific animation examples. Those examples are indeed there, but of arguably more value is the underlying general framework it provides for creating animations from the standard 2-D plotting tools that R provides.

The basic idea is that you create each frame of the animation as an R chart (using tools like plot, text, lines, etc.).  You bound the code creating the plots with the functions ani.start and ani.stop; within those bounds, each command that would normally create a new page for a plot instead creates a new frame of the animation. By default the animation is saved as an HTML page with an animation driven by JavaScript, but provided you have the appropriate image-conversion tools (ImageMagick and SW

In a post last week, I wondered whether it was possible to create animated data charts with R. I think I’ve found a solution.

The animations package bills itself as “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”, which makes it seem like a collection of specific animation examples. Those examples are indeed there, but of arguably more value is the underlying general framework it provides for creating animations from the standard 2-D plotting tools that R provides.

The basic idea is that you create each frame of the animation as an R chart (using tools like plot, text, lines, etc.).  You bound the code creating the plots with the functions ani.start and ani.stop; within those bounds, each command that would normally create a new page for a plot instead creates a new frame of the animation. By default the animation is saved as an HTML page with an animation driven by JavaScript, but provided you have the appropriate image-conversion tools (ImageMagick and SWFtools) installed, you can also save the animation as an animated GIF, MPG movie, or SWF animation.

You can see R code examples creating various animations at AniWiki. But be sure to check out the examples of using the animations package to create some cool optical illusions, too.