闪亮的仪表板 - 具有来自复选框的值的反应式条形图

Shiny dashboard - reactive bar plot with values from checkbox

根据我的数据,我可以准备一个简单的闪避条形图

geo <- data.frame("year" = c(2018, 2018, 2018, 2019, 2019, 2019, 2020, 2020, 2020), 
                   "geo" = c("Europe", "Asia", "America", "Europe", "Asia", "America", "Europe", "Asia", "America"), 
                   "sales" = c(100, 150, 200, 500, 500, 500, 1200, 1800, 1200)) 

ggplot(geo, aes(fill=as.factor(year), x=geo, y=sales))+
   geom_bar(position="dodge", stat = "identity")

我想把这个图和 select 年的复选框一起放在 Shiny 仪表板中。我愿意

library(shiny)
ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    # Boxes need to be put in a row (or column)
    fluidRow(
     
      box(plotOutput("plot1", height = 250)),
      
      box(
       
        checkboxGroupInput("checkGroup", label = "Year",                          
                           choices = list("2018"=2018, "2019" = 2019, "2020" = 2020),
                           selected = 2018)
      )
    )
  )
)

server <- function(input, output) {

  output$plot1 <- renderPlot({
    ggplot(geo, aes(fill=as.factor(input$checkGroup), x=geo, y=sales))+
      geom_bar(position="dodge", stat = "identity")
    
  })
}

shinyApp(ui, server)

我遇到两种类型的错误:

  1. 图上的值不会根据复选框发生变化 selection - 每年的图都相同(并且值是错误的)
  2. 我无法生成超过一年的情节 selected。我收到以下错误:“错误:美学必须是长度 1 或与数据 (9) 相同:填充”

有人可以帮忙吗?

这可以这样实现:

  1. 您必须根据选中的年份过滤数据集。为此使用 reactive.
  2. 在 renderPlot 中,使用反应式返回的数据帧进行绘图,并简单地将 year 映射到 fill


    library(shiny)
    library(shinydashboard)
    
    geo <- data.frame("year" = c(2018, 2018, 2018, 2019, 2019, 2019, 2020, 2020, 2020), 
                      "geo" = c("Europe", "Asia", "America", "Europe", "Asia", "America", "Europe", "Asia", "America"), 
                      "sales" = c(100, 150, 200, 500, 500, 500, 1200, 1800, 1200)) 
    
    ui <- dashboardPage(
      dashboardHeader(title = "Basic dashboard"),
      dashboardSidebar(),
      dashboardBody(
        # Boxes need to be put in a row (or column)
        fluidRow(
          
          box(plotOutput("plot1", height = 250)),
          
          box(
            
            checkboxGroupInput("checkGroup", label = "Year",                          
                               choices = list("2018"=2018, "2019" = 2019, "2020" = 2020),
                               selected = 2018)
          )
        )
      )
    )
    
    server <- function(input, output) {
      
      dat <- reactive({
        filter(geo, year %in% input$checkGroup)
      })
      
      output$plot1 <- renderPlot({
        ggplot(dat(), aes(fill=as.factor(year), x=geo, y=sales))+
          geom_bar(position="dodge", stat = "identity")
        
      })
    }
    
    shinyApp(ui, server)