繁体   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