Black Lives Matter. Please consider donating to Black Girls Code today.
Dash HoloViews is now available! Check out the docs.

Is it possible to combine plotly cumulative animations in subplot?

I am using plotly in R. I have 2 plotly plots with cumulative animations that work individually. But if I combine them using subplot they don’t work. Is it possible to animate 2 combined plots? Following is a reproducible example:

library(plotly)

accumulate_by <- function(dat, var) {
  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]])
  })
  dplyr::bind_rows(dats)
}

library(MASS)
data(Traffic)


# data 1
Traffic1 <- Traffic %>%
  filter(year==1961) %>% 
  accumulate_by(~day)

# plot1
y_plot <- plot_ly(data = Traffic1,
                  x = ~day,
                  y = ~y,
                  frame = ~frame,
                  type = "scatter") %>%  
animation_slider(
  currentvalue = list(
    prefix = "Day"
  )
)


# data 2
Traffic2 <- Traffic %>%
  filter(year==1962) %>% 
  accumulate_by(~day)

# plot 2
y_plot2 <- plot_ly(data = Traffic2,
                  x = ~day,
                  y = ~y,
                  frame = ~frame,
                  type = "scatter") %>%  
  animation_slider(
    currentvalue = list(
      prefix = "Day"
    )
  )


# combined plot
subplot(y_plot, y_plot2)   

Note:

I have asked this question on stackoverflow as well (no comments/answers so far). Here’s thelink.

Durraniu,
I think what you had would have worked if you just added the “animation_slider” to the subplot. I did autoscale the y axis because it looked like you were not always seeing your data because it was out of view

library(plotly)

accumulate_by <- function(dat, var) {
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]])
})
dplyr::bind_rows(dats)
}

library(MASS)
data(Traffic)

data 1

Traffic1 <- Traffic
Traffic1 <- Traffic[Traffic$year==1961,]
Traffic1 <- accumulate_by(Traffic1, ~day)
Traffic1min <- min(Traffic1$y)
Traffic1max <- max(Traffic1$y)

plot1

y_plot <- plot_ly(data = Traffic1,
x = ~day,
y = ~y,
frame = ~frame,
type = “scatter”)%>%
layout(yaxis = list(range = c(Traffic1min, Traffic1max)))

animation_slider(

currentvalue = list(

prefix = “Day”

# )

data 2

Traffic2 <- Traffic
Traffic2 <- Traffic[Traffic$year==1962,]
Traffic2 <- accumulate_by(Traffic2, ~day)
Traffic2min <- min(Traffic2$y)
Traffic2max <- max(Traffic2$y)

plot 2

y_plot2 <- plot_ly(data = Traffic2,
x = ~day,
y = ~y,
frame = ~frame,
type = “scatter”) %>%
layout(yaxis = list(range = c(Traffic1min, Traffic1max)))

animation_slider(

currentvalue = list(

prefix = “Day”

)

)

combined plot

subplot(y_plot, y_plot2, nrows=2, shareX = TRUE) %>%
animation_slider(
currentvalue = list(
prefix = “Day”
)
)