简体   繁体   English

D3将鼠标位置反转为X轴上最接近的刻度值

[英]D3 Inversion of mouse position to closest tick value on the X-axis

I have an X axis defined with a scale as follows: 我有一个用比例尺定义的X轴,如下所示:

xRange = d3.time.scale().domain([minTime, maxTime]).range([20 , rawSvg.attr("width")]);

The ticks on the X-axis are distinct date values like 1 Jan, 2 Jan, 3rd Jan, etc. I want a bar or line to follow my mouse position and this is the code I have written for it X轴上的刻度是不同的日期值,例如1月1日,1月2日,1月3日等。我希望有一条线或线条跟随我的鼠标位置,这是我为此编写的代码

var dateMousePosMapper = xRange.invert(d3.mouse(d3.event.currentTarget)[0]);

console.log("mouse pos mapper", dateMousePosMapper.range());

tooltipLine.attr({
    "stroke": "#e8e6e6",
    "stroke-width": '25',
    "x1": xRange(dateMousePosMapper),
    "x2": xRange(dateMousePosMapper),
    "y1": 30,
    "y2": height - 20,
}).style("opacity", 0.5).attr('class', 'multiline-tooltip');

However, the line is also drawn for all points in between the ticks as well. 但是,也为刻度线之间的所有点绘制了线。 Is it possible to to map the mouse position to the nearest tick point on the X-axis and only show the line over the tick values on the X axis? 是否可以将鼠标位置映射到X轴上最接近的刻度点,而仅在X轴上的刻度值上显示线条?

There are a few things you need to do, as kekuatan said, you should use d3.bisector here's Mikes example of how to use it. 正如kekuatan所说,您需要做一些事情,您应该使用d3.bisector这是Mikes如何使用它的示例

Using this example we append a line to the focus variable 在这个例子中,我们在focus变量后面添加了一行

  focus.append("line").attr("class", "x--line")
    .style("stroke", "#777")
    .attr("stroke-width", 1.5)
    .attr("y1",-height)
    .attr("y2",0);

And select it in the mousemove function 并在mousemove功能中选择它

focus.select(".x--line")
  .attr("transform", "translate(" + x(d.date) + "," + (height) + ")");

}

Here's a working example with this code: Plunker 这是一个使用此代码的工作示例: Plunker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM