【问题标题】:Rshiny: I want to allow users to select 3 graphsRshiny:我想让用户选择 3 个图表
【发布时间】:2021-10-04 13:15:49
【问题描述】:

在我的服务器函数中,我有一段代码旨在让用户看到三个图表之一。

x = reactive({
    
    if (input$Option == "By rating"){
      output$Movies = renderPlot({ggplot(data(),aes(`Rate`,`Gross Worldwide`, colour=Company)) +geom_point(size = 2,alpha = 0.6) +
          theme_bw()+geom_text(aes(label=`Original Title`),hjust=0, vjust=0)})
    }
    else if (input$Option == "By Opening Weekend (USA)"){
      output$Movies = renderPlot({ggplot(data(),aes(`Opening Weekend USA`,`Gross Worldwide`, colour=Company))+geom_point(size = 2,alpha = 0.6) +
          theme_bw()+geom_text(aes(label=`Original Title`),hjust=0, vjust=0)})
    }
    else if (input$Option == "By Budget"){
      output$Movies = renderPlot({ggplot(data(),aes(`Budget`,`Gross Worldwide`, colour=Company))+geom_point(size = 2,alpha = 0.6) +
          theme_bw()+geom_text(aes(label=`Original Title`),hjust=0, vjust=0)})
    }
  })
  
 output$Movies = renderPlot(x())

在我的 ui 函数中,我制作了一个选择器,允许他们选择他们希望使用的不同选项。

sidebarPanel(
    selectInput("Option", "Options:", 
                choices=c("By rating", "By Opening Weekend (USA)", "By Budget")),

我遇到的问题是,虽然这段代码名义上有效,但如果我要实际运行它,三种排序方法的选择器在工作时实际上并没有改变图形。这可能是什么问题?

【问题讨论】:

    标签: r plot rshiny


    【解决方案1】:

    我认为问题在于您在响应式中使用了 renderPlot,然后在 Output$Movies 中再次使用了 renderPlot。因此,您说要 renderPlot 两次。我如何让它为我工作只是从反应中删除 Output$Movies == renderPlot,只保留 renderPlot 作为单独的函数。由于我没有你的数据,所以我对其进行了一些修改,并使用 mtcars 展示了一个简单的工作示例,说明如何使用响应式:

        library(shiny)
        library(ggplot2)
        
        ui <- fluidPage(
          selectInput("Option", "Options:", 
                      choices=c("By rating", "By Opening Weekend (USA)", "By Budget")),
          plotOutput("Movies")
        )
        
        server <- function(input, output, session) {
          
          x = reactive({
            
            if (input$Option == "By rating"){
              ggplot(mtcars,aes(mpg,cyl, colour=gear)) +geom_point(size = 2,alpha = 0.6)
            }
            else if (input$Option == "By Opening Weekend (USA)"){
              ggplot(mtcars,aes(mpg,disp, colour=vs)) +geom_point(size = 2,alpha = 0.6)
            }
            else if (input$Option == "By Budget"){
              ggplot(mtcars,aes(mpg,drat, colour=hp)) +geom_point(size = 2,alpha = 0.6)
            }
          })
          
          output$Movies = renderPlot(x())
          
          
        }
        
        shinyApp(ui, server)
    

    希望这就是您想要的!

    【讨论】:

    • 非常感谢。这解决了我的问题!
    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多