我有以下json:
[{"Time":"2017-02-07 16:14:06"},
{"Time":"2017-02-07 16:58:49"},
{"Time":"2017-02-07 17:07:11"},
{"Time":"2017-02-07 18:13:19"},
{"Time":"2017-02-07 13:56:06"},
{"Time":"2017-02-07 19:07:57"},
{"Time":"2017-02-07 12:08:58"},
{"Time":"2017-02-07 01:41:00"},
{"Time":"2017-02-07 11:56:49"},
{"Time":"2017-02-07 02:45:29"},
{"Time":"2017-02-07 11:40:07"},
{"Time":"2017-02-07 04:15:45"},
]
我正在解析d3.json函数中的这些日期,以获得24小时值,如下所示:
var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;
d3.json("/wp-content/themes/jordan/js/data.json", function(d){
d.forEach(function(d){
d.Time = parseDate(d.Time).getHours();
console.log(d.Time);
});
});
这会将我的所有值以24小时为单位返回整数。一切都很好。如何使用d3.nest()
将所有小时值分组为4小时增量?防爆。 0 - 4,4 - 8,8 - 12,12 - 16,16 - 20,20 - 24.
答案 0 :(得分:2)
如果以这种方式定义句点数组
var periods = ['0 - 4', '4 - 8', '8 - 12', '12 - 16', '16 - 20', '20 - 24']
然后,您可以轻松定义特定时间属于这种方式的时间段
period[Math.floor(d/4)]
完整代码
var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse,
periods = ['0 - 4', '4 - 8', '8 - 12', '12 - 16', '16 - 20', '20 - 24'];
d3.json("/wp-content/themes/jordan/js/data.json", function(data) {
data = data.map(function(d) {
return parseDate(d.Time).getHours();
});
data = d3.nest()
.key(function(d) {
return periods[Math.floor(d/4)];
})
.entries(data);
});