Search code examples
shiny-servershiny

How to determine which plot is shown reactively


Here are two plots I want to show in the APP. In ui.r, I have one input(plot type) and one output(plot).

plot type input:

sidebarPanel(
             checkboxGroupInput("vo", 
                                label = "Visualization Object", 
                                choices = list("Polar Distance of VAR from nadir" = 1, 
                                               "Real Value of VAR" = 2 
                                ),
                                selected = c(1,2)
             )
           )

and the plot output:

fluidRow(
           column(6,
                  plotOutput(outputId="polar", width = "600px", height = "600px")
           ),
           column(6,
                  plotOutput(outputId="paral", width = "600px", height = "600px")
           )
         )

In server.r, I use this:

if(1%in%vo){
  output$polar <- renderPlot({
    # input$reset

    ap(whole_p[[ts$counter]])
  })}
  if(2%in%vo){
  output$paral <- renderPlot({
    # input$reset

    av(whole_v[[ts$counter2]])
  })}

So how can I change the server code to make it work as: when I select Polar Distance of VAR from nadir, then only plot output$polar is shown in the ui, and when select Real Value of VAR, only plot output$paral is shown in the ui. Thanks.


Solution

  • Here is a working solution based on conditionalPanel

    library(shiny)
    
    ui <- shinyUI(fluidPage(
    
       titlePanel("Old Faithful Geyser Data"),
    
       sidebarLayout(
          sidebarPanel(
            checkboxGroupInput("vo", 
                               label = "Visualization Object", 
                               choices = list("Polar Distance of VAR from nadir" = 1, 
                                              "Real Value of VAR" = 2 
                               ),
                               selected = c(1,2)
            )
          ),
    
          mainPanel(
            conditionalPanel(condition = "input.vo.indexOf('1') >= 0", plotOutput(outputId="polar", width = "600px", height = "600px")),
            conditionalPanel(condition = "input.vo.indexOf('2') >= 0", plotOutput(outputId="paral", width = "600px", height = "600px"))
          )
       )
    ))
    
    server <- shinyServer(function(input, output) {
    
        output$polar <- renderPlot({
          plot(mtcars$mpg, mtcars$cyl)
        })
        output$paral <- renderPlot({
          plot(mtcars$disp, mtcars$hp)
        })
    })
    
    shinyApp(ui = ui, server = server)