使用 Crosstalk 和 plotly 管理多个时间序列

Managing multiple Times Series with Crosstalk and plotly

我正在尝试使用带有串扰的 plotly 来显示多个时间序列的动态图。根据是否选中复选框,我希望时间序列显示在图表上。 在下面的代码中,我在同一数据帧 (df_final) 中创建了两个时间序列 1 和 2。 到目前为止我有两个问题:

我不知道如何改进以上任何一个,有什么想法吗?

此外,我不确定我是否使用了正确的工具(串扰等)。欢迎任何其他建议。

library(plotly)
library(crosstalk)

#Create two identical dataframe
df_1 <- economics
df_2 <- economics

#Add a key to each dataframe to dissociate the two time series
df_1$ts <- 1
df_2$ts <- 2

#Modify the first dataframe
df_2$psavert <- economics$psavert + 1

df_final <- rbind(df_1, df_2)

shared_df_final <- SharedData$new(df_final)

bscols(
       list(filter_checkbox("Time series", "Time series", shared_df_final, ~ts, inline = TRUE)),
       plot_ly(data = shared_df_final, x = ~date, height = 700) %>%
         add_lines(y = ~df_final$psavert, line = list(color = "#00526d", width = 1),
                   hoverinfo = "text", text = "ts")
)

您是否正在寻找类似的东西:

plot_ly() %>%
  add_lines(data = df_1, x= ~date, y = ~psavert, name = "First") %>%
  add_lines(data = df_2, x= ~date, y = ~psavert, name = "Second") %>%
  layout(
    updatemenus = list(
      list(
        y = 0.8,
        type= 'buttons',
        buttons = list(
          list(method = "restyle",
               args = list("visible", list(TRUE, TRUE)),
               label = "Both"),
          list(method = "restyle",
               args = list("visible", list(TRUE, FALSE)),
               label = "First"),

          list(method = "restyle",
               args = list("visible", list(FALSE, TRUE)),
               label = "Second")))
    )
  )