Search code examples
shinyshinydashboarddygraphs

shiny: add/remove time-series to dygraphs upon input values


I'm building a shiny app that would display in dygraphs a basic dataset and then offer an option to add new time series upon selecting the checkbox input. However, as I coded it now, I'm 'stuck' at the original dataset and unable to add/remove new content. Any hints how to solve this are very welcome, thanks.

library(shinydashboard)
library(dygraphs)
library(dplyr)


ui <-dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    useShinyjs(),
    checkboxGroupInput(inputId = 'options',
                       label = 'Choose your plot(s)',
                       choices = list("mdeaths" = 1,
                                      "ldeaths" = 2)
    ),

    uiOutput("Ui1")
  )
)

server <- function(input, output, session) {

  output$Ui1 <- renderUI({


    output$plot1 <- renderDygraph({

      final_ts <- ldeaths
      p <- dygraph(final_ts, main = 'Main plot') %>% 
        dygraphs::dyRangeSelector()

      if(1 %in% input$options) {

        final_ts <- cbind(final_ts, mdeaths)
        p <- p %>% 
          dySeries('mdeaths', 'Male Deaths')

      } else if(2 %in% input$options) {

        final_ts <- cbind(final_ts, fdeaths)
        p <- p %>% 
          dySeries('fdeaths', 'Female Deaths')

      } 

      p

    })

    dygraphOutput('plot1')
  })


}

shinyApp(ui, server)

Solution

  • I'd suggest to dynamically filter the data based on the user selection instead of dynamically adding/removing traces from the plot:

    library(shinydashboard)
    library(shinyjs)
    library(dygraphs)
    library(dplyr)
    
    lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)
    
    ui <- dashboardPage(
      dashboardHeader(),
      dashboardSidebar(),
      dashboardBody(
        useShinyjs(),
        selectizeInput(
          inputId = "options",
          label = "Choose your trace(s)",
          choices = colnames(lungDeaths),
          selected = colnames(lungDeaths)[1],
          multiple = TRUE,
          options = list('plugins' = list('remove_button'))
        ),
        uiOutput("Ui1")
      )
    )
    
    server <- function(input, output, session) {
      output$Ui1 <- renderUI({
        filteredLungDeaths <- reactive({
          lungDeaths[, input$options]
        })
    
        output$plot1 <- renderDygraph({
    
          p <- dygraph(filteredLungDeaths(), main = 'Main plot') %>%
            dygraphs::dyRangeSelector()
    
          if('mdeaths' %in% colnames(filteredLungDeaths())){
            p <- dySeries(p, 'mdeaths', 'Male Deaths')
          }
    
          if('fdeaths' %in% colnames(filteredLungDeaths())){
            p <- dySeries(p, 'fdeaths', 'Female Deaths')
          }
    
          p
    
        })
    
        dygraphOutput('plot1')
      })
    }
    
    shinyApp(ui, server)