Search code examples
rshinyplotlyshinydashboard

Filter Plotly Bar Chart with dropdown box selection


I have a static bar chart in Plotly, however the data that I am pulling in is a lot bigger than I realised and there is too much for the chart to show anything meaningful. In the UI I have a dropdown box with a selection of US States and I'd like to be able to filter the bar chart based on the users dropdown box selection. Is there a simple way of filtering the DF?

 output$County_Chart <- renderPlotly({

    validate(
      need(County_data(),""))

    ct_Plot_Data <- County_data()

    Bar <- plot_ly(ct_Plot_Data, x = ct_Plot_Data$Value, y = ct_Plot_Data[,c("COUNTY")], type = 'bar',
                   name = 'Value', marker = list(color = 'rgb((49,130,189)', orientation = 'h')) %>% 
      layout(
        yaxis = list(title = "",
                     categoryorder = "array",
                     categoryarray = ~COUNTY)
      ) %>%
      add_trace(x = ct_Plot_Data$Population, name = 'Population', marker = list(color = 'rgb(204, 204, 204)'))

    Bar

  })

Thanks in advance


Solution

  • As you haven't provided any example data, please check the following example:

    library(shiny)
    library(plotly)
    library(datasets)
    
    DF <- as.data.frame(state.x77)
    
    ui <- fluidPage(
      selectizeInput("vars", "Select variables", names(DF), multiple = TRUE, options = list('plugins' = list('remove_button'))),
      selectizeInput("states", "Select states", rownames(DF), multiple = TRUE, options = list('plugins' = list('remove_button'))),
      plotlyOutput("Bar")
    )
    
    server <- function(input, output, session) {
    
      filteredDF <- reactive({
        req(input$states, input$vars)
        cbind(stack(DF[input$states, ], select = input$vars), states = rownames(DF[input$states,]))
      })
    
      output$Bar <- renderPlotly({
        req(filteredDF())
        p <- plot_ly(filteredDF(), x=~ind, y= ~values, type = "bar", color = ~states)
        p
      })
    
    }
    
    shinyApp(ui, server)