2

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)
zx8754
  • 52,746
  • 12
  • 114
  • 209
Suzanne
  • 83
  • 9

2 Answers2

1

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.

HeiN3r
  • 178
  • 5
  • You're right, if my plots would have been that simple in reality. I did not mention this in the question, but my plots were reactive to some other input - and in that case this solution does not work. Thank you anyway! – Suzanne Mar 13 '20 at 08:10
  • Alright, thanks for the clarification. Glad you found a solution. – HeiN3r Mar 13 '20 at 08:27
1

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)
bretauv
  • 7,756
  • 2
  • 20
  • 57
  • This solution worked for me, even though my plots were reactive to some other input itself. Thank you! – Suzanne Mar 13 '20 at 08:09