闪亮错误:尝试从selectInput中选择少于一个元素

时间:2015-10-25 21:03:51

标签: r ggplot2 shiny

如何在Shiny的selectInput调用中添加一个类变量来从ggplot生成条形图?在我的数据集总计中,我想在生成不同的ggplot条形图时选择Class变量进行选择。我得到错误:"尝试选择少于一个元素"。

    totals<-data.frame(Class=c("A","A","A","B","B","B","c","C","D","D","D","D"),
               Type=c("Type1","Type2","Type3","Type1","Type2","Type3","Type1",
                      "Type2","Type1","Type2","Type3","Type4"),
               Acres=c(45,543,434,434,434,455,683,345,567,77,52,86))

server.r代码如下:

    library(shiny)
    library(ggplot2)

    shinyServer(function(input, output, session) {

    output$acresPlot <- reactivePlot(function() {

    acresData <- data.frame(acres = totals$Acres, var = factor(totals[[input$variable]]))

    p <- ggplot(acresData, aes(var, acres)) + 
    geom_bar(stat="identity") 
    print(p)
    })
    })

ui.r代码如下:

    shinyUI(pageWithSidebar(
    headerPanel("My types by class"),

    sidebarPanel(
    selectInput("Class", "Class:",
            c("A" = "A", 
                 "B" = "B", 
                 "C" = "C",
                 "D"="D"))),
    mainPanel(
    plotOutput("acresPlot")
    )
     ))

1 个答案:

答案 0 :(得分:0)

我不完全确定你想要什么,但如果你只想一次选择一个课程,你可以这样做:

library(shiny)
library(ggplot2)

totals<-data.frame(Class=c("A","A","A","B","B","B","c","C","D","D","D","D"),
                   Type=c("Type1","Type2","Type3","Type1","Type2","Type3","Type1",
                          "Type2","Type1","Type2","Type3","Type4"),
                   Acres=c(45,543,434,434,434,455,683,345,567,77,52,86))

server <- shinyServer(function(input, output, session) {

  output$acresPlot <- renderPlot(function() {
    inds <- totals$Class == input$Class
    acresData <- data.frame(acres = totals$Acres[inds], var = totals$Class[inds])

    p <- ggplot(acresData, aes(var, acres)) + 
      geom_bar(stat="identity") 
    print(p)
  })

  output$acresPlot2 <- renderPlot(function() {
    inds <- totals$Class == input$Class
    acresData <- data.frame(acres = totals$Acres, var = totals$Class, col=inds)

    p <- ggplot(acresData, aes(var, acres, fill =col)) + 
      geom_bar(stat="identity") 
    print(p)
  })
})

ui <- shinyUI(pageWithSidebar(
  headerPanel("My types by class"),

  sidebarPanel(
    selectInput("Class", "Class:",
                c("A" = "A", 
                  "B" = "B", 
                  "C" = "C",
                  "D"="D"))),
  mainPanel(
    plotOutput("acresPlot"),
    plotOutput("acresPlot2")
  )
))

shinyApp(ui=ui,server = server)

acresPlot显示所选栏,acresPlot2与所有其他栏一起显示所选栏。