0

Problem: The following code produces a plotly bar chart. If you click on the bars data will be shown. If I am not interested anymore in the underlying table I want to click somewhere (i.e. not the bar) on the chart and the table shall "disappear".

Any idea how to do that? I already tried to add the is.null if-condition which is not working due to the req() (and req() is needed). Many thanks!

library(shiny)
library(plotly)
library(DT)

ui <- fluidPage(
  plotlyOutput("plot"),
  dataTableOutput("table")
)

server <- function(input, output) {

  output$plot <- renderPlotly({
    mtcars %>%
      group_by(cyl) %>%
      summarise(m = mean(mpg)) %>%
      plot_ly(., x = ~cyl,
              y = ~m, source = "test_plot") %>%
      add_bars()
  })

  observe({
    p <- event_data("plotly_click", source = "test_plot")
    req(p)

    output$table <- renderDataTable({
      if (is.null(p)){
        return(NULL)
      }

      mtcars
    })
  })

}

# Run the application
shinyApp(ui = ui, server = server)
rkraft
  • 495
  • 4
  • 16

0 Answers0