汇总D3中的物品?

时间:2015-10-15 19:22:16

标签: javascript d3.js

假设我假设我有一个像这样的json数组:

[{"country":"Argentina", "impressions":199}, 
{"country":"Peru", "impressions":100}, 
{"country":"Brazil", "impressions":500} 
{"country":"Argentina", "impressions":201}, 
{"country":"Peru", "impressions":504},]

我希望使用D3.js创建一个表,其中每个国家/地区仅列出一次。 D3中的SQL中是否有类似“select distinct”的东西?我已经拥有了该表的所有代码,并且它生成了一个表,它完全按照上面的显示布局我的数据,但我需要汇总数据。

感谢你们给我的任何帮助!

1 个答案:

答案 0 :(得分:0)

- d3.nest with a rollup -

var nested_data = d3.nest()
  .key(function(d) {
    return d.country;
  })
  .rollup(function(o){
    return d3.sum(o,function(d){
      return d.impressions;
    });
  })
  .entries(data);

返回:

enter image description here

完整的工作代码:



<!DOCTYPE html>
<html>

<head>
  <script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
</head>

<body>
  <script>
    var data = [{
      "country": "Argentina",
      "impressions": 199
    }, {
      "country": "Peru",
      "impressions": 100
    }, {
      "country": "Brazil",
      "impressions": 500
    }, {
      "country": "Argentina",
      "impressions": 201
    }, {
      "country": "Peru",
      "impressions": 504
    }];

    var nested_data = d3.nest()
      .key(function(d) {
        return d.country;
      })
      .rollup(function(o){
        return d3.sum(o,function(d){
          return d.impressions;
        });
      })
      .entries(data);
      
    d3.select('body').html(JSON.stringify(nested_data));
  </script>
</body>

</html>
&#13;
&#13;
&#13;