How to reset event_data with a shiny button?

Viewed 767

in a interactive plot_ly the event_data saves the selected data. With the below code, it is possible to reset event_data with double click on the plot

 output$brush <- renderPrint({
    d <- event_data("plotly_selected")
    if (is.null(d)) "Click and drag events (i.e., select/lasso) appear here (double-click to clear)" else d
  })

But how to reset event_data with a shiny button?

Is there a solution?

1 Answers

If the source argument of the plot is set to XXX (the default is A), then you have to set the input plotly_selected-XXX to NULL. This can be done with the help of shinyjs:

library(shiny)
library(plotly)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  actionButton("reset", "Reset"),
  plotlyOutput("plot")
)

server <- function(input, output){
  output[["plot"]] <- renderPlotly({
    df <- data.frame(
      x = c(1,2,1), 
      y = c(1,2,1)
    )
    df %>%
      plot_ly(
        x = ~x,
        y = ~y,
        source = "A",
        type = 'scatter',
        mode = 'markers',
        marker = list(size = 20),
        showlegend = FALSE
      ) 
  })

  observeEvent(input[["reset"]], {
    runjs("Shiny.setInputValue('plotly_selected-A', null);")
  })

  observe({ # just to test
    print(event_data("plotly_selected", source = "A"))
  })

}

shinyApp(ui, server)
Related