【问题标题】:Switch between plots multiple times多次在绘图之间切换
【发布时间】:2020-06-24 11:45:19
【问题描述】:

我正在创建一个闪亮的应用程序,用户可以通过单击单选按钮在不同的绘图之间切换。我在this问题中按照cmaher的建议,但发现只能切换一次。第二次给了我一个空白输出。

为什么单击按钮时闪亮的绘图输出不再渲染?以及如何做到这一点?

MWE:

server <- shinyServer(function(input, output, session) {
PlotA <- reactive({
    plot(-2:2, -2:2)
  })

PlotB <- reactive({
  plot(-1:1, -1:1)
})

PlotInput <- reactive({
  switch(input$PlotChoice,
         "A" = PlotA(),
         "B" = PlotB())
})

output$SelectedPlot <- renderPlot({ 
  PlotInput()
})

})


ui <-  shinyUI(fluidPage(
  navbarPage(title=" ",
     tabPanel("A",
        sidebarLayout(
           sidebarPanel(
              radioButtons("PlotChoice", "Displayed plot:", 
                            choices = c("A", "B"))),
          mainPanel(plotOutput("SelectedPlot")))))
  ,  fluid=TRUE))

shinyApp(ui=ui, server=server)

【问题讨论】:

    标签: r shiny reactive


    【解决方案1】:

    似乎switch 不适用于反应式表达式,但我不知道为什么。这是另一种选择:

    server <- shinyServer(function(input, output, session) {
    
      your_plot <- reactive({
        if(input$PlotChoice == "A") {
          plot(-2:2, -2:2)
        }
        else if (input$PlotChoice == "B"){
          plot(-1:1, -1:1)
        }
      })
    
      output$SelectedPlot <- renderPlot({ 
        your_plot()
      })
    
    })
    
    
    ui <-  shinyUI(fluidPage(
      navbarPage(title=" ",
                 tabPanel("A",
                          sidebarLayout(
                            sidebarPanel(
                              radioButtons("PlotChoice", "Displayed plot:", 
                                           choices = c("A", "B"))),
                            mainPanel(plotOutput("SelectedPlot")))))
      ,  fluid=TRUE))
    
    shinyApp(ui=ui, server=server)
    

    【讨论】:

    • 这个解决方案对我有用,即使我的图对其他一些输入本身是反应性的。谢谢!
    【解决方案2】:

    我可以重现您的问题。 至少在您的示例中,不需要将图作为反应物。应该这样做:

    PlotInput <- reactive({
      switch(input$PlotChoice,
             "A" = plot(-2:2, -2:2),
             "B" = plot(-1:1, -1:1))
    })
    

    这会在我的环境中产生预期的行为。 但是,我不清楚为什么额外的 reactives() 会导致这种问题。也许其他人可以解释一下。

    【讨论】:

    • 你是对的,如果我的情节在现实中会那么简单。我在问题中没有提到这一点,但我的情节对其他一些输入有反应——在这种情况下,这个解决方案不起作用。还是谢谢你!
    • 好的,感谢您的澄清。很高兴您找到了解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 2020-03-22
    相关资源
    最近更新 更多