Published
Edited
Jun 23, 2020
Insert cell
Insert cell
chart = {
const nodes = root.descendants();

const svg = d3.create("svg")
.attr("viewBox", [-nodeSize / 2, -nodeSize * 3 / 2, width, (nodes.length + 1) * nodeSize])
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.style("overflow", "visible");

const link = svg.append("g")
.attr("fill", "none")
.attr("stroke", "#999")
.selectAll("path")
.data(root.links())
.join("path")
.attr("d", d => `
M${d.source.depth * nodeSize},${d.source.index * nodeSize}
V${d.target.index * nodeSize}
h${nodeSize}
`);

const node = svg.append("g")
.selectAll("g")
.data(nodes)
.join("g")
.attr("transform", d => `translate(0,${d.index * nodeSize})`);

node.append("circle")
.attr("cx", d => d.depth * nodeSize)
.attr("r", 2.5)
.attr("fill", d => d.children ? null : "#999");

node.append("text")
.attr("dy", "0.32em")
.attr("x", d => d.depth * nodeSize + 6)
.text(d => d.data.name);

node.append("title")
.text(d => d.ancestors().reverse().map(d => d.data.name).join("/"));

for (const {label, value, format, x} of columns) {
svg.append("text")
.attr("dy", "0.32em")
.attr("y", -nodeSize)
.attr("x", x)
.attr("text-anchor", "end")
.attr("font-weight", "bold")
.text(label);

node.append("text")
.attr("dy", "0.32em")
.attr("x", x)
.attr("text-anchor", "end")
.attr("fill", d => d.children ? null : "#555")
.data(root.copy().sum(d => d.topics ? 0 : d.value).descendants())
.text(d => format(d.value, d));
}

return svg.node();
}
Insert cell
columns = [
{
label: "Count",
value: d => d.value,
format,
x: 280
},
]
Insert cell
format = d3.format(",d")
Insert cell
topicsFileData = FileAttachment("topics.json").text()
Insert cell
data = JSON.parse(('{"label": "Constitute", "topics": ' + topicsFileData + '}').replace(/"label"/g, '"name"').replace(/"count"/g, '"value"'))
Insert cell
root = { let i = 0;
return d3.hierarchy(data, d => d.topics).eachBefore(d => d.index = i++); }


Insert cell
nodeSize = 17
Insert cell
d3 = require("d3@5")
Insert cell
d3plus = require('d3plus/d3plus.full.js')
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