Create an animated .gif image with R and ImageMagick
The purpose of this tutorial is to show you the steps to create an animated gif image with R and ImageMagick. You must first install ImageMagick.
It is also possible to create animated .gif images using only R, through write.gif() in caTools package.
The R code described in this tutotriel were tested on Mac OS X 10.6.8 with R 2.13
Example 1: Create a countdown
R code
The countdown is from 10 to 1. We will create it in 4 steps.
1 - Creating a clean working directory called 'examples'.
2 - Creating .png images, each containing a number (10 to 1).
3 - Creating a single image. Gif using ImageMagick
4 - delete png files that are no longer needed
The corresponding R code is shown below:
Code R :
#crearing working directory dir.create("examples") setwd("examples") #Creating countdown .png files from 10 to "GO!" png(file="example%02d.png", width=200, height=200) for (i in c(10:1, "G0!")){ plot.new() text(.5, .5, i, cex = 6) } dev.off() # Converting .png files in one .gif image using ImageMagick system("/opt/local/bin/convert -delay 80 *.png example_1.gif") # Remove .png files from working directory file.remove(list.files(pattern=".png"))
1 - The system() function executs the conversion command as in a terminal. I use the absolute path to the convert command. In my case it is: /opt/ local/bin/convert. In some cases the command system("convert -delay 80 *. Example_1.gif png") works.
2 - the flag -delay is the time between two images (the speed of the animation).
3-The part "%02d" in the filename increment automatically the .png file names
Result
The result is :
Example 2: Creating a 3D animated graphic
We will create a 3D surface plot to visualize a linear model using lattice package. 3D graphics can be created also with rgl package.
R code
Code R :
library(lattice) b0 <- 10 b1 <- .5 b2 <- .3 g <- expand.grid(x = 1:20, y = 1:20) g$z <- b0 + b1*g$x + b2*g$y png(file="example%03d.png", width=300, heigh=300) for (i in seq(0, 350 , 10)){ print(wireframe(z ~ x * y, data = g, screen = list(z = i, x = -60))) } dev.off() # converting .png file in .gif using ImageMagick system("/opt/local/bin/convert -delay 40 *.png example_2_reduced.gif") # Remove .png file file.remove(list.files(pattern=".png"))
Result
Source :
http://ryouready.wordpress.com/2010/11/21/animate-gif-images-in-r-imagemagick/