javascript - D3.js 获取面积图最近的 X 和 Y 坐标

标签 javascript svg d3.js coffeescript dc.js

您好,我有一个包含多个 X(年份)和 Y(价格)值的面积图。正如我发现的那样,当用户单击线上的一个点时,有一种简单的方法可以获取图表的 X、Y 坐标值,但是单击外部线,即 SVG/图表主体区域只能提供平面坐标的 X、Y而不是数据。

enter image description here

图表上的点:

circles = c.svg().selectAll 'circle.dot'
circles.on 'click', (d) ->
    console.log 'POINT', 'Datum:', d

O/P:

POINT Datum: 
{x: Fri Feb 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 666}

图表外点:

svg.on 'click', () ->
    console.log 'SVG', d3.mouse(@)

O/P:

SVG [605.5, 394.5]

现在有什么方法可以让我在单击 SVG 时获得最近的数据坐标?例如 SVG [605.5, 394.5] 会是(类似于最近的 [X, Y] 使用)

{x: Fri Feb 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 666}

或将 SVG X、Y 转换为数据 X、Y 的其他方式?

原始数据的形式为,

[
    {x: Fri Jan 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 666},
    {x: Fri Feb 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 668},
    {x: Fri Mar 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 700},
    {x: Fri Apr 01 1980 00:00:00 GMT+0000 (GMT Standard Time), y: 750},
    .
    .
    .
    {x: Fri Dec 01 2010 00:00:00 GMT+0000 (GMT Standard Time), y: 2000},
    .
    .
    .
]

最佳答案

http://bl.ocks.org/mikehadlow/93b471e569e31af07cd3

使用 d3.bisector,

var mouse = d3.mouse(this);
var mouseDate = xScale.invert(mouse[0]);
var bisectDate = d3.bisector(function(d) { return d.x; }).left;
var i = bisectDate(data, mouseDate); // returns the index to the current data item

var d0 = data[i - 1]
var d1 = data[i];
// work out which date value is closest to the mouse
var d = mouseDate - d0[0] > d1[0] - mouseDate ? d1 : d0;

var x = xScale(d[0]);
var y = yScale(d[1]);

关于javascript - D3.js 获取面积图最近的 X 和 Y 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25367987/

相关文章:

javascript - 如何判断一个 JavaScript 库是否支持 AMD

javascript - Chart.js 条形图中的多个条形宽度

javascript - 回调参数搞乱了ajax调用?

javascript - D3.js 可折叠力布局 : Links are not being generated

javascript - 我如何使用 mutationobserver 而不是突变事件?

javascript - 查找 div 内中心点和中点的 x 和 y 坐标

javascript - 将动态变化的信息添加到 ng-binding 中

javascript - 使用 canvg 脚本将内联 svg 转换为 Canvas

javascript - SVG/XML 中是否有一些 innerHTML 替代品?

javascript - D3.js - 将 LinearIcons 附加到 SVG