Last active
October 21, 2020 18:49
-
-
Save yjunechoe/2b3c03a1659f1635d9020feeca36fe5e to your computer and use it in GitHub Desktop.
To be used with transition_reveal() when you have your own column for reveal time
This file contains 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(rlang) | |
split_track <- function(df, grouping_var, tracked_along, ..., tracked_groups = ".all") { | |
region <- df %>% | |
filter(...) %>% | |
group_by({{ grouping_var }}) %>% | |
mutate(row_id = 1:n()) %>% | |
ungroup() %>% | |
select(row_id, {{ grouping_var }}, {{ tracked_along }}) | |
region_wide <- region %>% | |
pivot_wider(names_from = {{ grouping_var }}, values_from = {{ tracked_along }}) %>% | |
select(-row_id) | |
if (tracked_groups == ".all") { | |
tracked_groups <- names(region_wide) | |
untracked <- NULL | |
} else { | |
untracked <- region_wide %>% | |
select(-{{ tracked_groups }}) | |
} | |
grouping_var_enquo <- enquo(grouping_var) | |
tracked_along_enquo <- enquo(tracked_along) | |
region_split <<- bind_rows( | |
untracked, | |
map_dfr(tracked_groups, ~select(region_wide, .x)) | |
) %>% | |
fill(everything(), .direction = "down") %>% | |
mutate(across( | |
everything(), | |
~ifelse(is.na(.x), min(pull(region, {{ tracked_along }}), na.rm = TRUE) - 1, .x)) | |
) %>% | |
pivot_longer( | |
everything(), | |
names_to = quo_text(grouping_var_enquo), | |
values_to = quo_text(tracked_along_enquo) | |
) | |
df %>% | |
anti_join(filter(df, ...)) %>% | |
bind_rows( | |
region_split %>% | |
inner_join(df) | |
) %>% | |
group_by({{ grouping_var }}) %>% | |
mutate(!!tracked_along_enquo := row_number()) %>% | |
ungroup() | |
} | |
################### | |
## Generate Plot ## | |
################### | |
set.seed(123) | |
plot_df <- tibble( | |
a = cumsum(runif(100, -1, 1)), | |
b = cumsum(runif(100, -1.5, 1.5)), | |
c = cumsum(runif(100, -2, 2)), | |
d = cumsum(runif(100, -2.5, 2.5)) | |
) %>% pivot_longer(a:d) %>% | |
group_by(name) %>% | |
mutate(reveal_time = row_number(), x = row_number()) %>% | |
ungroup() | |
anim <- plot_df %>% | |
split_track(grouping_var = name, tracked_along = reveal_time, x > 74) %>% | |
ggplot(aes(x, value, color = name)) + | |
geom_line(size = 1) + | |
transition_reveal(reveal_time) + | |
theme_classic() | |
animate(anim, width = 5, height = 3, units = "in", res = 150) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment