Animated TreeMaps in R - the hard way
As I am a bear of very little brain, these are notes to myself on my slightly shonky process for creating animated TreeMaps in R. The aim is to end up with something like this:
Generate the images
Getting the data is left as an exercise for the reader (sorry!). This loops through the data and generates a separate image for each TreeMap:
Rfor(week in weeks) {
weekly_data <- subset(file_data, Week == week)
size <- sqrt(sum(weekly_data$Count)) / 2
if (size < 40) {
size <- 40
}
map <- ggplot(weekly_data, aes(area = Count, label = paste(Filetype,formatC(Count, big.mark=",") ,sep="\n"), subgroup = Category, fill=Category)) +
geom_treemap(layout="fixed") +
geom_treemap_text(colour = "white", place = "centre", grow = TRUE, layout="fixed")
file_name <- paste("media/", weekly_data$Week[1], ".png", sep="")
ggsave(file_name, map, width = size, height = size, units = "mm")
}
The width and height are proportionate the the square-root of the size of the data. Annoyingly, ggplot works in millimetres rather than pixels!
If images are too small, R throws an error of "Viewport has zero dimension(s)". So this sets a minimum size. This value was found using trial and error.
The layout is fixed, as per the documentation which keeps the order of the elements and their labels.
Resize and reorientate the images
Now I have a directory of images, each a different size. I want all of them to have the same size canvas and to be placed against the right-hand edge.
mogrify -gravity east -background white -extent 1750x1750 *.png
That sets the "gravity" to the right - so the original image is centred vertically but is up against the right edge. The extent
is the dimension of the new image.
Mogrify overwrites the original images.
Make a video
This is a lazy way to shove all the images into a video.
cat *.png | ffmpeg -f image2pipe -r 10 -vcodec png -i - -vcodec libx264 out.mp4
or
ffmpeg -framerate 8 -pattern_type glob -i '*.png' -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4
Some websites will need further conversion as they have specific codec requirements.
That's it
It isn't the prettiest way to do things, but it seemed pretty effective. If you know of a more efficient - or more R-ish way to accomplish the same animation - please let me know.
Andrew Fraser said on twitter.com:
gganimate? gganimate.com