默认情况下,如何在 ggplotly 分组时间序列图中隐藏单行? (情节,R,Javascript)

How to a hide single line in ggplotly grouped time series graph by default? (plotly,R,Javascript)

Plotly 具有隐藏情节的好功能,如果您在图例中单击它的名称。如果我们再次单击图例项,图例项将变为灰色并且线条只会再次出现。

假设您想部署一个闪亮的应用程序,用户可以在其中查看时间序列,此外他还可以在同一图中查看序列趋势季节性等。

当用户打开应用程序时,我最初只想在呈现的 ggplotly 对象中显示系列。默认情况下应隐藏所有其他诊断图,如趋势(在我的代表中)和季节性。只有当我点击图例项 Trend (reprex) 时,趋势线才会额外出现。

我知道如何使用闪亮的功能来完成此操作,但我希望能够按照我上面提到的方式使用 plotly 或 javascript 功能来解决它​​。

reprex 代码(尝试默认隐藏“趋势”行):

library(plotly)
library(lubridate)
library(ggplot2)
set.seed(42)
data <- tibble(id = c(rep("A",24)),
               value = c(cumsum(rnorm(12)), seq( 1, 7, length.out = 12)),
               date = rep(c(ymd("2013-01-01")+ months(0:11)),2),
               label = c(rep("Series",12),rep("Trend", 12))
)
p <- ggplot(data, mapping = aes(x= date, y= value, color = label)) +
            geom_line()  +
            xlab("")
ggplotly(p) %>% layout(legend=list(y = -0.2,
                                   xanchor = 'left',
                                   yanchor = 'bottom',
                                   orientation = 'h')) 

您可以将 styletraces 一起使用,这将只能隐藏 Trend 行。您可以使用以下代码:

library(plotly)
library(lubridate)
library(ggplot2)
set.seed(42)
data <- tibble(id = c(rep("A",24)),
               value = c(cumsum(rnorm(12)), seq( 1, 7, length.out = 12)),
               date = rep(c(ymd("2013-01-01")+ months(0:11)),2),
               label = c(rep("Series",12),rep("Trend", 12))
)
p <- ggplot(data, mapping = aes(x= date, y= value, color = label)) +
  geom_line()  +
  xlab("")

p <- ggplotly(p) %>% layout(legend=list(y = -0.2,
                                   xanchor = 'left',
                                   yanchor = 'bottom',
                                   orientation = 'h')) 

style(ggplotly(p),visible="legendonly", traces = 2)

输出:

如图所示,目前只显示系列,隐藏了趋势。