Skip to content

Instantly share code, notes, and snippets.

@Torvaney
Created April 22, 2018 09:22
Show Gist options
  • Save Torvaney/cea9466c937442600890e5454b728fd5 to your computer and use it in GitHub Desktop.
Save Torvaney/cea9466c937442600890e5454b728fd5 to your computer and use it in GitHub Desktop.
Animated shot counts of the Premier League with tweenr and gganimate
library(tidyverse)
shot_counts <- read_csv(here::here("data/shot_counts.csv"))
# Interpolate points
shot_counts_tween <- shot_counts %>%
filter(season < 2018) %>%
group_by(season) %>%
arrange(desc(count)) %>%
mutate(rank = row_number()) %>%
ungroup() %>%
select(season, rank, count) %>%
split(.$season) %>%
tweenr::tween_states(tweenlength = 1, statelength = 3, ease = 'linear', nframes = 240) %>%
mutate(season_label = str_glue("{floor(season) - 1}/{floor(season)}")) %>%
as_tibble()
# Create the plot
p <- shot_counts_tween %>%
ggplot(aes(frame = .frame)) +
geom_point(aes(x = rank, y = count)) +
# Hack the season label into the plot...
geom_label(data = shot_counts_tween %>% distinct(season_label, .frame),
aes(label = season_label),
x = 17, y = 900) +
scale_x_continuous(breaks = 1:20) +
scale_y_continuous(limits = c(300, 900)) +
theme_minimal() +
theme(panel.grid.minor.x = element_blank(),
panel.grid.major.x = element_line(linetype = "dotted"),
panel.grid.minor.y = element_blank(),
panel.grid.major.y = element_blank()) +
labs(x = "Rank",
y = "# of Shots",
title = "Premier League")
# Compose plot into animated gif
gganimate::gganimate(p, filename = here::here("figs/shot_counts.gif"),
title_frame = FALSE, interval = 0.001,
ani.width = 600, ani.height = 400)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment