Created
November 10, 2017 17:13
-
-
Save valex/8ebb52034eeb1c866a159739181d1604 to your computer and use it in GitHub Desktop.
Horizontal tree diagram, d3.js version 4
This file contains hidden or 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> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<script src="http://d3js.org/d3.v4.min.js"></script> | |
<script src="https://d3js.org/d3-selection-multi.v1.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') | |
.attrs({ | |
width: width, | |
height: height | |
}); | |
var mainGroup = svg.append('g') | |
.attr('transform', 'translate(' + margin.left + ',' + | |
margin.top + ')'); | |
var tree = d3.tree() | |
.size([ | |
height - (margin.bottom + margin.top), | |
width - (margin.left + margin.right), | |
]); | |
// assigns the data to a hierarchy using parent-child relationships | |
var nodes = d3.hierarchy(data, function(d) { | |
return d.children; | |
}); | |
nodes = tree(nodes); | |
var linksGenerator = d3.linkHorizontal() // d3.linkVertical() | |
.source(function(d) {return [d.parent.y, d.parent.x];}) | |
.target(function(d) {return [d.y, d.x];}); | |
mainGroup.selectAll('path') | |
.data(nodes.descendants().slice(1)) | |
.enter() | |
.append('path') | |
.attrs({ | |
d: linksGenerator, | |
fill: 'none', | |
stroke: '#ccc' | |
}); | |
var circleGroups = mainGroup.selectAll('g') | |
.data(nodes.descendants()) | |
.enter() | |
.append('g') | |
.attr('transform', function (d) { | |
return 'translate(' + d.y + ',' + d.x + ')'; | |
}); | |
circleGroups.append('circle') | |
.attrs({ | |
r: nodeRadius, | |
fill: '#fff', | |
stroke: 'steelblue', | |
'stroke-width': 3 | |
}); | |
circleGroups.append('text') | |
.text(function (d) { | |
return d.data.name; | |
}) | |
.attr('y', function (d) { | |
return d.children || d._children ? | |
-nodeRadius * 2 : nodeRadius * 2; | |
}) | |
.attrs({ | |
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