清除plotly点击事件

Clear plotly click event

我正在尝试在 shiny 应用程序的上下文中使用 plotly click 事件。在 the official demo 之后,我正在使用这段代码来更新日期选择器并在点击时跳转到我的应用程序中的另一个选项卡:

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")
  }

但是,当我随后尝试从 details 切换回 overview 选项卡时,我会立即返回到 details 选项卡。 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.

那么,如何以编程方式清除点击事件?添加 d <- NULL 到条件的末尾似乎并没有做到这一点。

我有同样的问题,我找到的解决方法是将旧状态存储在全局变量中,并且仅在该变量发生变化时进行更新,而不是 !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))
    }
  })
...
}

这还允许您在元素未被选中时添加一个行为

我通过使用 shinyjs 并在 Shiny.onInputChange 函数的帮助下手动重置 event_data("plotly_click") 解决了这个问题,该函数手动设置 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)