Public
Edited
Jun 10
Insert cell
Insert cell
chart = {
const root = d3.hierarchy(data);
const treeLayout = d3.tree().nodeSize([150, 100]);
treeLayout(root);

const nodes = root.descendants();
const links = root.links();

// Compute horizontal layout bounds
const minX = d3.min(nodes, d => d.x);
const maxX = d3.max(nodes, d => d.x);
const minY = d3.min(nodes, d => d.y);
const maxY = d3.max(nodes, d => d.y);

const svgWidth = width;
const svgHeight = maxY + 200;
const margin = { top: 40, right: 80, bottom: 40, left: 80 };
const xOffset = (svgWidth - (maxX - minX)) / 2;

const svg = d3.create("svg")
.attr("viewBox", [minX - xOffset - margin.left, -margin.top, svgWidth + margin.left + margin.right, svgHeight + margin.top + margin.bottom])
.attr("width", svgWidth)
.attr("height", svgHeight)
.style("font", "14px sans-serif");

// Draw links
svg.append("g")
.attr("fill", "none")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.8)
.attr("stroke-width", 1.5)
.selectAll("path")
.data(links)
.join("path")
.attr("d", d3.linkVertical()
.x(d => d.x)
.y(d => d.y));

// Draw nodes
const nodeGroup = svg.append("g")
.selectAll("g")
.data(nodes)
.join("g")
.attr("transform", d => `translate(${d.x},${d.y})`);

nodeGroup.append("rect")
.attr("x", -70)
.attr("y", -20)
.attr("width", 140)
.attr("height", 40)
.attr("rx", 10)
.attr("fill", "white")
.attr("stroke", "white");

nodeGroup.append("text")
.attr("dy", "-0.4em")
.attr("text-anchor", "middle")
.style("font-weight", "bold")
.text(d => d.data.name);

nodeGroup.append("text")
.attr("dy", "0.9em")
.attr("text-anchor", "middle")
.style("font-size", "12px")
.style("fill", "#666")
.text(d => d.data.position ?? "");

return svg.node();
};
Insert cell
diagonal = d3.linkVertical().x(d => d.x).y(d => d.y)
Insert cell
//tree = d3.tree().nodeSize([dx, dy])
Insert cell
Insert cell
height = 430 - margin.top - margin.bottom;
Insert cell
margin = ({top: 20, right: 10, bottom: 10, left: 10})
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