Plotly and Shiny Dashboard- use daterangeinput to change range on date axis in a plotly graph

2.3k Views Asked by At

I made a Plotly graph in R with lines and scatters and filled area variables. The X axis is dates and times formatted in as.POSIXCT with the format = "%Y-%m-%d %H:%M:%S". There's 2 months of data in 10 minute intervals. The Y axis is number of units.

I'm integrating the graph into a Shiny Dashboard. I'd like to use the daterangeInput to choose the date range for the X axis. I can't figure out how to integrate the daterangeInput to be reactive/interactive, though.

Any help would be appreciated!

The Plotly graph, consolidated:

graph <- plot_ly(master, x = date, y = arrival.one, name = 'One Arrival',    visible = "legendonly") %>%
add_trace(x= date, y = arrival.two, name = 'Two Arrival', mode = 'lines', visible = "legendonly" ) %>%
layout( xaxis = list(title= "Date and Time",
      rangeslider = list (type = "date"))) 

The UI:

ui <- dashboardPage(skin="black",
                dashboardHeader(title = "Rack Filling"),
                dashboardSidebar(sidebarMenu(
                  menuItem("Dashboard", tabName = "dashboard", icon =     icon("line-chart")),
                  menuItem("Staffing", tabName = "staffing", icon = icon("male")),
                  dateRangeInput("inDateRange", "Date range input:")
                )),

The Server:

server <- function(input, output) {  
output$graph <- renderPlotly({graph               
})
output$event <- renderPrint({
??????????
1

There are 1 best solutions below

2
On BEST ANSWER

In your server function, you have to create a reactive that filters the dataset every time the DateRange is changed. You call that reactive to draw your plot :

server <- function(input, output) {  
    reactiveMaster <- reactive({
        master %>% filter(date>=input$inDateRange[1] & date<input$inDateRange[2])
        })

    output$graph <- renderPlotly({
        plot_ly(reactiveMaster(), x = date, y = arrival.one, name = 'One Arrival',  visible = "legendonly") %>%
            add_trace(x= date, y = arrival.two, name = 'Two Arrival', mode = 'lines', visible = "legendonly" ) %>%
            layout( xaxis = list(title= "Date and Time",
                    rangeslider = list (type = "date"))) 
        })
}