D3:使用mouseover查找图形y坐标 [英] D3: finding graph y-coordinate with mouseover

查看:661
本文介绍了D3:使用mouseover查找图形y坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用D3制作交互式面积图。在鼠标悬停在区域图表上的时候,我想在图表顶部显示一个圆点,如下例所示:
http://hci.stanford.edu/jheer/files/zoo/ex/time/multiples.html

I am making an interactive area chart using D3. While mousing over the area-chart, I'd like to have a dot rolling along the top of the chart, as in the following example: http://hci.stanford.edu/jheer/files/zoo/ex/time/multiples.html

一旦我得到鼠标位置(使用d3.mouse),我如何将这些坐标转换为相应的数据? x轴使用x标度的逆(例如x.invert)是直接的。但是,我找不到我的图的相应的y坐标。理想情况下,我可以查找x坐标在我的数据,找到相应的y坐标,但不知道如何做到这一点与D3。谢谢!

Once I get the mouse position (using d3.mouse), how do I translate these coordinates to the corresponding data? The x-axis is straightforward using the inverse of the x-scale (e.g. x.invert). However, I can't find the corresponding y-coordinate for my graph. Ideally I could "look up" the x-coordinate in my data and find the corresponding y-coordinate, but not sure how to do this with D3. Thanks!

推荐答案

创建自己的查找表实际上比较容易:

It's actually relatively easy to create your own lookup table:

/* Create the lookup table */
var table = {};
data.forEach(function(d) {
    table[d.x] = d.y;
});

这是一个可行的解决方案,如果你有足够的数据点,但很可能你可能需要使用某种舍入或内插器来填充中间x值。例如,如果您的点之间有固定的间距,您可以使用线性插值器,然后进行以下计算,以在 mouseover 上获取圆圈的坐标:

This is a viable solution if you have enough data points, but it's likely that you will probably need to use some sort of rounding or interpolator to fill in the intermediate x-values. For instance, if there is a fixed spacing between your points, you can use a linear interpolator and do the following calculations to get the coordinates for your circle on mouseover:

var x = d3.mouse(this)[0];
var y;

if ( table[x] === undefined ) {
    var lower = x - (x % SPACING);
    var upper = lower + SPACING;
    var between = d3.interpolateNumber(table[lower], table[upper]);
    y = between( (x % SPACING) / SPACING );
} else {
    y = table[x];
}



这里是正在执行的代码: http://jsfiddle.net/Wexcode/KGxHF/



这里是另一个例子如何从 Mike Bostock http://bl.ocks.org/3025699

这篇关于D3:使用mouseover查找图形y坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆