填充D3阵列嵌套中的空隙 [英] Filling the gaps in D3 array nesting
问题描述
我有一个数组或对象由一个日期和一些值组成:
I have an array or objects consisting of a date and some values:
var flatData = [
{ "date": "2012-05-26", "product": "apple" },
{ "date": "2012-07-03", "product": "orange" },
...
]
我试图使用d3.nest这些对象的数量按年,然后按月。
I am trying to use d3.nest() to get a count of these objects by year and then by month.
var nestedData = d3.nest()
.key(function(d) { return d.date.split('-')[0]; }) // key is the year
.sortKeys(d3.ascending)
.key(function(d) {
var splitDate = d.date.split('-');
return splitDate[0] + '-' + splitDate[1]; // key is year-month
})
.sortKeys(d3.ascending)
.rollup(function(d) {
return d.length;
})
.entries(flatData);
这几乎可以工作,除了当一个月没有对象时,嵌套数据不包含指示该月份的计数为0的记录。是否有任何技巧来告诉D3填补这些差距?
This almost works, except that when there are no objects for a month, the nested data does not contain a record indicating a count of 0 for that month. Is there any trick to tell D3 to fill in these gaps?
(当然,我总是可以这么繁琐的方式,即循环遍历所有的嵌套层次, )
(Of course, I can always do it the tedious way, i.e. to loop through all the nested levels and create a new data structure that fills in the gaps.)
推荐答案
尝试在缩小之后添加缺少的数据点:
Try adding the missing data points after the reduction:
var flatData = [
{ "date": "2012-05-26", "product": "apple" },
{ "date": "2012-07-03", "product": "orange" }]
nestedData = d3.nest()
.key(function(d) { return d.date.split('-')[0]; }) // key is the year
.sortKeys(d3.ascending)
.key(function(d) {
var splitDate = d.date.split('-');
return splitDate[0] + '-' + splitDate[1]; // key is year-month
})
.sortKeys(d3.ascending)
.rollup(function(d) {
return d.length;
})
.entries(flatData);
yMFormat = d3.time.format('%Y-%m')
makeAllKeys = function(year) {
allKeys = [];
for(var i = 0; i<12;i++) { // 12 months in a year
allKeys.push(yMFormat(new Date(year,i,1)));
}
return allKeys;
}
nestedData = nestedData.map(function(yearObj) {
return {
values: makeAllKeys(+yearObj.key).map(function(k) {
value = yearObj.values.filter(function(v) { return v.key == k; })[0];
return value || ({key: k, values: 0});
})
};
});
这篇关于填充D3阵列嵌套中的空隙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!