我正在为时间报告应用程序开发 d3.js 可视化。 我在包含项目时间报告(简化)的数组 actuals 中有行数据:
[{ resource: "John Smith",
reporting_period: "2012/04/1",
project: "Java implementation",
hours: 8}
... }]
我正在尝试使用 d3.nest 运算符按项目、资源和期间对项目实际值进行分层分组。一切正常,但我找不到使用 nest.rollup() 运算符在分组的中间级别获取 小时 小计的方法。
我有这样的东西:
actuals_by_prj_rsrc_period = d3.nest()
.key(function(d) { return d["project"]; })
.key(function(d) { return d["resource"]; })
.key(function(d) { return d["reporting_period"]; })
.rollup(function(rows) {return {
tot_hours:d3.sum(rows, function(d) {return d["hours"];}),
actuals: rows
};})
.entries(actuals);
但它仅在叶级别返回 tot_hours。 关于如何仅使用 d3.nest 解决此问题的任何建议?
最佳答案
来自文档:
nest.rollup(function)
Specifies a rollup function to be applied on each group of leaf elements. The return value of the rollup function will replace the array of leaf values in either the associative array returned by the map operator, or the values attribute of each entry returned by the entries operator.
如您所见,汇总适用于叶元素。您可以通过在多个级别嵌套数据来绕过此问题:
function nest(keys, data, rollupFunc) {
var nst = d3.nest();
keys.forEach(function(key) {
nst.key(function(d) { return d[key]; });
});
if (rollupFunc) {
nst.rollup(rollupFunc);
}
return nst.entries(data);
}
var rollupFunction = function(d) {
return {
"total_hours": d3.sum(d, function(dd) { return dd["hours"]})
}
}
var rez1 = nest(["project", "resource"], actuals);
var rez2 = nest(["project"], actuals, rollupFunction);
var rez3 = nest(["project", "resource"], actuals, rollupFunction);
但这对于较大的数据集来说效率很低。否则我会建议使用 nest()
函数来创建所有中间级别。然后,您可以使用自己的递归函数汇总总小时数。伪代码:
function aggregate(node) {
if (node has property total_hours) {
return total_hours
}
sum = 0
foreach child in data.values {
sum += aggregate(child)
}
node.total_hours = sum
return node.total_hours
}
关于javascript - 具有多个键的嵌套运算符的 D3.js 汇总,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13185608/