Removing click event graphic data

I am developing a Shiny application that contains a scatter plotly . I would like the user to be able to click on the graph to record the event using the event_data function, but then be able to clear this event by pressing the actionButton button. The following is an example code example:

 library(shiny) library(plotly) ui <- fluidPage( actionButton("clearEvent", label = "clear event"), verbatimTextOutput("plotVal"), plotlyOutput('plot1') ) server <- function(input, output, session) { output$plot1 <- renderPlotly({ d <- diamonds[sample(nrow(diamonds), 1000), ] plot_ly(d, x = ~carat, y = ~price, color = ~carat, size = ~carat, text = ~paste("Clarity: ", clarity)) }) output$plotVal <- renderPrint({ e <- event_data("plotly_click") if (is.null(e)) { NULL } else { e } }) observeEvent(input[["clearEvent"]], { e <- NULL }) } shinyApp(ui = ui, server = server) 

This does not clear the event as I expected. A look at the code for event_data shows that this is probably because it is stored inside the session object itself. Any ideas how I can overwrite it?

The only similar thing I came across is a Bright click on an event , but it is very hacky and doesn't seem to work for me.

+5
source share
2 answers

In your example, e is defined only in renderPrint and in observeEvent and not globally, so even if e changed in observeEvent , it does not run anything in renderPrint .

You can use reactiveValues for this:

 data <- reactiveValues(e=NULL) observe({ data$e <- event_data("plotly_click") }) output$plotVal <- renderPrint({ e <- data$e if (is.null(e)) { NULL } else { e } }) observeEvent(input[["clearEvent"]], { data$e <- NULL }) 

data$e changes whenever the user presses a plot or button, and since renderPrint has a dependency on data$e , which is updated whenever data$e changes.

+2
source

The previous answer partially solves the problem, however, the user cannot click on the same plotly graph again, at least no update will be called. This problem can be solved by manually resetting the event_data("plotly_click") source event_data("plotly_click") using shinyjs :

 library(shiny) library(plotly) library(shinyjs) ui <- shinyUI( fluidPage( useShinyjs(), # code to reset plotlys event_data("plotly_click", source="A") to NULL -> executed upon action button click # note that "A" needs to be replaced with plotly source string if used extendShinyjs(text = "shinyjs.resetClick = function() { Shiny.onInputChange('.clientValue-plotly_click-A', 'null'); }"), actionButton("reset", "Reset plotly click value"), plotlyOutput("plot"), verbatimTextOutput("clickevent") ) ) server <- shinyServer(function(input, output) { output$plot <- renderPlotly({ plot_ly(mtcars, x=~cyl, y=~mpg) }) output$clickevent <- renderPrint({ event_data("plotly_click") }) observeEvent(input$reset, { js$resetClick() }) }) shinyApp(ui, server) 
0
source

Source: https://habr.com/ru/post/1265861/


All Articles