请根据我通过this 问题找到的this codepen 检查以下解决方法。
但是,到目前为止,我无法消除一个小的水平偏移 - 也许有人知道如何修复它?
library(plotly)
library(shiny)
library(htmlwidgets)
ui <- fluidPage(
plotlyOutput("graph"),
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.plot(id).then(attach);
function attach() {
var xaxis = gd._fullLayout.xaxis;
var yaxis = gd._fullLayout.yaxis;
var l = gd._fullLayout.margin.l;
var t = gd._fullLayout.margin.t;
var coordinates = [null, null]
gd.addEventListener('click', function(evt) {
var coordinates = [xaxis.p2c(evt.x - l), yaxis.p2c(evt.y - t)];
Shiny.setInputValue(inputName, coordinates);
});
};
}
"
clickposition_history <- reactiveVal(data.frame(x = 1:10, y = 1:10))
observeEvent(input$clickposition, {
clickposition_history(rbind(clickposition_history(), input$clickposition))
})
output$graph <- renderPlotly({
plot_ly(clickposition_history(), x = ~x, y = ~y, type = "scatter", mode = "markers") %>%
onRender(js, data = "clickposition")
})
output$click <- renderPrint({
input$clickposition
})
}
shinyApp(ui, server)
编辑:
这是使用plotlyProxy 而不是重新渲染的相同方法 - 偏移量更糟:
library(plotly)
library(shiny)
library(htmlwidgets)
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.plot(id).then(attach);
function attach() {
var xaxis = gd._fullLayout.xaxis;
var yaxis = gd._fullLayout.yaxis;
var l = gd._fullLayout.margin.l;
var t = gd._fullLayout.margin.t;
var coordinates = [null, null]
gd.addEventListener('click', function(evt) {
var coordinates = [xaxis.p2c(evt.x - l), yaxis.p2c(evt.y - t)];
Shiny.setInputValue(inputName, coordinates);
});
};
}
"
clickposition_history <- reactiveVal(data.frame(x = NA, y = NA))
observeEvent(input$clickposition, {
clickposition_history(rbind(clickposition_history(), input$clickposition))
})
output$myPlot <- renderPlotly({
plot_ly(data.frame(x = NA, y = NA), 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)
相关的 GitHub issue 和 PR。