如何使用d3.time.scale()来生成均匀间隔日期的数组? [英] How to use d3.time.scale() to generate an array of evenly spaced dates?

查看:170
本文介绍了如何使用d3.time.scale()来生成均匀间隔日期的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎像它应该是微不足道的。我想用 d3.time.scale()来得到均匀间隔日期覆盖一定范围内的时间的数组。例如,几年

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]

或几个月

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

或什么的。

于是,我开始像这样:

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

然后我会从文档假设的我' d是能够做到这一点。

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.

这给了我几个月的数组

var ticks = t.ticks(30)

...但只是因为我告诉它大概有多少蜱生成(30),我不会事先知道(除非我做一些繁重的我自己,哪一种违背了使用D3的目的为了这)。

...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).

我不明白为什么它不工作,每年只需告诉它我想,或每月或每3个月,或什么的。

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.

我在这里提出了一个小提琴: http://jsfiddle.net/herbcaudill/LgGpd/ 4 /

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

推荐答案

使用Date()构造不正常 - 它基本上依赖于浏览器。这是更安全的明确解析。构造函数不分析这样。

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.

而不是

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

使用:

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

修改的jsfiddle 这里

这篇关于如何使用d3.time.scale()来生成均匀间隔日期的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆