我在使用 d3js 和日期时遇到了一些麻烦:
这是一些数据,带有重量和日期的对象数组
var weights = [{"atdate":"2013-09-07","weight":"82","comment":"Reprise !"},
{"atdate":"2013-09-10","weight":"81.3","comment":""},
{"atdate":"2013-09-15","weight":"80.8","comment":""},
{"atdate":"2013-09-16","weight":"80.8","comment":""},
{"atdate":"2013-09-17","weight":"80.3","comment":""},
{"atdate":"2013-09-18","weight":"81.2","comment":""},
{"atdate":"2013-09-19","weight":"80.9","comment":""},
{"atdate":"2013-09-20","weight":"80.7","comment":""},
{"atdate":"2013-09-21","weight":"81","comment":""},
{"atdate":"2013-09-22","weight":"80.8","comment":""}];
可以看到最小日期是 2013-09-07,最大日期是 2013-09-22
现在,我将这些数据发送到一个函数
function draw_spline (_weights) {
var parse_date = d3.time.format('%Y-%m-%d').parse;
var weights = _weights.map(function(w) {
w.atdate = parse_date(w.atdate);
w.weight = parseFloat(w.weight);
return w;
})
var x = d3.time.scale().range([0,width]);
var boundaries_dates = d3.extent(weights, function(d){return d.atdate});
console.log('boundaries_dates',boundaries_dates);
x.domain(boundaries_dates);
console.log('domain extent',x.domain());
...
我使用 parse_date 构造真实的日期对象。这是控制台的输出:
boundaries_dates, Array [
Mon Sep 23 2013 00:00:00 GMT+0200 ,
Sun Sep 22 2013 00:00:00 GMT+0200 ]
domain extent, Array [
Sat Sep 07 2013 00:00:00 GMT+0200 ,
Sun Sep 22 2013 00:00:00 GMT+0200 ]
如您所见,范围是错误的,而不是我今天的 2013-09-07。我想有最短的日期。
让我烦恼的是,如果我将范围发送到比例域,则 scale.domain() 会返回我想要的值。(所以有一种方法可以得到我想要的,但感觉不对)。
所以,
如何使用 d3.extent() 获得正确的范围?
如何从不包含它的数组中获取正确的第一个日期?
谢谢