D3.js同时嵌套和汇总

时间:2016-01-15 04:39:16

标签: javascript json csv d3.js

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

示例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
          }
        ]
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:1)

注意:这仅适用于D3 v3 。新版本4的情况略有改变,在访问汇总的返回值时需要稍加调整。这由"D3.js nesting and rollup at the same time in v4"涵盖。

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);
    });
    
  3. 这将为您提供所需的输出。请查看以下代码段,了解它的实际效果。

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