I'm using D3.js. I want to show a tooltip with corresponding Y-axis value when i mouseover d3.svg.line().
I tried using this code:
d3.svg.line().append("title")
.text(function(d) { return d; });`
but it throws error has no method 'append'. Is there any other way?
d3.svg.line() is a line generator; it is not the actual line element. This function is designed to work with an area generator, though you can disable the appearance of the shape within by using "fill:none." For more detailed information, here is a link to its documentation: https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-line.
The code below creates a path element using the d3.svg.line() generator and then adds a tooltip to the path it generates. This title's text attribute shows the y-value of wherever the mouse is. This is done by using the mouse event "mousemove" which seems to be more what you want instead of using "mouseover." (Mouseover requires you to move in and out of the shape to update the text value, whereas mousemove will change the value even if your mouse moves along the line.)
var data = [[{x:100, y:200}, {x:0,y:400}, {x:2, y:300}]];
var line = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("basis");
var svg = d3.select("body").append("svg:svg")
.attr("width", 400)
.attr("height", 400);
var g = svg.selectAll("g").data(data).enter().append("svg:g")
.attr("width", 400)
.attr("height", 400);
g.append("path")
.attr("d", line)
.attr("id", "myPath")
.attr("stroke", "black")
.attr("stroke-width", 5)
.attr("fill", "none") // Remove this part to color the
// shape this path produces
.on("mousemove", mMove)
.append("title");
function mMove(){
var m = d3.svg.mouse(this);
d3.select("#myPath").select("title").text(m[1]);
}
There was a little error in your answer.
d3.svg.mouse(this)
doesn't work.
The correct answer is
d3.mouse(this)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With