forked from allisonhorst/eds-ggplot2-gganimate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgganimate_key.Rmd
377 lines (268 loc) · 15.3 KB
/
gganimate_key.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
---
title: "Intro to ggplot2 with gganimate"
subtitle: "Eco-Data-Science (January 2019)"
author: "Allison Horst"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
In this workshop, we'll practice some skills for creating animated graphics with ggplot2 and gganimate, plus some other cool things.
*Note: We won't be doing all of these examples in the workshop, but they're here for you to explore.*
Visit and fork the workshop repo on github for information and data.
**Packages required:**
- tidyverse
- gganimate
- ggrepel
- ggridges
Get the development version of gganimate:
```r
# install.packages('devtools')
# devtools::install_github('thomasp85/gganimate')
```
###An overview of gganimate terms
gganimate is an awesome new (and growing) package for intuitive graphics animation by Thomas Lin Pedersen (<https://github.com/thomasp85/gganimate>).
Some important terms to get us started:
- **state:** a 'phase' that you could plot statically, but you want to create transitions between for different phases (years, species, countries, etc.) - these might be things that you would otherwise consider plotting in different facets. So make sure that you can plot these statically FIRST, then add transitions!
- **transition:** How you want to shift from one state to another visually. These include things like: Will there be interpolation between states or frames? Ask yourself: does having a motion transition between things make sense? Would you put a line between them on a graph?
- **tweening:** Interpolation between states to determine pathway function. Default is linear...but we can change that to make it a little more fun. Also keep in mind that this doesn't always make sense!
- **ease_aes:** Visually update the 'look' of transitions **between states** by setting a function. Elastic is a pretty fun one. Check display_ease() from tweenr to see options for in/out functions for tweening interpolation. Note that you can add 'in' or 'out' separately, or 'in-out' for symmetric function at interpolation endpoints.
- **enter and exit:** How will things enter and exit **WITHIN STATES** at the beginning and end (fade, etc.)? Better to tween between discrete groups (vs. transition connected)
###My three pieces of advice for getting started (from a gganimate beginner)
- Make a static version first, ensuring that you can see all of your different states separately (and successfully), possibly using facet_wrap. Then...
- Start simply, then build animation pieces.
- Don't do it just because you *can*, do it because it's helps create an engaging visual that is scientifically sound *AND* benefits audience understanding *AND* looks awesome.
```{r, message = FALSE}
library(tidyverse)
library(gganimate)
library(ggrepel)
library(ggridges)
```
###1. Getting started: Channel Island Fox population on Santa Rosa Island
a. Data (ci_fox_pop.csv): Friends of the Island Fox (<http://www1.islandfox.org/2014/>)
```{r, message = FALSE, warning = FALSE}
# Get data:
ci_fox_pop <- read_csv("ci_fox_pop.csv")
# Gather it:
fox <- ci_fox_pop %>%
gather(island, pop, san_miguel:san_nicolas)
# Make a static plot frst!
ggplot(fox, aes(x = year, y = pop)) +
geom_point(size = 3, aes(color = island)) +
theme_dark() +
scale_colour_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery") +
scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
scale_x_continuous(expand = c(0,0), limits = c(1994, 2016)) +
facet_wrap(~year)# yes, this makes no sense - but this is what we want. All of the different states are plotting separately. That's good! We're going to combine them using gganimate transitions.
```
b. Now let's make an animated version using transition_states:
From: <https://rdrr.io/github/dgrtwo/gganimate/man/transition_states.html>:
"[transition_states] splits your data into multiple states based on the levels in a given column, much like ggplot2::facet_wrap() splits up the data in multiple panels. It then tweens (interpolates) between the defined states and pauses at each state."
```{r, warning = FALSE}
# Make an animated version (remove facet_wrap, instead add animation) - 30 seconds
ggplot(fox, aes(x = year, y = pop)) +
geom_point(size = 3, aes(color = island)) +
theme_dark() +
scale_colour_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery") +
scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
scale_x_continuous(expand = c(0,0), limits = c(1994, 2016)) +
transition_states(states = year, transition_length = 1, state_length = 1, wrap = FALSE)
```
c. Changing ease functions (ease_aes) between states, and adding a shadow_wake
A fun thing to explore while rendering: <https://easings.net/>
```{r, warning = FALSE}
ggplot(fox, aes(x = year, y = pop)) +
geom_point(size = 3, aes(color = island)) +
theme_dark() +
scale_colour_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery") +
scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
scale_x_continuous(expand = c(0,0), limits = c(1994, 2016)) +
transition_states(states = year, transition_length = 1, state_length = 1, wrap = FALSE) +
ease_aes('cubic-in-out') +
shadow_wake(wake_length = 0.2)
```
d. Use shadow_mark to leave previous frame points behind!
```{r, warning = FALSE}
# Also try shadow_mark to leave a point:
ggplot(fox, aes(x = year, y = pop)) +
geom_point(size = 3, aes(color = island)) +
theme_dark() +
scale_colour_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery") +
scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
scale_x_continuous(expand = c(0,0), limits = c(1994, 2016)) +
transition_states(states = year, transition_length = 1, state_length = 1, wrap = FALSE) +
ease_aes('cubic-in-out') +
shadow_mark()
```
e. Create an animated line graph of fox populations with transition_reveal():
From Thomas Lin Pedersen (<https://github.com/thomasp85/gganimate/wiki/Temperature-time-series>): "We use transition_reveal() to allow the lines to gradually be build up. transition_reveal() knows to only keep old data for path and polygon type layers which means that our segment, point, and text layers only appears as single data points in each frame."
```{r, warning = FALSE}
# And now with a line graph (transition_reveal):
ggplot(fox, aes(x = year, y = pop)) +
geom_line(size = 1, aes(color = island)) +
theme_dark() +
scale_colour_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery") +
scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
scale_x_continuous(expand = c(0,0), limits = c(1994, 2016)) +
transition_reveal(id = island, along = year) + # really wants two things...
ease_aes('quadratic-in-out')
```
f. Add labels to the animated line graph of fox populations
```{r, warning = FALSE}
ggplot(fox, aes(x = year, y = pop, group = island)) +
geom_line(size = 1, aes(color = island)) +
geom_segment(aes(xend = 2016, yend = pop), linetype = 2, colour = 'grey') +
geom_label(aes(x = 2016.5, label = island, fill = island), hjust = 0, color = "black") +
theme_dark() +
theme(legend.position = "none") +
scale_color_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
scale_fill_manual(values = c("white", "yellow","orange","magenta", "aquamarine","olivedrab1")) +
labs(x = "Year", y = "Fox Population", title = "Channel Island Fox Recovery\nYear: {frame_along}") +
scale_y_continuous(expand = c(0,0), limits = c(0,2000)) +
scale_x_continuous(expand = c(0,0), limits = c(1994, 2022)) +
transition_reveal(id = island, along = year) + # really wants two things...
ease_aes('quadratic-in-out')
```
###2. Star Wars characters: transition_manual, transition_layers, ggrepel, rendering gifs to send to all your friends and family
a. The 'starwars' dataset exists in dplyr (part of the tidvyerse), with data from the Star Wars API (<https://swapi.co/>). First, look at the data.
```{r}
View(starwars)
```
b. Filter to only include data for species: human, droid, wookiee, ewok. Relevel species with forcats' fct_relevel
```{r}
sw <- starwars %>%
filter(species == "Human" | species == "Droid" | species == "Wookiee" | species == "Ewok") %>%
mutate(species = factor(species))
sw$species <- fct_relevel(sw$species, "Ewok","Droid","Human","Wookiee")
```
c. Remember the first step I recommend for gganimate: make a static version first, with different states (in this case, species) separated using facet_wrap:
Another thing included here:
geom_text_repel (from ggrepel) - for "repulsive textual annotations" (seriously, see the documentation with ?geom_text_repel)
```{r, warning = FALSE}
# Static version:
ggplot(sw, aes(x = height, y = mass, label = name)) +
geom_point(aes(color = species)) +
geom_text_repel(size = 2, segment.color = "gray60", segment.size = 0.2) +
scale_color_manual(values = c("orange","navyblue","magenta","forestgreen")) +
theme_bw()# Yeah, looks bad but this is what we want!
```
d. Now that the static version is working, make an animated version using transition_manual
From <https://rdrr.io/github/dgrtwo/gganimate/man/transition_manual.html>:
"[transition_manual] allows you to map a variable in your data to a specific frame in the animation. No tweening of data will be made and the number of frames in the animation will be decided by the number of levels in the frame variable."
```{r, warning = FALSE}
# Animated version (copied from above, minus facet_wrap):
sw_graph <- ggplot(sw, aes(x = height, y = mass, label = name)) +
geom_point(aes(color = species), size = 3) +
labs(title = "Species: {current_frame}") +
geom_text_repel(size = 3, segment.color = "gray60", segment.size = 0.2) +
scale_color_manual(values = c("orange","navyblue","magenta","forestgreen")) +
theme_bw() +
transition_manual(frames = species) # No tweening! That makes sense if you don't have a logical path between states. Just want discrete frames that follow each other. Note: There is an argument 'cumulative = TRUE' that seems to be under development with some issues in newer versions...check back later to see if working.
sw_graph
# Rendering so you can send this to all your friends:
# animate(sw_graph, nframes = 4, renderer = gifski_renderer("sw_graph.gif"))
```
e. Use transition_layers to animate geoms on top of each other
From gganimate documentation: "[transition_layers] gradually adds layers to the plot in the order they have been defined. By default prior layers are kept for the remainder of the animation, but they can also be set to be removed as the next layer enters."
Try using different enter_ options to change how the layers appear (e.g. enter_fade()). *Note*: exit_ options also exist, but since the layers are NOT exiting, it's NA here. See the second example for an exit_ example.
```{r, warning = FALSE}
ggplot(sw, aes(x = height, y = mass, label = name)) +
geom_point(color = "gray50", size = 4) +
geom_smooth(method = "lm", se = FALSE, color = "black", lty = 5, size = 0.5) +
geom_smooth(method = "lm", se = TRUE, color = "NA") +
scale_color_manual(values = c("orange","navyblue","magenta","forestgreen")) +
theme_bw() +
transition_layers(layer_length = 1, transition_length = 2) +
enter_fade()
```
f. An transition_layers example with previous layers NOT retained (and exit_ updated) - here, height by planet (Tatooine or Naboo) ignoring all other variables
```{r, warning = FALSE}
sw_planets <- starwars %>%
filter(homeworld == "Tatooine" | homeworld == "Naboo")
ggplot(sw_planets, aes(x = homeworld, y = height)) +
geom_boxplot(aes(fill = homeworld)) +
geom_jitter(aes(color = homeworld), width = 0.1) +
geom_violin(aes(color = homeworld, fill = homeworld)) +
theme_bw() +
transition_layers(layer_length = 1, transition_length = 2, keep_layers = FALSE) +
enter_fade() +
exit_fade()
```
###3. Abalone + ridge plot + transition_states (Joy Division meets action figures)
**Data:** Accessed from UCI Machine Learning Repository (<https://archive.ics.uci.edu/ml/datasets/abalone>)
Warwick J Nash, Tracy L Sellers, Simon R Talbot, Andrew J Cawthorn and Wes B Ford (1994), "The Population Biology of Abalone (Haliotis species) in Tasmania. I. Blacklip Abalone (H. rubra) from the North Coast and Islands of Bass Strait", Sea Fisheries Division, Technical Report No. 48 (ISSN 1034-3288)
**Relevant info: **
- sex = M (Male), F (Female), I (Infant/Indeterminate)
- length_mm = longest shell dimension (mm)
- age = estimated age (years), calculated by # rings + 1.5
Animated abalone ridge plot with density plots separated by sex:
```{r, warning = FALSE, message = FALSE}
abalone <- read_csv("abalone.csv") %>%
filter(sex == "M" | sex == "F" | sex == "I") %>%
filter(age_years > 4 & age_years < 25) %>%
mutate(sex = fct_relevel(as.factor(sex), "I","F","M"))
ab_graph <- ggplot(abalone, aes(x = length_mm, y = age_years, fill = sex)) +
geom_density_ridges(alpha = 0.5, color = "white") +
scale_fill_manual(values = c("purple","blue","cyan")) +
theme_minimal() +
labs(x = "Shell Length (mm)", y = "Abalone Age (years)") +
transition_states(age_years, transition_length = 1, state_length = 1) +
shadow_mark()
ab_graph
# animate(ab_graph, nframes = 100, renderer = gifski_renderer("ab_graph.gif"))
```
### A few more random examples
```{r, warning = FALSE}
ggplot(abalone, aes(x = length_mm, y = diameter_mm)) +
geom_point(aes(color = age_years, size = height_mm)) +
labs(title = "Abalone age: {closest_state} years", x = "Length (") +
theme_dark()+
scale_color_gradientn(colors = c("magenta","orange","yellow","white")) +
transition_states(age_years, transition_length = 1, state_length = 2) +
enter_fade()+
exit_fade() +
shadow_mark()
```
And another abalone example...
```{r, warning = FALSE}
# Another one:
ggplot(abalone, aes(x = age_years, y = diameter_mm)) +
geom_point(aes(size = length_mm, color = diameter_mm)) +
scale_color_gradient(low = "magenta", high = "yellow") +
theme_dark()+
transition_states(age_years, transition_length = 2, state_length = 3) +
shadow_mark() +
enter_fade() +
ease_aes('back-in')
```
The following examples use dataset 'ChickWeight' in base R. Use ?ChickWeight for more information.
```{r, warning = FALSE}
# Animated column plot:
ggplot(ChickWeight, aes(x = Chick, y = weight)) +
geom_col(aes(fill = Diet)) +
labs(title = "Age (days): {closest_state}") +
scale_fill_manual(values = c("yellow","orange","coral","magenta")) +
scale_y_continuous(expand = c(0,0)) +
theme_dark() +
transition_states(Time, transition_length = 3, state_length = 1)
```
```{r, warning = FALSE}
# Find mean weight by time for each feed type
mean_wt <- ChickWeight %>%
group_by(Diet, Time) %>%
summarize(
mean_wt = mean(weight)
)
# Animated line plot
ggplot(mean_wt, aes(x = Time, y = mean_wt, label = Diet)) +
geom_line(aes(color = Diet)) +
geom_text(nudge_x = 0.2, nudge_y = 5) +
theme_light() +
scale_color_manual(values = c("dodgerblue","green3","purple","orange")) +
transition_reveal(Diet, Time)
```