Published
Edited
Jun 19, 2021
Insert cell
Insert cell
Insert cell
chart = {
const treemap = d3.treemap()
.tile(d3.treemapResquarify)
.size([width, height])
.padding(d => d.height === 1 ? 1 : 0)
.round(true);

// Compute the structure using the average value.
const root = treemap(d3.hierarchy(data.group)
.sum(d => Array.isArray(d.values) ? d3.sum(d.values) : 0)
.sort((a, b) => b.value - a.value));

const svg = d3.create("svg")
.attr("viewBox", `0 -20 ${width} ${height + 20}`)
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.style("overflow", "visible");

const box = svg.append("g")
.selectAll("g")
.data(data.keys.map((key, i) => {
const value = root.sum(d => d.values[i]).value;
return {key, value, i, k: Math.sqrt(value / max)};
}).reverse())
.join("g")
.attr("transform", ({k}) => `translate(${(1 - k) / 2 * width},${(1 - k) / 2 * height})`)
.attr("opacity", ({i}) => i >= viewof index.value ? 1 : 0)
.call(g => g.append("text")
.attr("y", -6)
.attr("fill", "#777")
.selectAll("tspan")
.data(({key, value}) => [key, ` ${formatNumber(value)}`])
.join("tspan")
.attr("font-weight", (d, i) => i === 0 ? "bold" : null)
.text(d => d))
.call(g => g.append("rect")
.attr("fill", "none")
.attr("stroke", "#ccc")
.attr("width", ({k}) => k * width)
.attr("height", ({k}) => k * height));

const leaf = svg.append("g")
.selectAll("g")
.data(layout(viewof index.value))
.join("g")
.attr("transform", d => `translate(${d.x0},${d.y0})`);

leaf.append("rect")
.attr("id", d => (d.leafUid = DOM.uid("leaf")).id)
.attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data[0]); })
.attr("width", d => d.x1 - d.x0)
.attr("height", d => d.y1 - d.y0);

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

leaf.append("text")
.attr("clip-path", d => d.clipUid)
.selectAll("tspan")
.data(d => [d.data.name, formatNumber(d.value)])
.join("tspan")
.attr("x", 3)
.attr("y", (d, i, nodes) => `${(i === nodes.length - 1) * 0.3 + 1.1 + i * 0.9}em`)
.attr("fill-opacity", (d, i, nodes) => i === nodes.length - 1 ? 0.7 : null)
.text(d => d);

leaf.append("title")
.text(d => d.data.name);

function layout(index) {
const k = Math.sqrt(root.sum(d => d.values[index]).value / max);
const x = (1 - k) / 2 * width;
const y = (1 - k) / 2 * height;
return treemap.size([width * k, height * k])(root)
.each(d => (d.x0 += x, d.x1 += x, d.y0 += y, d.y1 += y))
.leaves();
}

return Object.assign(svg.node(), {
update(index) {
box.transition()
.duration(duration)
.attr("opacity", ({i}) => i >= index ? 1 : 0);

leaf.data(layout(index)).transition()
.duration(duration)
.ease(d3.easeLinear)
.attr("transform", d => `translate(${d.x0},${d.y0})`)
.call(leaf => leaf.select("rect")
.attr("width", d => d.x1 - d.x0)
.attr("height", d => d.y1 - d.y0))
.call(leaf => leaf.select("text tspan:last-child")
.tween("text", function(d) {
const i = d3.interpolate(parseNumber(this.textContent), d.value);
return function(t) { this.textContent = formatNumber(i(t)); };
}));
}
});
}
Insert cell
update = chart.update(index)
Insert cell
duration = 2500
Insert cell
parseNumber = string => +string.replace(/,/g, "")
Insert cell
formatNumber = d3.format(",d")
Insert cell
sums = data.keys.map((d, i) => d3.hierarchy(data.group).sum(d => d.values[i]).value)
Insert cell
max = d3.max(sums)
Insert cell
color = d3.scaleOrdinal(data.group.keys(), d3.schemeCategory10.map(d => d3.interpolateRgb(d, "white")(0.5)))
Insert cell
data = {
const keys = d3.range(1790, 2000, 10);
const [regions, states] = await Promise.all([
FileAttachment("census-regions.csv").text(),
FileAttachment("population.tsv").text()
]).then(([regions, states]) => [
d3.csvParse(regions),
d3.tsvParse(states, (d, i) => i === 0 ? null : ({name: d[""], values: keys.map(key => +d[key].replace(/,/g, ""))}))
]);
const regionByState = new Map(regions.map(d => [d.State, d.Region]));
const divisionByState = new Map(regions.map(d => [d.State, d.Division]));
return {keys, group: d3.group(states, d => regionByState.get(d.name), d => divisionByState.get(d.name))};
}
Insert cell
tables = null
Insert cell
regions = d3.csvParse(await FileAttachment("census-regions.csv").text())
Insert cell
{
const keys = d3.range(1790, 2000, 10);
return d3.tsvParse(population, (d, i) => i === 0 ? null : ({name: d[""], values: keys.map(key => +d[key].replace(/,/g, ""))}))
}
Insert cell
population = await FileAttachment("population.tsv").text()
Insert cell
width = 954
Insert cell
height = width
Insert cell
d3 = require("d3@6")
Insert cell
import {Scrubber} from "@mbostock/scrubber"
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