Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

r - Clear plotly click event

I'm trying to use plotly click events in the context of a shiny app. Following the official demo I'm using this bit of code to update a date picker and jump to another tab in my app on 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 back from the details to the overview tab, I get immediately thrown back to the details tab. I'm assuming that this happens because the event is never cleared, i.e. d is not null when the tab gets changed and so the condition in the if-clause evaluates to TRUE.

So, how do I clear the click event programmatically? Adding d <- NULL to the end of the conditional doesn't seem to do it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I have same problem, and the workaround I've found is to store the old state in a global variable, and do the updates only when that variable changes and not on the !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))
    }
  })
...
}

This also allows you to add a behaviour whenever the element is unselected


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...