My next task is to draw a vertical line wherever the mouse is, when this line hits a data point of a graph it shows the tooltip. I already discovered that you have to use bisector for that, so will try something and get back to this topic if I am stuck.
Have to use invert and bisect somehow, my case is more complicated than those examples given.
I thought I have defined circle but it says circle not defined.
So right now, your mousemove code is looking for something called circle, but that’s not defined. (It was only defined in terms of the movetooltip function, because that function needed to know what “circle” was being hovered over.
Even if it did resolve the reference to circle, it would then complain that it cant resolve a function called x, because that should be your scale. It would also complain that your data does not contain an x property (because your data isnt an object, its a 2 dimensional array).
I’m… somewhat unclear what you’re specifically trying to do at this exact moment, but lets try this;
Instead of moving the circle, tell your VertLine to move itself on the x axis.
Things I had to do to get your code to work correctly: (No, i’m not giving you the code yet, but pointers :P)
The mousemove event should instead by a pointermove event bound to the SVG itself.
You will need a bisector with an accessor function pointing at the x value of the two dimensional data array.
The mouse, now bound to the SVG, is not translated; so you’ll need to adjust the x-coordinate received from the mouse to compensate.
Because the SVG is wider than your dataset, you will need to handle the edge case that the bisector returns a value that would be at the end of the new array.
Bonus, which may be helpful later:
I used a line instead of a rect. Because it’s a line.
That JSFiddle example code doesn’t work for me, there is an error message in the D3.
I wanna add this line functionality to the existing one, i.e. keep the current tooltip code for now and only remove it when the line version finally works. Tried this now, no error messages but not working either:
let VertLine = svg.append('line')
.attr("transform","translate(150,100)")
.style("stroke", "black")
.style("stroke-width", 2)
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", 0)
.attr("y2", height);
function mousemove(){
var x0 = xScale.invert(d3.mouse(this)[0]);
var i1 = bisect(dataset1, x0, 1);
var i2 = bisect(dataset2, x0, 1);
var i3 = bisect(dataset3, x0, 1);
selectedData1 = dataset1[i1]
selectedData2 = dataset1[i2]
selectedData3 = dataset1[i3]
VertLine
.attr("cx", xScale(selectedData1.xScale))
.attr("cy", yScale(selectedData1.yScale))
}
So… let’s tackle the points that I laid out before, one at a time.
Right now, your code binds a function on mousemove, and tries to bind it to:
a nonexistant element class .zoom,
each dot of the red line,
each dot of the blue line,
and each dot of the green line.
Instead, you will need to bind a pointermove event to an existing element.