rshinydygraphsshiny-reactivity

plot dygraph from a list in shiny


I wish to plot xts from a list of xts series by selecting the name of each list. I am not understunding how reactivity and list selection works

library(zoo)
library(dygraphs)
library(xts)

d <- seq(as.Date("2020/01/01"), as.Date("2020/05/01"), "months")
xts1 <- xts(rnorm(5),order.by = d)
xts2 <- xts(rnorm(5),order.by = d)
xts3 <- xts(rnorm(5),order.by = d)
l <- list(xts1,xts2,xts3)
names(l) <- c("uno","dos","tres")

Creation of list of xts objects


library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Old Faithful Geyser Data"),

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(
            selectInput(names,names,names(l))
        ),

        # Show a plot of the generated distribution
        mainPanel(
            dygraphOutput("plot")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
      
    #option 1 
        p <- reactive({
        input$names
    })
   output$plot <- renderDygraph({
        l[[p]]
})

# option 2

    output$plot <- renderDygraph({
        l[[input$names]]
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

It doesn´t work neither ways. Appreciate :)


Solution

  • Four things are wrong in your code:

    Therefore, your corrected code is:

    library(zoo)
    library(dygraphs)
    library(xts)
    library(shiny)
    
    d <- seq(as.Date("2020/01/01"), as.Date("2020/05/01"), "months")
    xts1 <- xts(rnorm(5),order.by = d)
    xts2 <- xts(rnorm(5),order.by = d)
    xts3 <- xts(rnorm(5),order.by = d)
    l <- list(xts1,xts2,xts3)
    names(l) <- c("uno","dos","tres")
    
    
    # Define UI for application that draws a histogram
    ui <- fluidPage(
      
      # Application title
      titlePanel("Old Faithful Geyser Data"),
      
      # Sidebar with a slider input for number of bins 
      sidebarLayout(
        sidebarPanel(
          selectInput("names", "names", names(l))
        ),
        
        # Show a plot of the generated distribution
        mainPanel(
          dygraphOutput("plot1"),
          dygraphOutput("plot2")
        )
      )
    )
    
    # Define server logic required to draw a histogram
    server <- function(input, output) {
      
      p <- reactive({
        input$names
      })
      output$plot1 <- renderDygraph({
        dygraph(l[[p()]])
      })
    
      output$plot2 <- renderDygraph({
        dygraph(l[[input$names]])
      })
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)