首页 > 解决方案 > 多次在绘图之间切换

问题描述

我正在创建一个闪亮的应用程序,用户可以通过单击单选按钮在不同的绘图之间切换。我在this question中遵循了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)

标签: rshinyreactive

解决方案


似乎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)

推荐阅读