Search code examples
javascriptrplotlyggplotly

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


Plotly has this nice function to hide a plot, if you click on its name in the legend. The legend items turns grey and the line only appears again, if we click on the legend item again.

Consider you want to deploy a shiny app, where the user can look at the time series and additionally he can look at the series trend seasonality etc. in the same plot.

I want initially only the series to be displayed in the rendered ggplotly object, when the user opens the app. All other diagnostic plots like Trend (in my reprex) and seasonality should be hidden by default. Only when I click on the legend item Trend (reprex), the trend line should additionally appear.

I know how to do this in shiny, with shiny functions, but I want to be able to solve it with plotly or javascript functionality in the way I mentioned above.

reprex code (try to hide the line "Trend" by default):

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')) 

Solution

  • You can use a style with traces which will be able to hide the Trend line only. You can use the following code:

    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)
    

    Output:

    enter image description here

    As you can see in the image, only series is currently displayed and Trend is hided.