Skip to content

Instantly share code, notes, and snippets.

@dagrende
Last active 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/a4ff24a0fee74ee026d8 to your computer and use it in GitHub Desktop.
Save dagrende/a4ff24a0fee74ee026d8 to your computer and use it in GitHub Desktop.
create d3 element hierarchy from hierarcic 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 + ")");
// hierarchical data
var data = [
{type: 'a',
children: [
{type: 'b',
children: [
{type: 'a'},
{type: 'b'}
]
},
{type: 'b'}
]
}
];
function createNodes(parentEl, data) {
var dataByType = _.groupBy(data,'type');
_.forEach(dataByType, (typeData, type) => {
var nodes = {'a': createANodes, 'b': createBNodes}[type](parentEl, typeData);
nodes.each(function(d) {
createNodes(d3.select(this), d.children);
});
});
}
createNodes(svg, data);
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