首页 文章

根据单选按钮选择R Shiny创建绘图

提问于
浏览
5

我正在尝试创建一个 Shiny 应用程序 . 用户界面 UI.R 看起来很好,但我遇到了 server.R 的问题 . 基本上我想要一个不同的绘图输出,具体取决于用户选择的 radio 选项 .

用户可以选择选项 ABC . 我想绘制直方图,如果用户选择选项 A ,条形图为 B ,饼图为选项 C ,但我不知道如何编码条件?这是一个 if-else 声明吗?我've been struggling for hours! Here'是我的代码示例:

output$plots <- renderPlot({    
   if selection == 'A'
      # plot histogram
   if selection == 'B'
      # plot bar chart
   if selection == 'C'
      # plot pie chart
})

谢谢!

1 回答

  • 14

    您可以使用switch根据选择确定行为:

    library(shiny)
    myData <- runif(100)
    plotType <- function(x, type) {
      switch(type,
             A = hist(x),
             B = barplot(x),
             C = pie(x))
    }
    runApp(list(
      ui = bootstrapPage(
        radioButtons("pType", "Choose plot type:",
                     list("A", "B", "C")),
        plotOutput('plot')
      ),
      server = function(input, output) {
        output$plot <- renderPlot({ 
           plotType(myData, input$pType)
        })
      }
    ))
    

相关问题