Skip to content

Instantly share code, notes, and snippets.

@dagrende
Created February 27, 2016 19:48
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 dagrende/d6def641dc7ec17ab092 to your computer and use it in GitHub Desktop.
Save dagrende/d6def641dc7ec17ab092 to your computer and use it in GitHub Desktop.
create d3 element hierarchy from flat data
<!DOCTYPE html>
<meta charset="utf-8">
<style>
rect, circle {
fill: none;
stroke: black;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4.5.1/lodash.min.js"></script>
<script>
var margin = {top: 10, right: 30, bottom: 30, left: 30},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// flat data with hierarchy expressed by parent attribute
var data = [
{type: 'a', id: '1'},
{type: 'b', id: '2', parent: '1'},
{type: 'a', id: '3', parent: '2'},
{type: 'b', id: '4', parent: '2'},
{type: 'b', id: '5', parent: '1'},
];
function createNodes(parentEl, data, parentId) {
var childData = _.filter(data, d => (parentId == d.parent));
var childDataByType = _.groupBy(childData, 'type');
_.forEach(childDataByType, (typeData, type) => {
var nodes = {'a': createANodes, 'b': createBNodes}[type](parentEl, typeData);
nodes.each(function(d) {
createNodes(d3.select(this), data, d.id);
});
});
}
createNodes(svg, data, undefined);
function createANodes(parentEl, data) {
var nodes = parentEl.selectAll('.a').data(data).enter().append('g')
.attr('class', 'a');
nodes.append('rect')
.attr('width', 50)
.attr('height', 30);
return nodes;
}
function createBNodes(parentEl, data) {
var nodes = parentEl.selectAll('.b').data(data).enter().append('g')
.attr('class', 'b');
nodes.append('circle')
.attr('cx', 25)
.attr('cy', 15)
.attr('r', 20);
return nodes;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment