Skip to content

Instantly share code, notes, and snippets.

@Torvaney
Last active March 23, 2018 13:33
Show Gist options
  • Select an option

  • Save Torvaney/3b542591272db5979b6c2002e8e01a3e to your computer and use it in GitHub Desktop.

Select an option

Save Torvaney/3b542591272db5979b6c2002e8e01a3e to your computer and use it in GitHub Desktop.
tidyverse-friendly (& hopefully more readable) version of the tweenr example
library(tidyverse)
library(gganimate)
library(ggforce)
library(tweenr)
# Making up data
n_balls <- 20
d <- tibble(x = rnorm(n_balls),
y = rnorm(n_balls),
time = sample(100, n_balls),
alpha = 0,
size = 10,
ease = "elastic-out",
id = 1:n_balls) %>%
list()
d[[2]] <- d[[1]] %>%
mutate(time = time + 10,
alpha = 1,
size = 1,
ease = "linear")
d[[3]] <- d[[2]] %>%
mutate(time = time + sample(50:100, n_balls),
size = 3,
ease = "bounce-out")
d[[4]] <- d[[3]] %>%
mutate(time = time + 10,
y = min(y) - 0.5,
size = 3,
ease = "bounce-out")
d[[5]] <- d[[4]] %>%
mutate(time = max(time))
df <- reduce(d, bind_rows)
# Using tweenr
dt <- tween_elements(df, 'time', 'id', 'ease', nframes = 500)
# Animate with gganimate
p <- ggplot(data = dt) +
geom_point(aes(x=x, y=y, size=size, alpha=alpha, frame = .frame)) +
scale_size(range = c(0.1, 20), guide = 'none') +
scale_alpha(range = c(0, 1), guide = 'none') +
ggforce::theme_no_axes()
animation::ani.options(interval = 1/24)
gganimate(p, 'dropping balls.gif', title_frame = F)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment