在d3.js中对x轴上的日期进行排序

Sorting dates on x axis in d3.js

本文关键字:日期 排序 d3 js 中对      更新时间:2023-09-26

我正在绘制一个d3图,其中我的数据来自json,在x轴上我有日期,但这些日期不是按升序排列的,这意味着这些日期没有排序。我使用过排序函数,但它不起作用,因为即使应用了这个排序函数,我也无法获得排序日期。这是我使用排序函数的片段

if (filterByDates) {
   selectDate = true;
   tempData = fliterdata;
   console.log("before date fliter data", tempData);
   var date1 = new Date(document.getElementById('field1').value);
   var date2 = new Date(document.getElementById('field2').value);
   tempData = tempData.filter(function(d) {
       console.log(date1, date2);
       //  alert(date1);
       return d.date >= date1 && d.date <= date2;

   });
   console.log("After date fliter data", tempData);
}

xScale.domain(tempData.map(function(d) {
    return d.date;
}).sort(function(a, b) {
    return a > b;
}));

您对日期的排序函数不正确,请参阅https://stackoverflow.com/a/10124053/1071630对于完整的答案,但最简单的比较函数是

xScale.domain(
    tempData.map(function(d) {
        return d.date;
    }).sort(function(a, b) {
        return a - b;
    })
);

还有一个演示

var objs = [
    {date: new Date('2016-01-01T00:00:00')}, 
    {date: new Date('2014-01-01T00:00:00')}, 
];
 
var dates = objs.map(function(d) {
    return d.date;
}).sort(function(a, b) {
    return a - b;
});
    
var scale = d3.time.scale();
scale.domain(dates);
console.log('2015-01-01T00:00:00' +' ---> ' + scale(new Date('2015-01-01T00:00:00')));
console.log('2014-07-01T00:00:00' +' ---> ' + scale(new Date('2014-07-01T00:00:00')));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>