Javier
Javier

Reputation: 730

Using Conditional Panel in Shiny to Render Plots at the Same Time

This is a reproducible example. I'm trying to understand using the conditionalpanel function under shiny.

How do I tweak the code in a manner such that when I check both checkboxes, the plot and image will be rendered together? (with the plot on the top and image at the bottom on main panel)

library(shiny)

ui = fluidPage(
  titlePanel("Plot or Example?"),
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput("my_choices", "Example or Plot",choices = c("Plot", "Example"), selected = 1),width=2),
    mainPanel(
      conditionalPanel(
        condition = "input.my_choices == 'Plot'",
        plotOutput('my_test1')
      ),
      conditionalPanel(
        condition = "input.my_choices == 'Example'",
        uiOutput("my_test2")
      )
    )
  )
)

server = function(input, output) {

  output$my_test1 <- renderPlot({plot(runif(100))})
  output$my_test2 <- renderUI({
    images <- c("http://www.i2symbol.com/images/abc-123/o/white_smiling_face_u263A_icon_256x256.png")
    tags$img(src= images)
  })
}

Upvotes: 0

Views: 1084

Answers (1)

Phil
Phil

Reputation: 8107

There are several things to do.

First, your selected argument of checkboxGroupInput should match one of the choices. Here I changed it to "Plot".

Second, I used "input.my_choices.includes('Example') && input.my_choices.includes('Plot')" as the condition when both are selected.

Third, Shiny doesn't allow the same output to be used more than once. To get around that, I made duplicates of the outputs in the server code, and referenced the duplicated names in the conditional Panel for the condition both boxes are checked.

library(shiny)

ui = fluidPage(
  titlePanel("Plot or Example?"),
      sidebarLayout(
    sidebarPanel(
      checkboxGroupInput("my_choices", "Example or Plot",choices = c("Plot", "Example"), selected = "Plot"),width=2),
    mainPanel(
      conditionalPanel(
        condition = "input.my_choices == 'Plot'",
        plotOutput("my_test1")
      ),
      conditionalPanel(
        condition = "input.my_choices == 'Example'",
        uiOutput("my_test2")
      ),
      conditionalPanel(
        condition = "input.my_choices.includes('Example') && input.my_choices.includes('Plot')",
        plotOutput("my_test1a"),
        uiOutput("my_test2a")
      )
    )
  )
)

server = function(input, output) {

  output$my_test1 <- output$my_test1a <- renderPlot({plot(runif(100))})
  output$my_test2 <- output$my_test2a <- renderUI({
    images <- c("http://www.i2symbol.com/images/abc-123/o/white_smiling_face_u263A_icon_256x256.png")
    tags$img(src= images)
  })

}

shinyApp(ui, server)

Upvotes: 1

Related Questions