d3JS:对嵌套数组进行二等分 [英] d3JS: Bisecting a Nested Array

查看:155
本文介绍了d3JS:对嵌套数组进行二等分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为对这个问题的跟进,我设法创建了一个嵌套数组中的多系列折线图。我现在正尝试将工具提示添加到类似于 Mike Bostock的这篇文章的图表上。

As a follow up to this question, I've managed to create a multi-series line chart out of nested arrays. I'm now trying to add tooltips to chart similar to the one on this post by Mike Bostock.

这意味着我必须找出一种方法来平分嵌套数组,然后为工具提示选择这些值。如何将下面的代码行转移到嵌套数组?

This means that I have to figure out a method for bisecting the nested array and then selecting those values for a tooltip. How do I transfer the lines of code below to a nested array?

bisectDate = d3.bisector(function(d) { return d.date; }).left,

进一步加入剧本:

i = bisectDate(data, x0, 1),
    d0 = data[i - 1],
    d1 = data[i],

感谢您的帮助,这里有一个JS Fiddle的例子,我想用它来创建工具提示: http://jsfiddle.net/JYS8n/2/

Thanks for any help, here is an example JS Fiddle which I'd like to use to create tooltips: http://jsfiddle.net/JYS8n/2/

推荐答案

你需要在这里使用 bisect 两次,首先找到匹配的 x value然后找到匹配的 y 值。首先,您需要定义第二个自定义平分线,将该值考虑在内。

You need to use bisect twice here, first to find the matching x value and then to find the matching y value. First, you'll need to define a second custom bisector that takes the value into account.

var bisectValue = d3.bisector(function(d) { return d.Value; }).left;

处理程序的第一部分与非嵌套版本相比没有太大变化。唯一的区别是,我们不是只考虑单个数据系列,而是迭代所有数据系列并为每个数据系列收集最接近的数据点。

The first part of the handler is not changed a lot from the non-nested version. The only difference is that instead of considering only a single data series, we are iterating over all of them and collecting the closest data point for each.

var x0 = x.invert(d3.mouse(this)[0]),
    ds = data.map(function(e) {
        var i = bisectDate(e.Data, x0, 1),
            d0 = e.Data[i - 1],
            d1 = e.Data[i];
        return x0 - d0.Date > d1.Date - x0 ? d1 : d0;
    });

现在 ds 是一个数据点列表,每个系列最接近光标位置的一个。现在剩下要做的就是再次一分为二,找到与当前光标位置最接近的值。

Now ds is a list of data points, the closest one to the cursor position for each series. All that remains to be done now is to bisect again to find the one with the closest value to the current cursor position.

var y0 = y.invert(d3.mouse(this)[1]),
    i = bisectValue(ds.sort(), y0, 1),
    d0 = ds[i - 1],
    d1 = ds[i],
    d = y0 - d0.Value > d1.Value - y0 ? d1 : d0;

基本骨架与以前相同,只是这次我们比较 y .Value 。现在 d 是要突出显示的数据点。

The basic skeleton is the same as before, only this time we are comparing y and .Value. Now d is the data point to be highlighted.

focus.attr("transform", "translate(" + x(d.Date) + "," + y(d.Value) + ")");
focus.select("text").text(d.Value);

完整示例此处。我也改变了线插值 - 虽然这样看起来更漂亮,但是线不再经过实际点了。

Full example here. I've also changed the line interpolation -- while that makes it look nicer, the line doesn't go through the actual points anymore.

这篇关于d3JS:对嵌套数组进行二等分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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