• Stars
    star
    1,935
  • Rank 23,945 (Top 0.5 %)
  • Language
    R
  • License
    Other
  • Created almost 9 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Grammar of Animated Graphics

gganimate

R-CMD-check CRAN_Status_Badge CRAN_Download_Badge Codecov test coverage

gganimate extends the grammar of graphics as implemented by ggplot2 to include the description of animation. It does this by providing a range of new grammar classes that can be added to the plot object in order to customise how it should change with time.

  • transition_*() defines how the data should be spread out and how it relates to itself across time.
  • view_*() defines how the positional scales should change along the animation.
  • shadow_*() defines how data from other points in time should be presented in the given point in time.
  • enter_*()/exit_*() defines how new data should appear and how old data should disappear during the course of the animation.
  • ease_aes() defines how different aesthetics should be eased during transitions.

An Example

All of the above might seem a bit abstract. Let’s try with a contrived example:

library(ggplot2)
library(gganimate)

ggplot(mtcars, aes(factor(cyl), mpg)) + 
  geom_boxplot() + 
  # Here comes the gganimate code
  transition_states(
    gear,
    transition_length = 2,
    state_length = 1
  ) +
  enter_fade() + 
  exit_shrink() +
  ease_aes('sine-in-out')

Here we take a simple boxplot of fuel consumption as a function of cylinders and lets it transition between the number of gears available in the cars. As this is a discrete split (gear being best described as an ordered factor) we use transition_states and provides a relative length to use for transition and state view. As not all combinations of data is present there are states missing a box. We define that when a box appears it should fade into view, whereas at should shrink away when it disappear. Lastly we decide to use a sinusoidal easing for all our aesthetics (here, only y is changing)

Installation

gganimate is available on CRAN and can be installed with install.packages('gganimate'). If you wish to install the development version you can install directly from github using devtools:

# install.packages('pak')
pak::pak('thomasp85/gganimate')

Yet Another Example

It is impossible to cover everything possible with gganimate in a README, but animations are fun, so let’s at least have one more:

library(gapminder)

ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
  geom_point(alpha = 0.7, show.legend = FALSE) +
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  facet_wrap(~continent) +
  # Here comes the gganimate specific bits
  labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
  transition_time(year) +
  ease_aes('linear')

In this example we see the use of transition_time() which can be used with continuous variables such as year. With this transition it is not necessary to provide transition and state length as the “transition variable” provides this directly (e.g. it should take twice as long to transition between 1980 and 1990 compared to 2000 to 2005). We also see the use of string literal interpolation in titles. gganimate lets you specify variables to evaluate inside titles and different transitions provide different type of information to use.

Where is my animation?

gganimate mimics the way ggplot2 renders its output, in that the rendering is done automatically when the gganim object is printed. Under the hood, the animate() function is called which renders the frame and passes the frames to a renderer functions which takes care of combining them to the final animation. The default renderer is gifski_renderer() which returns a gif_image object which is a simple wrapper around a path to a gif file. If animate() has been called implicitly as part of print the gif_image object is available using the last_animation() function (analogous to ggplot2::last_plot()). In order to save the animation to a specific location, you can use the anim_save() function which, like ggplot2::ggsave, defaults to taking the last rendered animation and writes it to a file.

I don’t like gifs…

gif is a fantastic format for animations due to its wide support, but sometimes another format is required. gganimate is agnostic to the renderer and while the default is to use gifski to combine the frames into a gif, it doesn’t have to be so. By passing an alternate renderer to the animate() function you can control the animation format, and gganimate comes with a bunch (and you can write your own). To create video files you can e.g. use the ffmpeg_renderer():

p <- ggplot(airquality, aes(Day, Temp)) + 
  geom_line(size = 2, colour = 'steelblue') + 
  transition_states(Month, 4, 1) + 
  shadow_mark(size = 1, colour = 'grey')
animate(p, renderer = ffmpeg_renderer())

Video output are automatically embedded in RMarkdown documents, but GitHub strips video when rendering READMEs so you can’t see it here

Further there’s support for rendering to sprite sheets if that is your vice.

Old API

This is the second iteration of the gganimate package. The first, developed by David Robinson had a very different API, and relied on specifying animation frame membership inside aes() blocks in the geom_*() calls. This approach was easy to grasp, but essentially limited in capabilities and has thus been abandoned for a more thorough grammar.

Code written for the old API will not work with this gganimate version and there will not come a future support for it. If you wish to continue using the old API then avoid upgrading gganimate. If you’ve already upgraded and wish to downgrade, the latest version of the old API is available as a GitHub release.

If you wish to convert your old animations to the new API, the closest you get is probably with transition_manual, even though it is not completely substitutable:

# Old code
ggplot(mtcars) + 
  geom_boxplot(aes(factor(cyl), mpg, frame = gear))

# New code
ggplot(mtcars) + 
  geom_boxplot(aes(factor(cyl), mpg)) + 
  transition_manual(gear)

More Repositories

1

patchwork

The Composer of ggplots
R
2,431
star
2

ggraph

Grammar of Graph Graphics
R
1,063
star
3

ggforce

Accelerating ggplot2
R
915
star
4

tidygraph

A tidy API for graph manipulation
R
545
star
5

ggplot2_workshop

Material for "Drawing Anything with ggplot2" workshop
491
star
6

lime

Local Interpretable Model-Agnostic Explanations (R port of original Python package)
R
480
star
7

scico

Palettes for R based on the Scientific Colour-Maps
R
409
star
8

tweenr

Interpolate your data
R
399
star
9

fiery

A flexible and lightweight web server
R
242
star
10

shinyFiles

A shiny extension for server side file access
JavaScript
195
star
11

ggfx

Filters and Shaders for 'ggplot2'
R
166
star
12

densityClust

Clustering by fast search and find of density peaks
R
150
star
13

farver

High Performance Colourspace Manipulation in R
R
127
star
14

particles

A particle simulation engine based on a port of d3-force
R
118
star
15

transformr

Smooth Polygon Transformations
R
115
star
16

ambient

A Generator of Multidimensional Noise
R
93
star
17

euclid

Exact Computation Geometry Framework Based on 'CGAL'
C++
82
star
18

routr

Routing of Web Requests in R
R
55
star
19

hierarchicalSets

Scalable Set Visualization using Hierarchies
R
54
star
20

Hr

Easy Access to Uppercase H
R
53
star
21

reqres

Powerful classes for http requests and responses
R
36
star
22

curry

Partial Function Application with %<%, %-<%, and %><%
R
30
star
23

FindMyFriends

Fast alignment-free pangenome creation and exploration
R
27
star
24

pipeplotter

Syntactic ggplot2 Sugar for a Tidy World
R
26
star
25

fawkes

An R Interface to the AxiDraw plotter
R
25
star
26

pearls

Operations on Lists of Data Frames
R
18
star
27

PanVizGenerator

Create your own PanViz visualizations
R
18
star
28

ink

The Modern, High-Performant, Graphic Device for R
C++
17
star
29

ggplot2_mechanics

The Mechanics of ggplot2
TeX
16
star
30

plotting_benchmark

Investigating R graphics performance
HTML
16
star
31

grid

personal devel version of grid
R
15
star
32

PanViz

D3 based visualisation for comparative genomics
JavaScript
14
star
33

boundaries

Algorithms for Working With and Modifying Polygon Boundaries
C++
13
star
34

data_imaginist

data_imaginist source
HTML
12
star
35

nanodev

Graphic Devices for R based on NanoVG
C
10
star
36

MSGFgui

A gui overlay and extension for MSGFplus
R
10
star
37

orion

Spatial Searching for Euclid
C++
9
star
38

web_dev_in_R

Web Development for R Users
TeX
9
star
39

heroku-fiery-demo

A demo fiery application for deployment on Heroku
R
8
star
40

unmeshy

A Vector Based 3D Renderer
C++
7
star
41

MSsary

Mass spectrometry data in R
R
7
star
42

RcppSNAP

'Rcpp' Integration for the SNAP Network Library
C++
6
star
43

tidy_graph_analysis

Tidy Network Analysis in R
TeX
6
star
44

polyclid

Polygon Support for Euclid
C++
6
star
45

mzID

An mzIdentML parser for R
R
6
star
46

MSGFplus

An MSGF+ interface for R
R
6
star
47

thomasp85.github.io

The source for data-imaginist.com
HTML
6
star
48

mvpcran

CRAN on a stick
R
5
star
49

shady

Compile and Execute Shaders from R
C++
5
star
50

anomaly

Detecting those outliers
R
4
star
51

firedock

Dockerfiles for fiery
R
4
star
52

phd_dissertation

Pangenome Tools for Rapid, Large-Scale Analysis of Bacterial Genomes
TeX
4
star
53

d3Disco

A showcase for Shiny and D3 integration
JavaScript
4
star
54

pepmaps

R package for quantitative peptidomics
R
2
star
55

masochist

For some reason I’m doing all of this from my phone
R
2
star
56

firedock_test

R
1
star
57

Biotools

Scripts for CMG-Biotools
Perl
1
star
58

firesafety

Security for fiery apps
1
star
59

circosScripts

Perl scripts to automate circos plots
Perl
1
star
60

CHtools

A list of diverse functions for CH
R
1
star