Home > Software engineering >  R plotly display cursor coordinates
R plotly display cursor coordinates

Time:02-24

I would like to display the x- and y-axis cursos coordinates at all times and wherever on the plot.

This is what I am looking for:

enter image description here

This is what I have tried, without success:

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")

Edit
I can do not have access to a shiny server.

CodePudding user response:

The main idea of the code I linked above is not shiny related. Please check the following:

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)

result


Using ggplotly:

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