簡體   English   中英

Shiny 儀表板 - 反應欄 plot 與復選框中的值

[英]Shiny dashboard - reactive bar plot with values from checkbox

根據我的數據,我可以准備一個簡單的閃避條 plot

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")

我想把這個 plot 放在 Shiny 儀表板中,連同一個復選框到 select 年。 我願意

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. plot 上的值不會根據復選框選擇而改變 - plot 每年都相同(並且值是錯誤的)
  2. 如果選擇了一年以上,我無法生成 plot。 我收到以下錯誤:“錯誤:美學必須是長度 1 或與數據 (9) 相同:填充”

任何人都可以幫忙嗎?

這可以像這樣實現:

  1. 您必須根據檢查的年份過濾數據集。 為此,請使用reactive .
  2. 在 renderPlot 中,使用響應式返回的數據框進行繪圖,只需 map fill year


    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)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM