2 min read

Engifification in R with gifski

Matt Dray


Gif of sloth on pizza in space

gifski::gifski()

You and I both know that the world needs more intergalatic-sloth-pizza gifs.

Great news: ‘the fastest gif encoder in the universe’ has been created. The gifski package for R is now in CRAN. It’s a simple yet fast and powerful way to create gifs from within R, built by Jeroen Oom (@opencpu) for ROpenSci.

The obvious application is for creating gifs from plots, as in the following example from the ROpenSci announcement.

Example of ggplot animation produced with gifski

dray::make_gif()

I’ve made a quick function for my dray package that – in one line of code – takes a folder of PNGs and stitches them into a gif using the gifski::gifski() function. I’ve called it make_gif() because it makes gifs. Mostly I’ve done this for my own benefit, but maybe you’ll find it useful too.

You can find the documentation on the dray package site, which is built with the awesome pkgdown package.

Also I’m endorsing the verb ‘to engif’ as in ‘I am engiffing a bunch of PNGs’. Join me.

Example

There’s an example of producing a hand-made gif (i.e. an artisanal gif) on the gifski help pages (execute ?gifski in your console). It looks like this:

png_path <- file.path(tempdir(), "frame%03d.png")
png(png_path)
par(ask = FALSE)
for(i in 1:10)
  plot(rnorm(i * 10), main = i)
dev.off()
png_files <- sprintf(png_path, 1:10)
gif_file <- tempfile(fileext = ".gif")
gifski(png_files, gif_file)
unlink(png_files)
utils::browseURL(gif_file)

With dray::make_gif() you supply two things:

  1. a path to a folder containing the images
  2. a path for where the gif should be written
dray::make_gif(
  png_folder = "img",  # folder containing PNGs
  gif_path = "gif/intergalactic-sloth-pizza.gif"  # path for the output
)

I created the following very important gif with make_gif() from seven PNG images.

Gif of the evolution chain of the Pokemon Lotad

You should make sure your PNGs are ordered alphabetically or numerically in the folder so that they’re engiffed (see, isn’t that a great verb?) in the right order. Don’t worry if your folder has other filetypes; make_gif() only extracts PNGs. You’ll get a warning if you try to make a gif with less than two PNGs, obviously.

So get out there and engif to your heart’s content!

Gif of cat on pizza in space