简体   繁体   中英

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

I have an X axis defined with a scale as follows:

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

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?

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.

Using this example we append a line to the focus variable

  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

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

}

Here's a working example with this code: Plunker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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