use*_*801 8 javascript r shiny plotly r-plotly
我是 r-plotly 新手,试图找出如何处理不在数据上的点击。似乎使用event_data("plotly_click")
I 获取数据中点上的事件,但到目前为止还没有弄清楚如何针对不接近数据但仅在绘图的白色部分上的点击执行此操作。
图中的闪亮点击事件可以做到这一点,我只得到点击的 x 和 y。我想要类似的,但是为了情节。
我可以指定点击事件来自绘图上的任何位置,而不仅仅是数据上吗?
编辑:令人惊讶的是,这在情节中还不存在。查看此功能请求
https://github.com/plotly/plotly.js/issues/2696
https://github.com/ropensci/plotly/issues/1194
因此,在添加此功能之前,我想我的问题是有哪些选项可以做到这一点?看起来像是一个基本功能,我希望对 JavaScript/Shiny/Plotly 有更多了解的人能够破解它。
编辑:该Plotly.plot()
函数已被弃用- 现在使用Plotly.update()
:
以下是使用plotlyProxy
而不是重新渲染绘图,速度更快:
library(plotly)
library(shiny)
library(htmlwidgets)
initDF <- data.frame(x = 1:10, y = 1:10)
ui <- fluidPage(
plotlyOutput("myPlot"),
verbatimTextOutput("click")
)
server <- function(input, output, session) {
js <- "
function(el, x, inputName){
var id = el.getAttribute('id');
var gd = document.getElementById(id);
var d3 = Plotly.d3;
Plotly.update(id).then(attach);
function attach() {
gd.addEventListener('click', function(evt) {
var xaxis = gd._fullLayout.xaxis;
var yaxis = gd._fullLayout.yaxis;
var bb = evt.target.getBoundingClientRect();
var x = xaxis.p2d(evt.clientX - bb.left);
var y = yaxis.p2d(evt.clientY - bb.top);
var coordinates = [x, y];
Shiny.setInputValue(inputName, coordinates);
});
};
}
"
clickposition_history <- reactiveVal(initDF)
observeEvent(input$clickposition, {
clickposition_history(rbind(clickposition_history(), input$clickposition))
})
output$myPlot <- renderPlotly({
plot_ly(initDF, x = ~x, y = ~y, type = "scatter", mode = "markers") %>%
onRender(js, data = "clickposition")
})
myPlotProxy <- plotlyProxy("myPlot", session)
observe({
plotlyProxyInvoke(myPlotProxy, "restyle", list(x = list(clickposition_history()$x), y = list(clickposition_history()$y)))
})
output$click <- renderPrint({
clickposition_history()
})
}
shinyApp(ui, server)
Run Code Online (Sandbox Code Playgroud)
感谢@unumireappassionato 在我最初的答案中提供了有关小水平偏移的解决方案。