JSFiddle - React, Tailwind, and code Playground
by lchau
CSS
path, circle {
stroke:black;
fill:none;
}
JavaScript
var arrays = [
[1, 2, 3, 4, 5],
[1, 2, 6, 4, 5],
[1, 3, 6, 4, 5],
[1, 2, 3, 6, 5],
[1, 7, 5],
[1, 7, 3, 5]
];
// Each array describes a path from the root
// to a unique leaf, via named labels (here integers)
var root = {},
path, node, next, i, j, N, M;
for (i = 0, N = arrays.length; i < N; i++) {
// for each path in the data array
path = arrays[i];
node = root; // start the path from the root
for (j = 0, M = path.length; j < M; j++) {
// follow the path through the tree
// creating new nodes as necessary
if (!node.children) {
// undefined, so create it:
node.children = {};
// children is defined as an object
// (not array) to allow named keys
}
next = node.children[path[j]];
// find the child node whose key matches
// the label of this step in the path
if (!next) {
// undefined, so create
next = node.children[path[j]] = {
label: path[j]
};
}
node = next;
// step down the tree before analyzing the
// next step in the path.
}
}
// console.log(root);
// In order to use the root object in a d3 tree
// layout,you'll need to specify a child accessor
// function that turns the children object into
// a children array, e.g. using the d3.values() function:
// (Graphing code from http:// bl.ocks.org/mbostock/4063570 )
var height = 500,
width = 600;
var cluster = d3.layout.cluster()
.size([height, width - 100])
.children(function children(d) {
// get children as an array:
return d3.values(d.children);
// you could add in a sort if you wanted
// the nodes returned in numerical order
});
var diagonal = d3.svg.diagonal()
.projection(function (d) {
return [d.y, d.x];
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
...