Skip to content

Instantly share code, notes, and snippets.

@mikmart
Last active November 23, 2018 11:34
Show Gist options
  • Select an option

  • Save mikmart/139bf936e64fd91cbe38fadf7e38301d to your computer and use it in GitHub Desktop.

Select an option

Save mikmart/139bf936e64fd91cbe38fadf7e38301d to your computer and use it in GitHub Desktop.
Match point and line transitions
library(tidyverse)
library(lubridate)
library(gganimate)
library(ggfortify)
deaths <- fortify(UKDriverDeaths) %>%
rename(date = Index, deaths = Data) %>%
mutate(year = year(date), month = month(date))
p <- ggplot(deaths, aes(month, deaths)) +
geom_point() +
geom_line() +
scale_y_continuous(labels = scales::number) +
scale_x_continuous(breaks = 1:12, labels = month.abb) +
theme(axis.title = element_blank()) +
theme(panel.grid.minor = element_blank()) +
transition_states(year, 1, 2, wrap = FALSE) +
theme(title = element_text(size = 14)) +
labs(title = "UK driver deaths in {closest_state}")
animate(p, fps = 24, duration = 12)
anim_save("uk-driver-deaths.gif")
library(tweenr)
deaths_s <- split(deaths, deaths$year)
f <- function(x, y) {
fps <- 24
dur <- 12
ns <- length(deaths_s)
tt <- 1
st <- 2
dur_s <- dur / ns
tf <- round(fps * dur_s * (tt / (tt + st)), 0)
sf <- round(fps * dur_s * (st / (tt + st)), 0)
keep_state(tween_state(x, y, 'cubic-in-out', tf), sf)
}
deaths_f <- reduce(deaths_s, f)
p2 <- ggplot(deaths_f, aes(month, deaths)) +
geom_point() +
geom_line() +
scale_y_continuous(labels = scales::number) +
scale_x_continuous(breaks = 1:12, labels = month.abb) +
theme(axis.title = element_blank()) +
theme(panel.grid.minor = element_blank()) +
transition_manual(.frame) +
theme(title = element_text(size = 14)) +
labs(title = "UK driver deaths in {current_frame}")
animate(p2, fps = 24, duration = 12)
anim_save("uk-driver-deaths_manual.gif")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment