Muthu Rg
Muthu Rg

Reputation: 662

dynamic tooltip for multiline in d3.js

I'm building a complicated multiline graph with zoom, brushing, checkboxes etc. I was able to get this all work but stuck in getting the tooltip working. I would like to get something like this

http://bl.ocks.org/benjchristensen/2657838

A line with all the path value at a particular x cordinate

var vertical = d3.select("#main-graph")
.append("div")
.attr("class", "remove")
.style("position", "absolute")
.style("z-index", "19")
.style("width", "1px")
.style("height", "380px")
.style("top", "10px")
.style("bottom", "30px")
.style("left", "0px")
.style("background", "#fff");

d3.select("#main-graph")
.on("mousemove", function(){
mousex = d3.mouse(this);
mousex = mousex[0] + 220 ;
vertical.style("left", mousex + "px" )})
.on("mouseover", function(){  
mousex = d3.mouse(this);
mousex = mousex[0] +220 ;
vertical.style("left", mousex + "px")});
});

Currently i've this above code to get the line. How would i go about getting the data of all the lines on hover now. Appreciate any help!

Upvotes: 1

Views: 4986

Answers (1)

Yogesh
Yogesh

Reputation: 2228

Use scale.invert function to get the actual value from the mousex value.

var xValue = xScale.invert(mousex);

Once you have the xValue, use array bisector to find the index of the value in the array.

To declare the bisector function:

var bisectDate = d3.bisector(function(d) { return d.date; }).left;

and here's how to use it:

var index = bisectDate(data, xValue, 1);

Once you have the index, then you can choose the nearest between index, index - 1 and index + 1 values and get the all the yValues and xValues from the data.

var finalIndex = getDesiredIndex(data, index); //Implement getDesiredIndex to get the left, right or center whatever index you think is perfect for your graph.

my assumption is that your data is in the from of array of objects. So data[finalIndex].yValue1, data[finalIndex].yValue2 ..... should be what you are looking for.

If you need me to provide you with more concrete implementation or working example then add a jsFiddle and I can edit it for you.

Upvotes: 10

Related Questions