Site icon R-bloggers

Animating and labeling figures with ImageMagick

[This article was first published on Jonathan Chang, 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.

ImageMagick is an incredible command-line tool that lets you edit and convert images of all sorts. Suppose you wanted to compare some figures that you’ve generated, and label the figures with their respective filenames so that you know which is which. Here’s a quick worked example in R and Terminal that gets you going.

First, let’s generate some figures to compare. The latest version of ggplot2 (3.0) recently added the new viridis color palettes as an option, and by default, that are ordered factors use the viridis palettes when assigned to the color or fill aesthetic. Let’s plot the default diamonds dataset to compare the two:

library(ggplot2)
# Uses viridis by default
ggplot(diamonds, aes(carat, price, color = clarity)) + geom_point()
ggsave("diamonds_ordered.png")
# Unorder the factor to use the unordered palette
ggplot(diamonds, aes(carat, price, color = factor(clarity, ordered = FALSE))) + geom_point() + labs(color = “clarity”)
ggsave(“diamonds_unordered.png”)

Next, let’s fire up ImageMagick to convert this to an animated GIF. Sadly we can’t use this in papers yet but it can easily be blogged or tweeted about. brew install imagemagick if you don’t have it already, then:

convert -resize 33% -gravity north -undercolor '#ffffff80' -pointsize 16 -annotate 0 "%f" diamonds_*.png -set delay 100 -loop 0 diamonds_flicker.gif

This does a few things:

Here’s the end result:

There’s a lot of cool stuff that ImageMagick can do (basically every kind of image manipulation imaginable), so check out the manual and start hacking!

To leave a comment for the author, please follow the link and comment on their blog: Jonathan Chang.

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.