RShiny_Noob
RShiny_Noob

Reputation: 57

Multiple Separate Plots on User select/multi input

I want to visualize plot/s based on user input. I have a dropdown menu and if the user select one or more variables out of the choices given, the code automatically visualize the separate plots for each variable based on the user inputs.

Code: This is how I tried to do it. If there is any other way, please suggest.

library(shiny)
library(shinyjs)

shinyApp(
  ui = fluidPage(
    useShinyjs(), #Necessary to activate shinyjs
    selectInput("select", "Select plot:", 1:4, multiple = TRUE),
    plotOutput("p1"),
    plotOutput("p2"),
    plotOutput("p3"),
    plotOutput("p4")
  ),
  server = function(input, output) {
    output$p1 <- renderPlot({ plot(iris) })
    output$p2 <- renderPlot({ plot(mtcars) })
    output$p3 <- renderPlot({ plot(0) })
    output$p4 <- renderPlot({ plot(1) })
    
    observeEvent(input$select, {
      req(input$select)
      shinyjs::toggle("p1", condition = input$select == 1)
      shinyjs::toggle("p2", condition = input$select == 2)
      shinyjs::toggle("p3", condition = input$select == 3)
      shinyjs::toggle("p4", condition = input$select == 4)
    })
    
  }
)

The problem with this code is that when I select any one input from the dropdown menu, all the other plots for other variables show up too. Plus when all the variables are selected and I try to unselect variable/s from the dropdown menu, they does not hide.

Upvotes: 4

Views: 445

Answers (1)

Waldi
Waldi

Reputation: 41220

As the selection allows multiple choice, you should use %in% instead of ==.
You should also use observe instead of observeEvent to react on NULL input.

library(shiny)
library(shinyjs)

shinyApp(
  ui = fluidPage(
    useShinyjs(), #Necessary to activate shinyjs
    selectizeInput("select", "Select plot:", 1:4, multiple = TRUE),
    plotOutput("p1"),
    plotOutput("p2"),
    plotOutput("p3"),
    plotOutput("p4")
  ),
  server = function(input, output) {
    output$p1 <- renderPlot({ plot(iris) })
    output$p2 <- renderPlot({ plot(mtcars) })
    output$p3 <- renderPlot({ plot(0) })
    output$p4 <- renderPlot({ plot(1) })

    observe({
      shinyjs::toggle("p1", condition = isTRUE(1 %in% input$select))
      shinyjs::toggle("p2", condition = isTRUE(2 %in% input$select))
      shinyjs::toggle("p3", condition = isTRUE(3 %in% input$select))
      shinyjs::toggle("p4", condition = isTRUE(4 %in% input$select))
    })
    
  }
)

Upvotes: 3

Related Questions