Clear click event

I am trying to use plot clicks in the context of a brilliant app. After the official demo, I use this bit of code to update the date picker and switch to another tab in my application when I click:

observe({ d <- event_data("plotly_click", source = 'plot') if(!is.null(d) & (input$navPanel == 'overview')) { d %>% filter(curveNumber == 0) %>% select(x) -> selected_date updateDateInput(session, "date", value = lubridate::ymd(selected_date$x)) updateTabsetPanel(session, "navPanel", selected = "details") } 

However, when I then try to switch from the details tab to overview , I will immediately return to the details tab. I assume that this happens because the event is never cleared, i.e. d not null when the tab changes, so the condition in if -clause is TRUE .

So how can I clear the click event programmatically? Adding d <- NULL to the end of the conditional expression does not seem to do this.

+2
source share
2 answers

I have the same problem and the workaround I found is to keep the old state in the global variable and only make updates when this variable changes, and not !is.null()

 selected_date <- 0 # declare outside the server function server <- function(input, output, session) { observe({ d <- event_data("plotly_click") new_value <- ifelse(is.null(d),"0",d$x) # 0 if no selection if(selected_date!=new_value) { selected_date <<- new_value if(selected_date !=0 && input$navPanel == 'overview') updateDateInput(session, "date", value = lubridate::ymd(selected_date)) } }) ... } 

It also allows you to add behavior whenever an item is not selected.

+2
source

I solved this using shinyjs and manually resetting event_data("plotly_click") using the Shiny.onInputChange function, which manually sets the values ​​to input :

 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) 
+1
source

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


All Articles