首页 > 解决方案 > 基于 R Shiny 仪表板中的单选按钮进行绘图

问题描述

这是我的代码:

ui <- fluidPage(
  radioButtons("dist", "Distribution type:",
               c("Sepal.Length" = "Length",
                 "Sepal.Width" = "Width",
                 "Petal.Length" = "Length")),
  plotOutput("distPlot")
)

server <- function(input, output) {
  output$distPlot <- renderPlot({
    dist <- switch(input$dist,
                   "Length" = plot(iris$Sepal.Length),
                   "Width" = plot(iris$Sepal.Width),
                   "Length" = plot(iris$Sepal.Length))

    plot(dist)
  })
}

shinyApp(ui, server)
}

我究竟做错了什么?

另外,我想par(mfrow=c(1,2))为每个按钮绘制一个图。我怎样才能做到这一点?

有什么帮助吗?

谢谢

标签: rshiny

解决方案


您不需要绘制分配的函数,因为switchit0s 已经这样做了。

server <- function(input, output) {
  output$distPlot <- renderPlot({
  switch(input$dist,
               "Length" = plot(iris$Sepal.Length),
               "Width" = plot(iris$Sepal.Width),
               "Length" = plot(iris$Sepal.Length))
           })
}

编辑:关于使用 par(mfrow=c(1,2))并且尽管我对其他替代方案发表评论,这是我想出的替代方案:

server <- function(input, output) {
  output$distPlot <- renderPlot({
  par(mfrow=c(1,2))
  switch(input$dist,
               "Length" = plot(iris$Sepal.Length),
               "Width" = plot(iris$Sepal.Width),
               "Length" = plot(iris$Sepal.Length))
  switch(input$dist,
               "Length" = plot(iris$Sepal.Length),
               "Width" = plot(iris$Sepal.Width),
               "Length" = plot(iris$Sepal.Length))
       }) 

推荐阅读