D3.js同时嵌套和汇总

D3.js nesting and rollup at same time

本文关键字:嵌套 js D3      更新时间:2023-09-26

我希望将csv文件转换为特定的JSON格式,以进行D3.js可视化。 基本思想是在每个级别同时嵌套和汇总。 换句话说,结构中每个级别的父母都将包含他们孩子的总和。

示例 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 的情况略有变化,在访问汇总的返回值时需要稍作调整。这在 v4 中同时嵌套和汇总的"D3.js"中有所介绍。


D3 没有内置函数来执行您正在寻找的操作。使用 nest.rollup() 将修剪所有子节点,以将它们替换为此函数的返回值。但是,编写一个小的辅助函数可以通过两个步骤轻松完成:

  1. 使用 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);
    
  2. 遍历所有顶级节点以递归计算总和所有儿童。

    // 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>