单击相同的绘图标记两次不会触发事件两次

问题描述 投票:3回答:3

在用户点击散点图中的标记后,我使用Plotly的event_data("plotly_click")来做东西(打开模态)。之后(例如关闭模态),event_data("plotly_click")当然不会改变并且点击相同的标记因此不再触发相同的动作。

最小的例子:

library(plotly)
ui <- fluidPage(  
  plotlyOutput("plot")
)
server <- function(input, output, session) {
  output$plot <- renderPlotly({
    mtcars %>% plot_ly(x=~disp, y=~cyl)
  }) 

  # Do stuff after clicking on a marker in the plot
  observeEvent(event_data("plotly_click"), {
    print("do some stuff now") # this is not executed after second click on same marker
  })  
}
shinyApp(ui, server)

我尝试过使用shinyjs的onclick的解决方法,但没有用(它在情节的空白区域很好用,但在点击标记时却没有效果):

shinyjs::onclick(id="plot", print("clicked"))

我还尝试使用存储最后一次点击的反应值,然后立即重置(例如通过event_data("plotly_hover")),但所有尝试都失败,因为event_data("plotly_click")保持其旧值。

有人可以帮忙吗?

r modal-dialog shiny plotly shinyjs
3个回答
5
投票

[编辑:问题已在Plotly 4.9.0中修复。见答案below。这个答案适用于Plotly 4.8.0。从plotly 4.9.0。,从源代码中删除字符串.clientValue-或使用below answer

我终于解决了这个问题。我知道这会困扰一些人,所以我会在这里发布我的解决方案:

基本上我使用shinyjs包来重置关于某个事件(在我的情况下是一个按钮)的最后一次点击(event_data("plotly_click")获取其信息的来源)的数据。

函数的定义是(注意,如果使用“A”需要用plotly-source字符串替换):

extendShinyjs(text = "shinyjs.resetClick = function() { Shiny.onInputChange('.clientValue-plotly_click-A', 'null'); }")

然后在js$resetClick()按下按钮时调用它。

最小的例子:

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)

enter image description here


0
投票

我遇到了同样的问题,并提出了一个解决方案,我将plotly对象的source参数指定为无效值,如下所示:

在qazxsw poi和qazxsw poi中,让qazxsw poi成为plot_ly(data,x,y,...,source = x)对象的元素。当您的事件触发时,更改x(增量或散列)的值,该值实例化新的event_data(...,source = x)对象。

工作就像一个魅力。


0
投票

这个问题终于在Plotly方面得到了解决:x

reactiveValues每次点击都会更新,不仅仅是闪亮的输入变化(如前所述)。从Plotly 4.9.0开始工作。

使用Plotly 4.9.0的最小示例:

event_data()

https://github.com/ropensci/plotly/issues/1043

© www.soinside.com 2019 - 2024. All rights reserved.