我希望将 csv 文件转换为特定的 JSON 格式以进行 D3.js 可视化。基本思想是在每个级别同时嵌套和汇总。换句话说,结构中每一层的 parent 都将包含其 child 的总和。
示例 csv 文件如下:
Country,State,City,Population,
"USA","California","Los Angeles",18500000,
"USA","California","San Diego",1356000,
"USA","California","San Francisco",837442,
"USA","Texas","Austin",885400,
"USA","Texas","Dallas",1258000,
"USA","Texas","Houston",2196000
我希望创建的 JSON 格式如下:
[
{
key: "USA",
Population: 25032842,
values: [
{
key: "California",
Population: 20693442,
values: [
{
key: "Los Angeles",
Population: 18500000
},
{
key: "San Diego",
Population: 1356000
},
{
key: "San Francisco",
Population: 837442
}
]
},
{
key: "Texas",
Population: 4339400,
values: [
{
key: "Austin",
Population: 885400
},
{
key: "Dallas",
Population: 1258000
},
{
key: "Houston",
Population: 2196000
}
]
}
]
}
]
最佳答案
注意:这仅适用于 D3 v3。新版本 4 中情况略有变化,在访问汇总的返回值时需要进行一些调整。 "D3.js nesting and rollup at the same time in v4" 涵盖了这一点.
<小时/>D3 没有内置功能来完成您正在寻找的功能。使用nest.rollup()
将 trim 所有子节点,以用该函数的返回值替换它们。但是,编写一个小辅助函数可以通过两个步骤轻松完成:
使用
d3.nest()准备嵌套数据结构
:var nested = d3.nest() .key(function(d) { return d.Country; }) .key(function(d) { return d.State; }) .rollup(function(cities) { return cities.map(function(c) { return {"City": c.City, "Population": +c.Population }; }); }) .entries(data);
循环遍历所有顶级节点以递归计算总和 所有 child 。
// Recursively sum up children's values function sumChildren(node) { node.Population = node.values.reduce(function(r, v) { return r + (v.values ? sumChildren(v) : v.Population); },0); return node.Population; } // Loop through all top level nodes in nested data, // i.e. for all countries. nested.forEach(function(node) { sumChildren(node); });
这将为您提供所需的输出。请查看以下代码片段以了解其实际效果。
// Initialization
var csv = 'Country,State,City,Population\n' +
'"USA","California","Los Angeles",18500000\n' +
'"USA","California","San Diego",1356000\n' +
'"USA","California","San Francisco",837442\n' +
'"USA","Texas","Austin",885400\n' +
'"USA","Texas","Dallas",1258000\n' +
'"USA","Texas","Houston",2196000\n';
var data = d3.csv.parse(csv);
// Nesting the input using d3.nest()
var nested = d3.nest()
.key(function(d) { return d.Country; })
.key(function(d) { return d.State; })
.rollup(function(cities) {
return cities.map(function(c) {
return {"City": c.City, "Population": +c.Population };
});
})
.entries(data);
// Recursively sum up children's values
function sumChildren(node) {
node.Population = node.values.reduce(function(r, v) {
return r + (v.values ? sumChildren(v) : v.Population);
},0);
return node.Population;
}
// Loop through all top level nodes in nested data,
// i.e. for all countries.
nested.forEach(function(node) {
sumChildren(node);
});
// Output. Nothing of interest below this line.
d3.select("body").append("div")
.style("font-family", "monospace")
.style("white-space", "pre")
.text(JSON.stringify(nested,null,2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
关于javascript - D3.js 同时嵌套和汇总,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34804507/