How to use d3.time.scale() to generate an array of evenly spaced dates?

前端 未结 2 1891
囚心锁ツ
囚心锁ツ 2021-01-15 08:13

This seems like it should be trivial. I want to use d3.time.scale() to get an array of evenly spaced dates that covers a certain range of time. For example, yea

相关标签:
2条回答
  • 2021-01-15 08:50

    Using a dataset such as

    var dataset = [ 
          { "active" : false,
            "date" : "2014-12-12"
          },
          { "active" : true,
            "date" : "2014-12-13"
          },
          { "active" : true,
            "date" : "2014-12-14"
          },
          { "active" : true,
            "date" : "2014-12-15"
          }
        ]
    
    var slicedData = var slicedData = dataset.slice();
    

    I had a similar problem, and found that

    var x = d3.time.scale()
        .domain([new Date(slicedData[0].date), new Date(slicedData[slicedData.length - 1].date)])
        .range([0,width]);
    

    Dropped the first item in the scale (it still remains a mystery as to why that was the case), whereas

    var dates = slicedData.map(function(d) {
            return d3.time.format("%Y-%m-%d").parse(d.date);
        });
        var t = d3.time.scale()
            .domain(d3.extent(dates))
            .range([0,width])
            .nice(d3.time.day);
    

    worked fine.

    So, my only explanation is the one Lars provided. Date() is unpredictable, so use d3.time.format instead.

    0 讨论(0)
  • 2021-01-15 08:52

    Using the Date() constructor doesn't work reliably -- it basically depends on the browser. It's much safer to parse explicitly. The constructor doesn't parse as such.

    Instead of

    var dates = getDates().map(function(d) { return new Date(d) });
    

    use this:

    var dates = getDates().map(function(d) {
        return d3.time.format("%Y-%m-%d").parse(d);
    });
    

    Modified jsfiddle here.

    0 讨论(0)
提交回复
热议问题