D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
pmariac
Full window
Github gist
simple tree
Built with
blockbuilder.org
<!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": "1", "children": [ {"name": "11", "children": [ {"name": "111", "size": 1}, {"name": "112", "size": 1}, {"name": "113", "size": 1}, {"name": "114", "children": [ {"name": "1141", "size": 1}, {"name": "1142", "size": 1}] }] }, {"name": "12", "children": [ {"name": "121", "children": [ {"name": "1211", "size": 1}, {"name": "1212", "size": 1}] }, {"name": "122", "size": 1}] }] }; // set the dimensions and margins of the diagram var width = 500, height = 400; // 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); // append the svg obgect to the body of the page // appends a 'group' element to 'svg' // moves the 'group' element to the top left margin var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height), g = svg.append("g"); // 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.x + "," + d.y + "C" + d.x + "," + (d.y + d.parent.y) / 2 + " " + d.parent.x + "," + (d.y + d.parent.y) / 2 + " " + d.parent.x + "," + d.parent.y; }); // adds each node as a group 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 + ")"; }); // adds the circle to the node node.append("circle") .attr("r", 10); // adds the text to the node node.append("text") .attr("dy", ".35em") .attr("y", function(d) { return d.children ? -20 : 20; }) .style("text-anchor", "middle") .text(function(d) { return d.data.name; }); </script> </body>
https://d3js.org/d3.v4.min.js