You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Plotly JavaScript中获取光标XY坐标?

获取Plotly JavaScript图表的鼠标悬停坐标方法

方法1:借助plotly_hover事件实现坐标转换

鼠标悬停在图表区域时,plotly_hover事件的回调参数包含鼠标屏幕坐标,结合Plotly内置的坐标转换工具,可将屏幕坐标转为图表的x/y轴数据坐标:

// 假设图表容器id为"myPlot"
const plotDiv = document.getElementById('myPlot');

plotDiv.addEventListener('plotly_hover', function(event) {
  // 获取鼠标屏幕坐标
  const pointer = event.pointer;
  // 转换为图表坐标轴对应的数值坐标
  const xAxisNode = Plotly.d3.select(plotDiv).select('.xaxislayer-above').node();
  const yAxisNode = Plotly.d3.select(plotDiv).select('.yaxislayer-above').node();
  const xCoord = xAxisNode.__xaxis__.invert(pointer.x);
  const yCoord = yAxisNode.__yaxis__.invert(pointer.y);
  
  console.log(`光标对应图表坐标:X=${xCoord.toFixed(2)}, Y=${yCoord.toFixed(2)}`);
});

方法2:监听mousemove事件实时获取

如果需要鼠标不在数据点上时也能获取坐标,直接给图表容器绑定mousemove事件,再通过图表布局对象的坐标转换方法处理:

const plotDiv = document.getElementById('myPlot');

plotDiv.addEventListener('mousemove', function(event) {
  // 计算鼠标相对于图表容器的像素位置
  const rect = plotDiv.getBoundingClientRect();
  const pixelX = event.clientX - rect.left;
  const pixelY = event.clientY - rect.top;
  
  // 从像素坐标转为图表数据坐标
  const xAxis = plotDiv._fullLayout.xaxis;
  const yAxis = plotDiv._fullLayout.yaxis;
  const xCoord = xAxis.p2d(pixelX);
  const yCoord = yAxis.p2d(pixelY);
  
  console.log(`光标图表坐标:X=${xCoord.toFixed(2)}, Y=${yCoord.toFixed(2)}`);
});

注意事项

  • 务必在图表渲染完成后绑定事件,比如放在Plotly.newPlot的回调函数内
  • 不同Plotly版本的坐标转换API可能略有差异,若上述方法失效,可打印plotDiv._fullLayout对象查看轴的结构和可用转换方法
  • 多轴图表需指定对应轴(如xaxis2、yaxis2)进行转换

内容的提问来源于stack exchange,提问作者drypatrick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:20:21