Public
Edited
Apr 24, 2024
Insert cell
Insert cell
{
const height = width * 0.618;

const treemap = d3
.treemap()
.size([width, height])
.tile(d3.treemapFlex())
.paddingInner(10)
.paddingLeft((d) => (d.data.hide ? 0 : 10))
.paddingTop((d) => (d.data.hide ? 0 : 10))
.paddingBottom((d) => (d.data.hide ? 0 : 10))
.paddingRight((d) => (d.data.hide ? 0 : 10));

const root = treemap(d3.hierarchy(data));

const nodes = root.descendants().filter((d) => !d.data.hide);

const color = d3
.scaleOrdinal()
.domain(d3.sort(Array.from(new Set(nodes.map((d) => d.height)))))
.range(d3.schemeObservable10);

const svg = d3.create("svg").attr("viewBox", `0 0 ${width} ${height}`);

const g = svg
.selectAll("g")
.data(nodes)
.join("g")
.attr("transform", (d) => `translate(${d.x0},${d.y0})`);

g.append("rect")
.attr("width", (d) => d.x1 - d.x0)
.attr("height", (d) => d.y1 - d.y0)
.attr("fill", (d) =>
d.depth === 0 ? "#fff" : d3.hsl(color(d.height)).brighter(1.2)
)
.attr("stroke", (d) => (d.depth === 0 ? "#fff" : color(d.height)));

g.filter((d) => !d.children)
.append("text")
.attr("x", (d) => (d.x1 - d.x0) / 2)
.attr("y", (d) => (d.y1 - d.y0) / 2)
.attr("text-anchor", "middle")
.attr("dominant-baseline", "middle")
.text((d) => d.data.name);

return svg.node();
}
Insert cell
data = ({
name: "root",
children: [
{ name: "a" },
{
name: "group",
hide: true,
children: [
{
name: "group",
wrap: 2,
value: 2,
children: [{ name: "h" }, { name: "i" }, { name: "j" }, { name: "k" }]
},
{ name: "g" }
]
},
{
name: "group",
children: [
{ name: "l" },
{ name: "m" },
{ name: "n" },
{ name: "o" },
{ name: "p" },
{ name: "q" },
{ name: "r" }
]
}
]
})
Insert cell
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