d3.bisector降序排列 [英] d3.bisector on descending array

查看:147
本文介绍了d3.bisector降序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个简单的D3折线图,并且在使用d3.bisector()函数创建工具提示时遇到了麻烦.我正在寻找它去每个值的Y和X轴. bisector函数可以很好地为我提供与鼠标坐标相对应的xData值,但是对于yData,我一直得到一些非常奇怪的结果.我怀疑问题出在yData数组的降序性质.有没有一种方法可以调整bisector()函数以处理降序数组?我正在寻找一种适用于任何数据集的解决方案.

I am creating a simple D3 line chart and am having trouble creating the tooltip with the d3.bisector() function. I am looking for it to go to the Y and X axis for each value. The bisector function works fine for giving me the xData value that corresponds to the mouse coordinates but I keep getting some very strange results for the yData. I am suspecting that the problem lies in the descending nature of the yData array. Is there a way to adjust the bisector() function to handle descending arrays? I am looking for a solution that would work with any dataset.

//define the domain and range for the chart
var xScale =  d3.scaleLinear().domain([0,10]).range([0, width]);
var yScale =  d3.scaleLinear().domain([0,10]).range([height,0]);

//data for the line
var xData = [0,1,2,3,4,5,6,7,8,9,10];
var yData = [10,9,8,7,6,5,4,3,2,1,0];

//set up the  bisector function
var bisectData= d3.bisector(function(d){return d}).left;

 // get the x and y position of the cursor and put it into the Xscale/yScale function to get the correct X and Y values from the corresponding coordinates
var x0 = xScale.invert(d3.mouse(this)[0])
var y0 = yScale.invert(d3.mouse(this)[1])

//round the values to the nearest integer to match the original data
var x0 = Math.round(x0);
var y0 = Math.round(y0);

//get the correct index value of the relevant data array
var xIndex= bisectData(xData,x0,1);
//get the actual value from the original array using the correct index

//this work fine 
var x1 = xData[xIndex];

//this does not
var yIndex= bisectData(yData,y0,1);
var y1 = yData[yIndex];

推荐答案

d3.bisector() 您已覆盖(重点是我):

The documentation on d3.bisector() has you covered (emphasis mine):

如果您希望值以与自然顺序不同的顺序(例如,以降序而不是升序)排序,请使用比较器而不是访问器.

Use a comparator rather than an accessor if you want values to be sorted in an order different than natural order, such as in descending rather than ascending order.

该方法的签名使您可以传递比较器函数,该函数以将搜索值作为第二个参数传递的方式进行调用.因此,您可以按降序排列数组的等分线,如下所示:

The signature of that method allows you to pass in a comparator function which is called with the search value passed as the second argument. You can thus have a bisector for an array in descending order like so:

d3.bisector((d, x) => x - d).left
//              ^--- Search value

看看下面的工作演示:

const yData = [10,9,8,7,6,5,4,3,2,1,0];

const descBisector = d3.bisector((d, x) => x - d).left;
const yIndex = descBisector(yData, 2);

console.log(yIndex);

<script src="https://d3js.org/d3.v5.js"></script>

这篇关于d3.bisector降序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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