Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 386
rudivonstaden Avatar asked Apr 26 '13 14:04

rudivonstaden


People also ask

How can we use D3 js explain with example?

D3 allows you to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to the document. For example, you can use D3 to generate an HTML table from an array of numbers. Or, use the same data to create an interactive SVG bar chart with smooth transitions and interaction.

How to create a line in D3 js?

Step 8: Plot Line To make a line, we will use the line generator of d3 by invoking d3. line() . This line generator can then be used to compute the d attribute of an SVG path element. We append path to our SVG and then specify the class as line .

What is D3 bisector?

The bisector() Function in D3. js is used to returns a new bisector using the specified accessor or comparator function. This method can be used to bisect arrays of objects instead of being limited to simple arrays of primitives.


1 Answers

You can use bisect to find the date in your array and then call the y0 function. The code would look something like this (taken pretty much straight from the documentation):

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

Note that this approach requires your dates to be sorted, which they are in your example data.

like image 76
Lars Kotthoff Avatar answered Oct 19 '22 03:10

Lars Kotthoff