Search code examples
rdataframeanimationplotly

Redefine labels to animation slider in plot_ly


I'm trying to set the labels for the animation slider using plot_ly() in R. Here's a minimal example:

library(dplyr)
library(plotly)

dat <- tibble(x = rep(seq(1,5), 2), f = rep(c(1, 2), each = 5))
dat <- dat %>% mutate(y = x^f)


steps <- list(
  list(label = "a", method = "restyle"),
  list(label = "b", method = "restyle")
)

plot_ly() %>%
  add_trace(x = dat$x,
            y = dat$y,
            name = "Tæthed",
            frame = dat$f,
            type = "scatter",
            mode = "lines") %>%
  animation_opts(frame = 0) %>%
  animation_slider(steps = steps)

From what I could gather, the steps option in animation_slider() needs a list of lists, one for each value of the slider. I am misspecifying it somehow because the labels aren't "a" and "b" but 1 and 2. What am I doing wrong?


Solution

  • What you are trying to do works with sliders (part of layout): https://plotly.com/r/sliders/

    But there is no step argument for animations: https://plotly.com/r/animations/

    We can modify the dataframe beforehand to show the right frame name:

    dat %>% 
      mutate(fr = letters[f]) %>% 
    plot_ly() %>%
      add_trace(x = ~x,
                y = ~y,
                name = "Tæthed",
                frame = ~fr,
                type = "scatter",
                mode = "lines") %>%
      animation_opts(frame = 0) %>%
      animation_slider()