I am trying to implement a D3 chart with multiple lines that shows the sample size at every point as a tooltip when hovering over the chart. I have the data as two arrays but I don't know how to access the second array relative to the position of the mouse on the chart.
How can I access the values in the second array with the correct index? Here is a jsfiddle showing what I need to fix: http://jsfiddle.net/fMXvv/1/ on line 60 of the js, or the div.html method shown below:
graph.append("svg:path").attr("d", line(data[0])).style("stroke", "black").style("stroke-width", 2)
.on("mouseover", function (d, i) {
div.transition()
.duration(200)
.style("opacity", .9);
div.html("n = " + data[0][i])
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
The difficulty comes from the fact that the chart has more than one series (3 lines), so knowing the x coordinate is not enough.
I used d3.event.pageY to map mouse coordinates using scale:
var toolTipScale = d3.scale.linear().domain([h + 80, 80]).range([0, max_value]);
and then you use:
div.html("n = " + Math.ceil(toolTipScale( d3.event.pageY)) )
To map mouse position correctly it is necessary to add css
body { margin: 0; padding: 0; }
Here is jsfiddle of this - http://jsfiddle.net/cuckovic/sDnC8/
To access elements from second array you can use d3.event.pageX:
var iScale = d3.scale.linear().domain([w + 80, 80]).range([data[0].length, 0]);
and then:
div.html("n = " + data[1][Math.floor(iScale( d3.event.pageX))] )
jsfiddle: http://jsfiddle.net/cuckovic/sDnC8/5/
I had a problem that might have been similar to yours, I needed to select a time based on the mouse position, this is what I did (might give you some ideas):
var timeScale = d3.scale.linear()
.domain([startTime.getTime(), endTime.getTime()])
.range([30, r + 10])
.clamp(true);
axisOverlay.on("mousemove", mousemove)
.on("touchmove", mousemove);
function mousemove() {
selectedTime = new Date(timeScale.invert(d3.mouse(this)[1]));
}
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.