使用下拉框选择过滤条形图

时间:2019-10-22 16:21:23

标签: r shiny plotly shinydashboard

我在Plotly中有一个静态条形图,但是要提取的数据比我想象的要大得多,图表无法显示任何有意义的信息。在用户界面中,我有一个带有选择美国状态的下拉框,我希望能够根据用户下拉框的选择来过滤条形图。有没有一种简单的方法来过滤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

  })

预先感谢

1 个答案:

答案 0 :(得分:1)

由于您未提供任何示例数据,请检查以下示例:

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)