![Gif of a sloth riding a pizza slice in space.](https://media.giphy.com/media/I8eorWE0QuYYU/giphy.gif)
A sloth. On a pizza slice. In space. (via Giphy)
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 on CRAN. It’s a simple yet fast and powerful way to create gifs from within R, built by Jeroen Ooms) for rOpenSci.
The obvious application is for creating gifs from plots, as in the following example from the ROpenSci announcement, which shows life expectancy by GDP per capita with a different year for each frame of the gif.
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’.
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:
- a path to a folder containing the images
- 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.](https://media.giphy.com/media/oNrPlnnezq1tjhSkH8/giphy.gif)
Lotad is the best
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.
So get out there and get engiffing.
Also!
Consider:
- {magick}, also by Jeroen Ooms for rOpenSci, which lets you use the power of ImageMagick to manipulate your images before turning them into a gif (website, vignette)
- {gganimate} for animating plots by Thomas Lin Pedersen and David Robinson (website), which uses {gifski} as its renderer, though you can also use ffmpeg