How to use d3.time.scale() to generate an array of

2020-03-30 01:59发布

问题:

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, years

 [2012-01-01, 2013-01-01, 2014-01-01]

or months

 [2012-01-01, 2012-02-01, 2012-03-01 ... 2014-12-01]

or whatever.

So I start out like this:

var t = d3.time.scale()
    .domain(d3.extent(dates))
    .nice(d3.time.year);

I would then assume from the documentation that I'd be able to do this

var ticks = t.ticks(d3.time.month,1);

...but that just returns a single date.

This gives me an array of months

var ticks = t.ticks(30)

...but only because I told it roughly how many ticks to generate (30), which I won't know in advance (unless I do some heavy lifting on my own, which kind of defeats the purpose of using d3 for this).

I don't understand why it's not working to just tell it that I want every year, or every month, or every 3 months, or whatever.

I've put up a fiddle here: http://jsfiddle.net/herbcaudill/LgGpd/4/

回答1:

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.



回答2:

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.