我正在创建一个简单的 D3 折线图,但在使用以下命令创建工具提示时遇到问题d3.bisector()
功能。我正在寻找它去 Y 和 X 轴的每个值。 bisector 函数可以很好地为我提供与鼠标坐标相对应的 xData 值,但我不断得到 yData 的一些非常奇怪的结果。我怀疑问题在于 yData 数组的降序性质。有没有办法调整bisector()
处理降序数组的函数?我正在寻找一种适用于任何数据集的解决方案。
//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];