This is a tree diagram with styling applied to the nodes and links written with d3.js v4. It is based on the simple horizontal version here
This is designed to be used as part of documenting an update to the book D3 Tips and Tricks to version 4 of d3.js.
forked from d3noob's block: Tree diagram with styling in v4
xxxxxxxxxx
<meta charset="utf-8">
<style> /* set the CSS */
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text { font: 12px sans-serif; }
.node--internal text {
text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
</style>
<body>
<!-- load the d3.js library -->
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
// set the dimensions and margins of the diagram
var margin = {top: 20, right: 90, bottom: 30, left: 90},
width = 1000 - margin.left - margin.right,
height = 600 - margin.top - margin.bottom;
// declares a tree layout and assigns the size
var treemap = d3.tree()
.size([height, width])
d3.json("task.json", function(error, graph) {
console.log("treeData",graph)
var nodes = d3.hierarchy(graph)
nodes = treemap(graph)
// nodes.each(function(d) {
// d.y = d.depth * 100
// })
console.log('nodes', nodes)
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom),
g = svg.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
console.log('svg', svg)
const line = d3.line().curve(d3.curveBasis);
var link = g.selectAll(".link")
.data( nodes.descendants().slice(1))
.enter().append("path")
.attr("class", "link")
.style("stroke", function(d) { return d.data.level; })
.attr("d", function(d) {
return line([
[d.x, d.y],
[d.x, (d.y + d.parent.y) / 2],
[d.parent.x, (d.y + d.parent.y) / 2],
[d.parent.x, (d.parent.y)]
])
});
var node = g.selectAll(".node")
.data(nodes.descendants())
.enter().append("g")
.attr("class", function(d) {
return "node" +
(d.children ? " node--internal" : " node--leaf"); })
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; });
node.append("circle")
.attr("r", 9)
.style("stroke", function(d) { return d.data.type; })
.style("fill", function(d) { return d.data.level; });
// node.append("text")
// .attr("dy", ".35em")
// .attr("x", function(d) { return d.children ?
// (d.data.value + 4) * -1 : d.data.value + 4 })
// .style("text-anchor", function(d) {
// return d.children ? "end" : "start"; })
// .text(function(d) { return d.data.name; });
});
</script>
</body>
https://d3js.org/d3.v4.min.js