'How to calculate y value for given x using d3.js

I have defined a line generator with d3.js as follows:

var line = d3.svg.line()
    .interpolate("monotone")
    .x(function(d) {return x(d.date); })
    .y(function(d) {return y0(d.visits); });

The data is read from a csv with the following format:

date,visits
12/08/12,1
13/08/12,0
14/08/12,0
15/08/12,33
16/08/12,28

The csv file is loaded into data, and parsed as:

data.forEach(function(d) {
    d.date = d3.time.format("%d/%m/%y").parse(d.date);
    d.visits = +d.visits;
});

and added to the document with:

svg.append("path")
    .datum(data)
    .attr("class", "line")
    .attr("d", line)

Elsewhere in my script, I need to work out what the y value is at a particular date. So for example, I might want to get a y value for the line where the date is 15/08/12 (equivalent to y0(33)). How can I do this?



Solution 1:[1]

Edit

To piggy back off of Lars' example, with a minor tweak to avoid -1 hacks:

var bisect = d3.bisector(function(d) { return d.date; }).left;
...   
var item = data[bisect(data, new Date(2012, 8, 15))];
y0(item.visits);

Original Post

rudivonstaden, you can use the .left function attached to the bisector instead of the .right in Lars' example -- that way you do not have to do the -1 hack that you did.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1