Skip to content

Instantly share code, notes, and snippets.

@cpsievert
Created February 9, 2018 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpsievert/8aceb01f22d02ec8ef54f818e150b58c to your computer and use it in GitHub Desktop.
Save cpsievert/8aceb01f22d02ec8ef54f818e150b58c to your computer and use it in GitHub Desktop.
Cumulative animation where last frame is shown first
accumulate_by <- function(dat, var, showLastFirst = FALSE) {
var <- lazyeval::f_eval(var, dat)
lvls <- plotly:::getLevels(var)
dats <- lapply(seq_along(lvls), function(x) {
cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]])
})
if (showLastFirst) {
lastFrame <- dats[[length(dats)]]
# you will likely have to fiddle with this value
lastFrame$frame <- 0
dats <- c(list(lastFrame), dats)
}
dplyr::bind_rows(dats)
}
df <- data.frame(
x = c(1,2,3),
y = c(1,2,3),
f = c(1,2,3)
)
p <- df %>%
accumulate_by(~f, TRUE) %>%
plot_ly(
x = ~x,
y = ~y,
frame = ~frame,
type = 'scatter',
mode = 'markers',
showlegend = F
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment