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 ay value for the line where the date is 15/08/12
(equivalent to y0(33)
). How can I do this?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.