Tree layout.
Last active
October 9, 2017 07:56
-
-
Save SevenChan07/e0c065c4f8a2285625af434ce8520f05 to your computer and use it in GitHub Desktop.
Tree Layout I
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: gpl-3.0 | |
height: 700 |
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> | |
<meta charset="utf-8"> | |
<style> | |
body { | |
padding: 20px | |
} | |
.node circle { | |
fill: #fff; | |
stroke: steelblue; | |
stroke-width: 3px; | |
} | |
.link { | |
fill: none; | |
stroke: #ccc; | |
stroke-width: 2px; | |
} | |
</style> | |
<body> | |
<script src="//d3js.org/d3.v4.min.js"></script> | |
<script> | |
const height = 700 | |
const width = 960 | |
const margin = {top: 20, right: 90, bottom: 30, left: 90} | |
const svg = d3.select('body') | |
.append('svg') | |
.attr('width', width) | |
.attr('height', height) | |
.append("g") | |
.attr("transform", "translate(" | |
+ margin.left + "," + margin.top + ")") | |
var data = { | |
"name": "0-0", | |
"children": [ | |
{ | |
"name": "1-0", | |
"children": [ | |
{ | |
"name": "2-0" | |
}, | |
{ | |
"name": "2-1" | |
} | |
] | |
}, | |
{ | |
"name": "1-1" | |
}, | |
{ | |
"name": "1-2" | |
} | |
] | |
} | |
const treemap = d3.tree().size([height, width]) | |
let root = d3.hierarchy(data, d => d.children) | |
root.x0 = height / 2 | |
root.y0 = 0 | |
const treeData = treemap(root) | |
const nodes = treeData.descendants() | |
const links = treeData.descendants().slice(1) | |
treeData.descendants().forEach(d => d.y = d.depth * 180) | |
// the node position | |
const node = svg.selectAll('g.node') | |
.data(treeData.descendants()) | |
.enter() | |
.append('g') | |
.attr('class', 'node') | |
.attr('transform', e => { | |
return `translate(${e.y},${e.x+15})` | |
}) | |
// append circle | |
node.append('circle') | |
.attr('class', 'node') | |
.attr('r', 10) | |
// Creates a curved (diagonal) path from parent to the child nodes | |
function diagonal(s, d) { | |
path = `M ${s.y} ${s.x + 15} | |
C ${(s.y + d.y) / 2} ${s.x + 15}, | |
${(s.y + d.y) / 2} ${d.x + 15}, | |
${d.y} ${d.x + 15}` | |
return path | |
} | |
// create link | |
const link = svg.selectAll('path.link') | |
.data(links) | |
// the link path | |
const linkEnter = link.enter() | |
.insert('path', "g") | |
.attr("class", "link") | |
.attr('d', function(d){ return diagonal(d, d.parent) }) | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment