Search code examples
rshinyggplotly

Shiny renderPlotly with two conditions


I am developing app in Shiny. I want to render plot using submit button. I also want to print labels if user check the inputcheckbox. I am able to render plot via button. But it doesnt work when the checkbox checked.

Here is the code:

 library(shiny)
 library(plotly)

 ui <-  fluidPage(
 actionButton('RUN', 'Run'),
 checkboxInput('PrintLab', 'Label', FALSE),
 plotlyOutput("plot1")
 )

 server = function(input, output) {
 output$plot1 <- renderPlotly({
 req(input$RUN)
 isolate({
   ggplotly(ggplot(data = mtcars, aes(wt, hp)) + 
           geom_point(size=1, colour = "grey"))
   })

  req(input$PrintLab)
  isolate({
   ggplotly(ggplot(data = mtcars, aes(wt, hp)) + 
           geom_point(size=1, colour = "grey") +
           geom_text(aes(label=wt), size=3, colour = "black"))
   })

 })
}

 runApp(shinyApp(ui, server))

Solution

  • I'm no Shiny expert, but req(input$PrintLab) doesn't look right to me. Does this accomplish what you were going for?

    server <- function(input, output) {
      output$plot1 <- renderPlotly({
        req(input$RUN)
    
        if (!input$PrintLab) {
          ggplotly(ggplot(data = mtcars, aes(wt, hp)) + 
                 geom_point(size=1, colour = "grey"))
        } else {
          ggplotly(ggplot(data = mtcars, aes(wt, hp)) + 
                 geom_point(size=1, colour = "grey") +
                 geom_text(aes(label=wt), size=3, colour = "black"))
        }
    
      })
    }
    

    (I'm sure there's a better way. That's just off the top of my head.)