问题描述
我已经定义了 d3.js
的行生成器,如下所示:
var line = d3.svg.line()
.interpolate(monotone)
.x(function(d){return x(d.date);})
.y(function(d){return y0(d.visits);});
数据从csv读取,格式如下:
日期,访问
12/08 / 12,1
13/08 / 12,0
14/08/12, 0
15/08 / 12,33
16/08 / 12,28
csv文件加载到 data
,并解析为:
data.forEach(function(d){
d.date = d3.time.format(%d /%m /%y)。parse(d.date);
d.visits = + d.visits;
});
并添加到文档中:
svg.append(path)
.datum(data)
.attr(class,line)
.attr d,line)
在我的脚本中的其他地方,我需要计算出y值特定日期。因此,例如,我可能想获得ay值的日期 15/08/12
(相当于 y0(33)
)。
您可以使用在数组中查找日期,然后调用 y0
函数。代码看起来像这样(从文档中直接得到):
var bisect = d3.bisector(function d){return d.date;})。
...
var item = data [bisect(data,new Date(2012,8,15))];
y0(item.visits);
请注意,这种方法需要对您的日期进行排序, p>
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?
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.
这篇关于如何使用d3.js计算给定x的y值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!