Built with blockbuilder.org
Last active
July 21, 2017 13:40
-
-
Save timelyportfolio/612c434485cfccddfa15049bbeb099c9 to your computer and use it in GitHub Desktop.
generalized aggregate for hierarchy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit | |
height: 200 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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