我正在设计一个包含plotly
散点图的Shiny应用程序.我希望用户能够使用该event_data
功能单击图表来记录事件,但是能够通过单击来清除该事件actionButton
.下面是一些示例代码:
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)
Run Code Online (Sandbox Code Playgroud)
然而,这并不像我期望的那样清除事件.查看event_data
显示的代码,这可能是因为它存储在session
对象本身中.我有什么想法可以覆盖它吗?
我遇到的唯一类似的事情是清晰的点击事件,但它非常hacky,似乎不适合我.
在您的示例中,e
仅在renderPrint
和 中定义observeEvent
,而不是全局定义,因此即使e
在 中更改observeEvent
,它也不会触发 中的任何内容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
})
Run Code Online (Sandbox Code Playgroud)
data$e
每当用户单击绘图或按钮时就会发生变化,并且由于data$e
中存在依赖关系,因此每当发生变化renderPrint
时都会更新。data$e