Published
Edited
Feb 16, 2019
15 stars
Insert cell
Insert cell
chart = {
const root = pack(data);

const svg = d3.select(DOM.svg(width, height))
.style("font", "10px sans-serif")
.style("width", "100%")
.style("height", "auto")
.attr("text-anchor", "middle");

const node = svg.selectAll("g")
.data(root.descendants())
.join("g")
.attr("transform", d => `translate(${d.x + 1},${d.y + 1})`)
.each(function(d) { d.node = this; })
.on("mouseover", hovered(true))
.on("mouseout", hovered(false));

node.append("circle")
.attr("r", d => d.r)
.attr("fill", d => d.children ? "none" : "#ddd")
.attr("stroke", d => d.height === 1 ? "#ccc" : "none")
.attr("pointer-events", "all");

const leaf = node.filter(d => !d.children && d.data.name);
leaf.select("circle")
.attr("id", d => (d.leafUid = DOM.uid("leaf")).id);

leaf.append("clipPath")
.attr("id", d => (d.clipUid = DOM.uid("clip")).id)
.append("use")
.attr("xlink:href", d => d.leafUid.href);

leaf.append("text")
.style("font-size", d => `${Math.sqrt(d.r) * 2}px`)
.attr("clip-path", d => d.clipUid)
.selectAll("tspan")
.data(d => d.data.name.split(/(?=[A-Z][^A-Z])/g))
.join("tspan")
.attr("x", 0)
.attr("y", (d, i, nodes) => `${i - nodes.length / 2 + 0.8}em`)
.text(d => d);

node.append("title")
.text(d => `${d.data.name || "N/A"}${d.children ? "" : `
${d.parent.data.name}`}
${format(d.value)}`);

function hovered(hover) {
return d => d3.selectAll(d.ancestors().map(d => d.node))
.select("circle")
.attr("stroke", hover ? "black" : d => d.height === 1 ? "#ccc" : "none");
}

return svg.node();
}
Insert cell
data = d3.json("https://gist.githubusercontent.com/mbostock/3cba6ac2fac09e5483bf6c1fade733be/raw/2bfb86aee2ca8311202b9a2cd644421a72eb11a1/authors.json")
Insert cell
pack = data => d3.pack()
.size([width - 2, height - 2])
.padding(3)
(d3.hierarchy(data)
.each(d => { if (/^other[0-9]+$/.test(d.data.name)) d.data.name = null; })
.sum(d => d.size)
.sort((a, b) => b.value - a.value))
Insert cell
width = 975
Insert cell
height = width
Insert cell
format = d3.format(",d")
Insert cell
d3 = require("d3@5")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more