Switch between plots multiple times

Viewed 288

I'm creating a Shiny app where users can switch between different plots, based on a click on a radio button. I followed the suggestion of cmaher in this question, but I found that I can switch only once. The second time gives me a blank output.

Why doesn't shiny render the plot output again when clicking the button? And how to do this?

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)
2 Answers

I can reproduce your problem. At least in your example, there is no need to have the plots as reactives. This should do it:

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

This results in the expected behaviour in my environment. However, it is not clear to me, why the additional reactives() cause this kind of problem. Maybe someone else can explain this.

It appears that switch does not work with reactive expressions but I don't know why. Here's another alternative:

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)
Related