简体   繁体   English

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

[英]Sorting dates on x axis in d3.js

I am plotting a d3 graph in which my data is coming from json and on x axis I am having dates but those dates are not coming in ascending order means those dates are not sorted.我正在绘制一个 d3 图,其中我的数据来自 json 并且在 x 轴上我有日期,但这些日期没有按升序排列意味着这些日期没有排序。 I have used the sort function but its not working because even after applying this sort function I am not getting sorted dates.我已经使用了排序函数,但它不起作用,因为即使在应用这个排序函数之后,我也没有得到排序的日期。 Here is my snippet where I used sort function这是我使用排序功能的片段

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;
}));

Your sort function on dates is incorrect, see https://stackoverflow.com/a/10124053/1071630 for a complete answer but the simplest comparison function would be您对日期的排序功能不正确,请参阅https://stackoverflow.com/a/10124053/1071630以获取完整答案,但最简单的比较功能是

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

And a demo还有一个演示

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM