How to show tooltip with value when hovering over svg line graph using d3.js?

I am using D3.js. I want to show a tooltip with the 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 an error does not have a method of 'append' . Is there another way?

+6
source share
2 answers

d3.svg.line () - string generator; This is not an actual line item. This function is designed to work with the area generator, although you can disable the appearance of the form inside using "fill: none". For more details, here is a link to his documentation: https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-line .

In the code below, a path element is created using the d3.svg.line () generator, and then a tooltip is added to the path that it creates. This header text attribute shows the value of y, wherever we are. This is done using the "mousemove" mouse event, which seems to be more than what you want, instead of using a "mouseover". (Mouseover requires you to move and exit the form to update the text value, while 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 dx; }) .y(function(d) { return dy; }) .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]); } 
+11
source

There was a small error in your answer.

 d3.svg.mouse(this) 

does not work.

Correct answer

 d3.mouse(this) 
+8
source

All Articles