R plotly显示光标坐标

R plotly display cursor coordinates

我想在绘图的任何时间和任何位置显示 x 轴和 y 轴光标坐标。

这就是我要找的:

这是我试过的,没有成功:

library(magrittr)
library(ggplot2)
library(plotly)

X <- data.frame(xcoord = -5:5, ycoord = -5:5)

gg <- ggplot(X, aes(xcoord, ycoord)) + geom_point() + labs(x = "", y = "")

ggplotly(gg) %>% 
  add_trace(type = "bar", 
            x = ~xcoord, y = 0, 
            hoverinfo = 'text', 
            text = ~paste("X:", xcoord),
            yaxis = "y", opacity = 0,
            showlegend = FALSE,
            marker = list(color = "#ffffff")) %>% 
  layout(hovermode = "x")

编辑
我无法访问闪亮的服务器。

我上面链接的代码的主要思想与 shiny 无关。请检查以下内容:

library(plotly)
library(htmlwidgets)

DF <- data.frame(x = 1:10, y = 1:10)

JS <- "
    function(el, x){
      var id = el.getAttribute('id');
      var gd = document.getElementById(id);
      var d3 = Plotly.d3;
      Plotly.update(id).then(attach);
        function attach() {
          gd.addEventListener('mousemove', 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);
            Plotly.relayout(gd, 'xaxis.title', 'x: ' + parseFloat(x).toFixed(2));
            Plotly.relayout(gd, 'yaxis.title', 'y: ' + parseFloat(y).toFixed(2));
            // Plotly.relayout(gd, 'title', ['x: ' + x, 'y : ' + y].join('<br>'));
          });
        };
    }"

plot_ly(
  DF,
  x = ~ x,
  y = ~ y,
  type = "scatter",
  mode = "markers"
) %>% layout(
  title = "My Plot",
  xaxis = list(title = 'x:'),
  yaxis = list(title = 'y:')
) %>% onRender(JS)


使用ggplotly:

gg <- ggplot(DF, aes(x, y)) + geom_point() + labs(title = "My Plot", x = "x:", y = "y:")
ggplotly(gg) %>% onRender(JS)