Skip to content

Instantly share code, notes, and snippets.

Created March 6, 2017 20:07
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 anonymous/9c1c28f2f865b8d616448eb12ad51e06 to your computer and use it in GitHub Desktop.
Save anonymous/9c1c28f2f865b8d616448eb12ad51e06 to your computer and use it in GitHub Desktop.
Simple vertical tree diagram using v4
license: mit

This is a simple vertical tree diagram written with d3.js v4.

This is designed to be used as a starting point for further development as part of documenting an update to the book D3 Tips and Tricks to version 4 of d3.js.

forked from d3noob's block: Simple vertical tree diagram using v4

forked from anonymous's block: Simple vertical tree diagram using v4

forked from anonymous's block: Simple vertical tree diagram using v4

forked from anonymous's block: Simple vertical tree diagram using v4

forked from anonymous's block: Simple vertical tree diagram using v4

<!DOCTYPE html>
<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>
var treeData =
{
name: "malmö-trelleborg",
children: [
{ name: 'trelleborg-göteborg',
children: [
{ name: 'göteborg-skövde' },
{ name: 'trelleborg-gais' },
]
},
{ name: 'malmö-gais' }
]
};
// set the dimensions and margins of the diagram
var margin = {top: 40, right: 90, bottom: 50, left: 90},
width = 660 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// declares a tree layout and assigns the size
var treemap = d3.tree()
.size([width, height]);
// assigns the data to a hierarchy using parent-child relationships
var nodes = d3.hierarchy(treeData);
// maps the node data to the tree layout
nodes = treemap(nodes);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
var g = svg.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// adds the links between the nodes
var link = g.selectAll(".link")
.data( nodes.descendants().slice(1))
.enter().append("path")
.attr("class", "link")
.attr("d", function(d) {
return "M" + d.y + "," + d.x
+ "C" + (d.parent.y + d.y) / 2 + "," + d.x
+ " " + (d.parent.y + d.y) / 2 + "," + d.parent.x
+ " " + d.parent.y + "," + d.parent.x;
});
// adds each node as a group
var node = g.selectAll(".node")
.data(nodes.descendants())
.enter().append("circle")
.attr("class", "node")
.attr("r", 4.5)
.attr("cx", o => o.y)
.attr("cy", o => o.x);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment