Home > Software design >  switch graphics with checkboxInput
switch graphics with checkboxInput

Time:06-27

Consider the toy example below. I am trying to display a different graphic when the checkbox is = TRUE but appears to have no effect. I am using 'switch' to display the graphics based on its label. Thanks for any hints on how to display an alternate graphic with a conditional statement(if).

   library(shiny)

    mytest <- c("first","second")
   # Define UI for application that draws a histogram
    ui <- fluidPage(

    # Application title
    titlePanel("Old Faithful Geyser Data"),

        sidebarLayout(
        sidebarPanel(
          selectInput(inputId = "test",
                      label = "Test",
                      choices = mytest,
                      selected = "first"),
          checkboxInput("checkbox","check this box",FALSE)),

        mainPanel(
           plotOutput("distPlot")
        )))

      server <- function(input, output) {

    output$distPlot <- renderPlot({
      switch(input$test,
             "first" = plot(rnorm(100)),
             
             if("checkbox" == FALSE){
             "second" = plot(rnorm(1000),col="blue")
             } else{
       #I want the graphic below to be displayed when the checkbox = TRUE or checked
            "second" = plot(rnorm(10000),col='red')   
             }
      )
})
}

shinyApp(ui = ui, server = server)

CodePudding user response:

If you need the value of the checkbox you have to reference it using input[["checkbox]] or input$checkbox.

I assume you wanted a black coloured block when the dropdown is "first" and a blue/red one (depending on the checkbox) when the dropdown is "second"?

The solution disables the check box when the first item is selected. To do that you can use the functions enabled/disabled from the shinyjs package. For that we have to initialise shinyjs in the ui.

library(shiny)
library(shinyjs)

mytest <- c("first","second")
# Define UI for application that draws a histogram
ui <- fluidPage(
  useShinyjs(), # to initialise shinyjs
  
  # Application title
  titlePanel("Old Faithful Geyser Data"),
  
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "test",
                  label = "Test",
                  choices = mytest,
                  selected = "first"),
      disabled( # start as disabled
        checkboxInput("checkbox","check this box", FALSE))
      ),
    
    mainPanel(
      plotOutput("distPlot")
    )))


server <- function(input, output) {
  
  output$distPlot <- renderPlot({
    switch(
      input$test,
      "first" = { 
        plot(rnorm(100))
        disable("checkbox")
      },
      {
        enable("checkbox")
        if(input[["checkbox"]] == FALSE){
         "second" = plot(rnorm(1000), col="blue")
        } else{
         "second" = plot(rnorm(10000), col="red")   
        }
      }
    )
  })
}

shinyApp(ui = ui, server = server)
  • Related