Last active
March 23, 2018 13:33
-
-
Save Torvaney/3b542591272db5979b6c2002e8e01a3e to your computer and use it in GitHub Desktop.
tidyverse-friendly (& hopefully more readable) version of the tweenr example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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