Skip to content

Instantly share code, notes, and snippets.

@d3byex
Last active November 29, 2015 02:10
Show Gist options
  • Save d3byex/17c624d8d2be63f65e88 to your computer and use it in GitHub Desktop.
Save d3byex/17c624d8d2be63f65e88 to your computer and use it in GitHub Desktop.
D3byEX 10.4: Tree Diagram
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="D3byEX 10.4" />
<meta charset="utf-8">
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var url = 'https://gist.githubusercontent.com/d3byex/25129228aa50c30ef01f/raw/c1c3ad9fa745c42c5410fba29cefccac47cd0ec7/familytree.json';
d3.json(url, function (error, data) {
var width = 960, height = 500,
nodeRadius = 10,
margin = {
left: 50, top: 10,
bottom: 10, right: 40
};
var svg = d3.select('body')
.append('svg')
.attr({
width: width,
height: height
});
var mainGroup = svg.append('g')
.attr('transform', 'translate(' + margin.left + ',' +
margin.top + ')');
var tree = d3.layout.tree()
.size([
height - (margin.bottom + margin.top),
width - (margin.left + margin.right),
]);
var nodes = tree.nodes(data);
var links = tree.links(nodes);
var diagonal = d3.svg.diagonal()
.projection(function (d) {
return [d.y, d.x];
});
mainGroup.selectAll('path')
.data(links)
.enter()
.append('path', 'g')
.attr({
'd': diagonal,
fill: 'none',
stroke: '#ccc',
'stroke-width': 2
});
var circleGroups = mainGroup.selectAll('g')
.data(nodes)
.enter()
.append('g')
.attr('transform', function (d) {
return 'translate(' + d.y + ',' + d.x + ')';
});
circleGroups.append('circle')
.attr({
r: nodeRadius,
fill: '#fff',
stroke: 'steelblue',
'stroke-width': 3
});
circleGroups.append('text')
.text(function (d) {
return d.name;
})
.attr('y', function (d) {
return d.children || d._children ?
-nodeRadius * 2 : nodeRadius * 2;
})
.attr({
dy: '.35em',
'text-anchor': 'middle',
'fill-opacity': 1
})
.style('font', '12px sans-serif');
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment