Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Removing plotly click event data

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)

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?

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.

You can use reactiveValues for this:

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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...