Published
Edited
Sep 21, 2020
2 forks
1 star
Insert cell
Insert cell
chart = {
const root = tree(data);

const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height ]);
const g = svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.attr("transform", `translate(${width/2},${0.1*height})`);
const link = g.append("g")
.attr("fill", "none")
.attr("stroke", "#555")
.attr("stroke-opacity", 0.4)
.attr("stroke-width", 1.5)
.selectAll("path")
.data(root.links())
.join("path")
.attr("d", d3.linkVertical()
.x(d => d.x)
.y(d => d.y));
const node = g.append("g")
.attr("stroke-linejoin", "round")
.attr("stroke-width", 3)
.selectAll("g")
.data(root.descendants())
.join("g")
.attr("transform", d => `translate(${d.x},${d.y})`);

node.append("rect")
.attr("fill", d => d.children ? "#555" : "#999")
.attr("width", root.dx * 0.9)
.attr("height", root.dx* 0.6)
.attr("transform", d => `translate(${-root.dx*0.45},${-root.dy*0.3})`);

// node.append("text")
// .attr("dy", "0.31em")
// .attr("x", d => d.children ? -6 : 6)
// .attr("text-anchor", d => d.children ? "end" : "start")
// .text(d => d.data.name)
// .clone(true).lower()
// .attr("stroke", "white");
return svg.node();
}
Insert cell
data = ({name: "Test1", children:[{name:"test2", children:[{name:"test2" },{name:"test2"},{name:"test3",children:[{name:"test2"},{name:"test3"}]}]},{name:"test2", children:[{name:"test2", children:[{name:"test2" },{name:"test2"},{name:"test3",children:[{name:"test2"},{name:"test3"}]}]},{name:"test2"},{name:"test3",children:[{name:"test2"},{name:"test3"}]}]},{name:"test3",children:[{name:"test2"},{name:"test3"}]}]})
Insert cell
tree = data => {
const root = d3.hierarchy(data);
// compute the new height
var levelWidth = [1];
var childCount = function(level, n) {

if(n.children && n.children.length > 0) {
if(levelWidth.length <= level + 1) levelWidth.push(0);

levelWidth[level+1] += n.children.length;
n.children.forEach(function(d) {
childCount(level + 1, d);
});
}
};
childCount(0, root);
var newWidth = d3.max(levelWidth); // 20 pixels per line
root.dx = 0.8*width / newWidth
root.dy = 0.8* height / (root.height)
// root.eWidth = width
root.newWidth = newWidth
return d3.tree().nodeSize([root.dx, root.dy])(root);
}
Insert cell
height = 100;

Insert cell
width = 100;
Insert cell
d3.hierarchy(data)
Insert cell
d3 = require("d3@6")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more