Site icon R-bloggers

Animated Plots with R

[This article was first published on Playing with R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.


Using ImageMagick it’s pretty easy to make an animated gif from a set of plots. Essentially the way to do it is to save a plot for each frame of the animation and then convert them into a .gif. Here’s a simple example that plots binomial density’s for two different success rates and n between 1 and 50.

#set working directory setwd('~/Documents/R/images/') frames = 50 for(i in 1:frames){ # creating a name for each plot file with leading zeros if (i < 10) {name = paste('000',i,'plot.png',sep='')}
if (i < 100 && i >= 10) {name = paste('00',i,'plot.png', sep='')} if (i >= 100) {name = paste('0', i,'plot.png', sep='')} x = seq(0, i, 1) f.3 = dbinom(x, size = i, prob=.3) f.7 = dbinom(x, size = i, prob=.7) #saves the plot as a .png file in the working directory png(name) plot(x, f.3, type='h', xlim = c(0,frames), ylim = c(0,.7), ylab ='probability', main = paste(‘Binomial density with n = ‘, i), col = ‘red’)
lines(x,f.7,type='h',col='blue') text(45, .6, 'p = .3', col='red') text(45, .6, 'p = .7', col='blue', pos=1) dev.off() }

The important part of the code is the png function. This function saves the plot as a .png file in the working directory (there are aslo jpeg, bmp, and tiff functions that work the same way). Anything between the png and dev.off() will be saved in the plot.

After running this code there will be 50 .png files in your working directory. Now it’s time to use ImageMagick. From a command line navigate to the directory where the .png files are saved and enter the following command.

$ convert *.png -delay 3 -loop 0 binom.gif

This will convert all the .png files into a animated .gif file. The -delay 3 option sets the delay between frames. The -loop 0 option makes it so the .gif repeats forever, -loop 5 would repeat the animation 5 times.


An After Thought: I made this plot just as a simple example but I think it’s also a nice visualization of hypothesis testing. In the animation we can see the power of the corresponding simple versus simple hypothesis test goes to 1 as n increases. Also, I haven’t tried it, but it might be neat to look at the animation with 3D glasses.

To leave a comment for the author, please follow the link and comment on their blog: Playing with R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.