如何在 plotly 动画中连续向图形添加多条线?

How can I successively add multiple lines to a graph in a plotly animation?

我想使用 R 显示添加到绘图(作为动画)的多条线。例如,我有以下绘图线图 (p, p2, p3):

library(plotly)
set.seed(3)
x = 1:10
y = 1:10
y2 = y^2
y3 = y^3
p = plot_ly(data = data.frame(x = x, y = y), x = ~ x, y = ~y, type = "scatter", mode = "lines")
p2 = plot_ly(data = data.frame(x = x, y = y2), x = ~ x, y = ~y2, type = "scatter", mode = "lines")
p3 = plot_ly(data = data.frame(x = x, y = y3), x = ~ x, y = ~y3, type = "scatter", mode = "lines")

这里 p, p2, p3 是不同的图,但它们都有相同的 x 轴和不同的 y 轴。我希望能够制作一个动画,其中 y, y2, y3 行将连续出现在绘图图中。

P.S:不一定非要使用plotly,但强烈推荐。

一个想法可能是为每一帧创建一个 'dataset'。
第一帧包含 y 的所有值,y2 和 y3 的所有值都位于 y 轴限制之外。对于第二帧,显示了 y 和 y2 的所有值,只有 y3 的值超出了限制。在第 3 帧中包含所有值。

library(tidyverse)
library(plotly)

# transform dataframe into a long format
df <- data.frame(x = 1:10,
                 y = 1:10) %>%
  mutate(y2 = y^2,
         y3 = y^3) %>%
  pivot_longer(cols = -x,
               names_to = "line",
               values_to = "value")

# set the values for each frame and line 
# (all lines not shown, need to hidden outside the plot limits - NA won't work)
df_plot <- map_df(1:3,  ~ mutate(df, frame = .)) %>% 
  mutate(value = case_when(frame == 1 & line %in% c("y2", "y3") ~ -10,
                           frame == 2 & line %in% c("y3") ~ -10,
                           TRUE ~ value))

# create plot
plot_ly(data = df_plot, 
        x = ~x,
        y = ~value,
        color = ~line,
        type = "scatter",
        mode = "line",
        frame = ~frame)  %>%
  layout(yaxis=list(range = c(0, 1000))) %>%
  animation_opts(easing = "bounce")