D3.js同时嵌套和汇总 [英] D3.js nesting and rollup at same time

查看:132
本文介绍了D3.js同时嵌套和汇总的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking to convert a csv file into a particular JSON format for a D3.js visualization. The basic idea is to simultaneously nest and rollup at each level. In other words, parents at every level in the structure would contain the sum of their children.

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

希望创建如下:

[
  {
    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在v4中同时嵌套和汇总 涵盖。

Note: This will only work for D3 v3. Things have changed slightly with the new version 4, which requires a little adjustment when accessing the rollup's return value. This is covered by "D3.js nesting and rollup at the same time in v4".

D3没有内置函数来做你正在寻找的东西。使用 nest.rollup()将删除所有子节点,以使用此函数的返回值替换它们。但是,编写一个小助手函数,可以通过两个步骤轻松完成:

D3 has no built-in function to do what you are looking for. Using nest.rollup() will prune all child nodes to replace them with this function's return value. However, writing a small helper function this can easily be done in two steps:


  1. 使用<$ c准备嵌套数据结构$ c> 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);


  • 循环浏览所有顶级节点,递归计算所有子项的总和

  • Loop through all top level nodes to recursively calculate the sums of all children.

    // 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);
    });
    


  • 这将精确地显示所需的输出。请查看以下代码段以查看其操作。

    This will give you exactely the desired output. Have a look at the following snippet to see it in action.

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

    这篇关于D3.js同时嵌套和汇总的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆