删除情节点击事件数据情节、事件、数据

2023-09-06 14:27:13 作者:竹风雅梦

我正在设计一个包含 plotly 散点图的 Shiny 应用程序.我希望用户能够单击图表以使用 event_data 函数记录事件,然后能够通过单击 actionButton.一些示例代码如下所示:

I am designing a Shiny app which contains a plotly scatter plot. I would like for the user to be able to click on the graph to record an event using the event_data function, but then be able to clear that event on the click of an actionButton. Some example code can be seen below:

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)

但是,这并没有像我预期的那样清除事件.查看 event_data 的代码表明这可能是因为它存储在 session 对象本身中.有什么想法可以覆盖它吗?

This doesn't clear the event like I would expect, however. Looking into the code for event_data shows that this is probably because it is stored within the session object itself. Any ideas how I can overwrite it?

我遇到的唯一类似的事情是 Clear plotly click event 但它非常hacky并且似乎对我不起作用.

The only similar thing I have come across is Clear plotly click event but it's very hacky and doesn't seem to work for me.

推荐答案

在您的示例中,e 只是在 renderPrintobserveEvent 而不是全局性的,因此即使 eobserveEvent 中更改,它也不会触发 renderPrint 中的任何内容.

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

您可以为此使用 reactiveValues:

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 每当用户单击绘图或按钮时都会更改,并且由于 renderPrint,每当 data$e 更改时都会更新.

data$e is changed whenever the user click the plot or the button, and since there is a dependency on data$e in the renderPrint, that gets updated whenever data$e is changed.