-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgganimate.Rmd
463 lines (346 loc) · 14.6 KB
/
gganimate.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
---
title: "gganimate"
output:
html_document:
highlight: pygments
theme: sandstone
df_print: paged
toc: yes
html_notebook:
highlight: pygments
theme: sandstone
toc: yes
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
# options for the knitted html document
knitr::opts_chunk$set(
echo = T,
eval = T,
message = F,
warning = F,
comment = NA,
R.options = list(width = 120),
cache.rebuild = F,
cache = T,
gganimate = list(nframes = 50),
fig.align = 'center',
fig.asp = .7,
dev = 'png' # need png for gganimate renderer
# dev.args = list(bg = 'transparent') # this will make some themes look bad
)
```
## Getting started
### Installation
You'll need to install `gganimate` as follows.
```{r install, eval=FALSE}
install.packages("gganimate")
```
### Other packages
These packages should be enough for our purposes.
```{r packages, cache=FALSE}
# Packages you need
library(tidyverse); library(gganimate)
# Packages you may not have and can install
library(ggrepel)
library(gapminder)
```
### Demo plots
Here are a couple plots that will serve as a basis for some examples, or can just give you a ready ggplot object to do your own exploration.
```{r sw_plots, eval=TRUE}
load('data/starwars_df.RData') # load starwars data frames
bar_sw = people_df %>%
mutate(homeworld = fct_lump(homeworld, n = 4)) %>%
drop_na(homeworld) %>%
ggplot() +
geom_bar(aes(x = homeworld, fill = homeworld), show.legend = F)
smooth_sw = people_df %>%
filter(!is.na(gender) & !grepl(name, pattern = 'Jabba')) %>%
ggplot(aes(x=mass, y=height)) +
geom_point() +
geom_smooth()
scatter_sw = starships_df %>%
arrange(length) %>%
ggplot(aes(x = length, y = cost_in_credits)) +
geom_point(aes(color = log(cost_in_credits*length)), size = 5, show.legend = F) +
geom_text_repel(aes(label = name), size=6, color = 'gray50') + # requires ggrepel
scale_x_continuous(trans = 'log') +
scale_y_continuous(trans = 'log') +
scale_color_viridis_c()
box_sw = people_df %>%
mutate(species = fct_lump(species, n = 2)) %>%
drop_na(species) %>%
ggplot(aes(x= species, y = mass)) +
geom_boxplot()
```
```{r gm_plots, eval=TRUE}
continent_df = gapminder %>%
group_by(continent) %>%
summarise(lifeExp = mean(lifeExp),
gdpPercap = mean(gdpPercap))
country_df = gapminder %>%
group_by(continent, country) %>%
summarise(lifeExp = mean(lifeExp),
gdpPercap = mean(gdpPercap))
year_df = gapminder %>%
group_by(year) %>%
summarise(lifeExp = mean(lifeExp),
gdpPercap = mean(gdpPercap))
gapminder_std = gapminder %>%
group_by(year) %>%
mutate(lifeExp = scale(lifeExp)[,1],
gdpPercap = scale(gdpPercap)[,1])
bar_gap = gapminder %>%
group_by(continent) %>%
summarise(lifeExp = mean(lifeExp)) %>%
ggplot() +
geom_col(aes(x = continent, y = lifeExp, fill = continent), show.legend = F)
smooth_gap = gapminder %>%
ggplot(aes(x = gdpPercap, y = lifeExp)) +
geom_point() +
geom_smooth() +
scale_x_continuous(trans = 'log') +
scale_y_continuous(trans = 'log')
scatter_gap = country_df %>%
ggplot(aes(x = gdpPercap, y = lifeExp)) +
geom_point(aes(color = gdpPercap*lifeExp), show.legend = F) +
geom_text_repel(aes(label = country), size=2) +
scale_x_continuous(trans = 'log') +
scale_y_continuous(trans = 'log') +
scale_color_viridis_c()
box_gap = gapminder %>%
group_by(continent, country) %>%
summarise(lifeExp = mean(lifeExp)) %>%
ggplot() +
geom_boxplot(aes(x = continent, y = lifeExp, fill = continent), show.legend = F)
```
## A starting point
We start with a simple example to get things going. Note that *all animations will take at least several seconds to produce*. To reduce this you can change the number of frames used, though this will typically make for a choppier plot. Note that output will be forced to the viewer instead of inline also.
```{r first_animation}
box_sw +
transition_states(
species,
transition_length = 2,
state_length = 1
) +
enter_fade() +
exit_shrink() +
ease_aes('sine-in-out')
```
To see what's going on, let's take it step by step. The `transition_states` function specifies how the plot information goes from one state to the next and how 'states' is defined. In this case, our states are represented by species. The `transition_length` is the 'relative length of the transition', but can be as many values as there are states. The `state_length` determines how long we pause (in terms of number of frames) at each state. We'll talk about the others as we go along.
Typically you may want to assign the plot to an object so that you can use the `animate` function for more control.
```{r box, eval=F}
p_box = box_sw +
transition_states(
species,
transition_length = 2,
state_length = 1
) +
enter_fade() +
exit_shrink() +
ease_aes('sine-in-out')
animate(p_box, nframes = 50)
```
## Transitions
There are many **transitions**, though `_states` and `_reveal` are probably ones you'll use a lot. The former works on some categorical variable as we saw before, while the latter works on an ordered (numeric) variable. A variant of it is `transition_time`, which can work with an actual date/time variable. In the following, we examine life expectancy over time with the gapminder data. We'll see how to pause the visualization at the end for a specific number of frames.
```{r transition_time}
yr_life_exp = year_df %>%
ggplot(aes(x = year, y = lifeExp, group = 1)) +
geom_point(size = 10, color = '#ff5500') +
theme_minimal()
p_time = yr_life_exp +
transition_time(year)
animate(p_time, end_pause = 25)
```
We can use the `glue` package to insert text into the titles. Each type of transition you create comes with named objects we can use. With `transition_time`, the unique value is `frame_time`, but others are generically available. See the corresponding help files for what all is available.
```{r glue}
p_glue = yr_life_exp +
transition_time(year) +
ggtitle('Now showing {frame_time}',
subtitle = 'Frame {frame} of {nframes}')
animate(p_glue, nframes=50)
```
Another that might come in handy is revealing the plot by the layers used to construct it. With the following we introduce some redundancy to take advantage of this.
```{r transition_layers}
mass_height = people_df %>%
filter(!is.na(gender) & !grepl(name, pattern = 'Jabba')) %>%
ggplot(aes(x=mass, y=height)) +
geom_point(alpha = .5) +
geom_point(aes(color = species == 'Human'), show.legend = F) +
geom_smooth(se = T, color = NA) +
geom_smooth(se = F, color = '#00aaff') +
geom_smooth(se = F, method = 'lm', color = '#ff5500') +
theme_void()
p = mass_height +
transition_layers()
animate(p, nframes = 50)
```
The list of transitions includes:
- `transition_components`
- `transition_events`
- `transition_filter`
- `transition_layers`
- `transition_manual`
- `transition_null`
- `transition_reveal`
- `transition_states`
- `transition_time`
## Shadows
Shadows can add a nice effect to show paths over some index, especially time. The following recreates the famous TED talk visualization, which attempted to show how much better things were getting (if you ignored a lot of other factors).
```{r shadows}
p = gapminder %>%
ggplot(aes(x = gdpPercap, y = lifeExp)) +
geom_point(aes(color = country, size = pop), alpha = .25, show.legend = F) +
ggtitle('Year: {frame_time}') +
scale_size(guide = F) +
scale_x_continuous(trans = 'log') +
scale_y_continuous(trans = 'log', breaks = seq(30, 80, by = 10)) +
theme_minimal()
p +
transition_time(year)
```
The following shows the data for just a handful of countries. We'll use both `shadow_mark` and `shadow_trail`. The former can shadow past vs. future data points, while the latter has additional options for leaving a trail of symbols behind.
```{r shadow_mark}
p = gapminder_std %>%
filter(country %in% c('China', 'India', 'Norway', 'United States')) %>%
ggplot(aes(x = gdpPercap, y = lifeExp)) +
geom_point(aes(color = country, size = pop), alpha = .25) +
ggtitle('Year: {frame_time}') +
scale_size(guide = F) +
theme_minimal()
p +
transition_time(year) +
shadow_mark()
```
```{r shadow_trail}
p +
transition_time(year) +
shadow_trail(distance = .02, alpha = 0.3, shape = 1)
```
Maybe things hadn't changed that much after all for some, relatively speaking, or only improved in one domain.
## Enter/Exit
We have many options for how the plots enter and leave the space. In the following, we use `enter_drift` to let the previous plot linger a bit.
```{r enter}
box_gap +
transition_states(continent) +
enter_drift()
```
The following might be fun as an exercise to demonstrate `grow/shrink` and, but please don't do this to try and spruce up a boring bar graph. After running, set the size of `enter_grow` to 1 to see what it changes.
```{r exit}
bar_gap +
transition_states(continent) +
enter_grow(size = .5) +
exit_shrink(size = .1)
```
Here are the options we can play with. Each `enter_*` function has a corresponding `exit_*` function.
- `enter_manual`, `exit_manual`
- `enter_appear`, `exit_disappear`
- `enter_fade`, `exit_fade`
- `enter_grow`, `exit_shrink`
- `enter_recolour`, `exit_recolour`
- `enter_recolor`, `exit_recolor`
- `enter_fly`, `exit_fly`
- `enter_drift`, `exit_drift`
- `enter_reset`, `exit_reset`
## Easing
With easing we can define the velocity with which aesthetics change during an animation. This is done with `ease_aes`. By default the transition is 'linear', but let's see some others.
```{r ease}
p = gapminder %>%
filter(year %in% c(1962, 2002)) %>%
mutate(year = factor(year)) %>%
ggplot(aes(x = gdpPercap, y = lifeExp)) +
geom_point(aes(color = country, group = 1), alpha = .25, show.legend = F)
p +
transition_states(year, transition_length = 5, state_length = 1) +
enter_fade() +
exit_fade() +
ease_aes(y = 'bounce-in-out')
```
```{r ease2}
p +
transition_states(year, transition_length = 5, state_length = 1) +
enter_fade() +
exit_fade() +
ease_aes('elastic-in-out')
```
Easing functions:
- `quadratic` Models a power-of-2 function
- `cubic` Models a power-of-3 function
- `quartic` Models a power-of-4 function
- `quintic` Models a power-of-5 function
- `sine` Models a sine function
- `circular` Models a pi/2 circle arc
- `exponential` Models an exponential function
- `elastic` Models an elastic release of energy
- `back` Models a pullback and release
- `bounce` Models the bouncing of a ball
Modifiers
-`in` The easing function is applied as-is
-`out` The easing function is applied in reverse
-`in-out` The first half of the transition it is applied as-is, while in the last half it is reversed
## Animate options
When using `animate`, you have some options you'll commonly want to alter that will affect the animation appearance. Here are the ones you'll probably want to fiddle with most.
- `nframes` The number of frames to render (default 100)
- `fps` The frame rate of the animation in frames/sec (default 10)
- `duration` The length of the animation in seconds (unset by default)
- `start/end_pause` Number of times to repeat the first and last frame in the animation
- `rewind` Should the animation roll back in the end (default FALSE)
## Common issues
#### Simple breakage
Often you'll just get an error. This means you'll need to read the documentation closely, as you likely have not used the correct variable type, and in general have not provided the function what it expects.
As an example, let's try to use `transition_reveal` for a categorical variable.
```{r borked, error=TRUE}
box_gap +
transition_reveal(continent)
```
It states clearly what's needed for this transition, and we didn't provide it. We can change to `transition_states` for example.
#### But it worked before!
Sometimes what *should* work apparently does not. For example look at the following, which is our easing example from before. This time, no bounce!
```{r broken_bounce}
p = people_df %>%
mutate(Human = factor(species == 'Human', labels = c('Other', 'Human'))) %>%
filter(!is.na(gender) & !grepl(name, pattern = 'Jabba')) %>%
drop_na(Human, mass, height) %>% # to remove warnings
ggplot(aes(x = mass, y = height)) +
geom_point(aes(color = Human), show.legend = T)
p +
transition_states(Human,
transition_length = 5,
state_length = 1) +
enter_fade() +
exit_fade() +
ease_aes(y = 'bounce-in-out')
```
The variables Why does this happen? Because behind the scenes some sort of grouping is being done on the data. By specifying the color argument, we only have the two groups, while we want each individual point to bounce. If we add a `group = 1` aesthetic for `geom_point` as we did the first time, we can get what we want. As stated in the documentation, the group aesthetic defines how the data in a layer is matched across the animation.
```{r fixed_bounce}
p = people_df %>%
mutate(Human = factor(species == 'Human', labels = c('Other', 'Human'))) %>%
filter(!is.na(gender) & !grepl(name, pattern = 'Jabba')) %>%
drop_na(Human, mass, height) %>% # to remove warnings
ggplot(aes(x = mass, y = height)) +
geom_point(aes(color = Human, group = 1), show.legend = T) # change made here
p +
transition_states(Human, transition_length = 5, state_length = 1) +
enter_fade() +
exit_fade() +
ease_aes(y = 'elastic-in-out')
```
#### Wrong transition to convey the effect
The previous plot makes it look as though humans are transitioning to/from non-humans. In this case, it would be more appropriate to not have such a transition ease. We can still use other effects, like enter/exit, if we like.
```{r right_transition}
p = people_df %>%
mutate(Human = factor(species == 'Human', labels = c('Other', 'Human'))) %>%
filter(!is.na(gender) & !grepl(name, pattern = 'Jabba')) %>%
drop_na(Human, mass, height) %>% # to remove warnings
ggplot(aes(x = mass, y = height)) +
geom_point(aes(color = Human, group = Human), show.legend = T)
p +
transition_states(Human, transition_length = 2, state_length = 1) +
enter_fade() +
exit_drift(x_mod = 0, y_mod = 100)
```
#### R Markdown
You may find a number of issues arise when using the animations in R Markdown, especially with non-default device settings, and even if it runs fine with the chunk code. It may be easiest to save the plot and load the file instead.
## Summary
Animation is a great way to enhance a plot and tell a data driven story. It can definitely be overkill for many situations though, and so should be used with caution. With the right approach though, you can take your visualizations further, and have some fun doing it too!