Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Last active July 21, 2017 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timelyportfolio/612c434485cfccddfa15049bbeb099c9 to your computer and use it in GitHub Desktop.
Save timelyportfolio/612c434485cfccddfa15049bbeb099c9 to your computer and use it in GitHub Desktop.
generalized aggregate for hierarchy
license: mit
height: 200
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<pre id="results"></pre>
<script>
var data = {
name: 'root',
children: [
{
name: 'A',
children: [
{name: 'A1', x:1},
{name: 'A2', x:10}
]
},
{
name: 'B',
children: [
{name: 'B1', x:50},
{name: 'B2', x:-3},
{name: 'B3', x:100}
]
},
]
}
var root = d3.hierarchy(data);
function aggregate(f, valuef, name) {
return this.eachAfter(function(node) {
var children = node.children,
values;
if(children && children.length) {
values = children.map(function(d){return d[name]});
} else {
values = [valuef(node)];
}
var agg = f(values);
node[name] = agg;
});
}
console.log(
aggregate.call(root,d3.max,function(d){return d.data.x},'max')
);
var results = [];
root.eachBefore(function(d){results.push(d.data.name + ' max:' + d.max)});
d3.select('#results').text(
results.join('\n')
);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment