treemap
Lays out children into a treemap: a 2D tiling of rectangles, or of convex polygons with Tile.voronoi, whose areas are proportional to a weight.
const items = [
{ name: "Action", value: 120 },
{ name: "Comedy", value: 80 },
{ name: "Drama", value: 160 },
{ name: "Sci-Fi", value: 60 },
{ name: "Horror", value: 40 },
];
// Each child gets its own rectangle; treemap assigns its (x,y,w,h).
// `size` is an explicit per-child weight array (one value per child, in
// child order) that drives each leaf's tile area.
gf.treemap(
{
size: items.map((d) => d.value),
spacing: 2,
padding: 2,
round: true,
},
gf.map(items, (d) =>
gf
.rect({
fill: gf.v(d.name),
stroke: "white",
strokeWidth: 1,
rx: 3,
ry: 3,
})
.label("name", { position: "center", color: "white", fontSize: 12 })(
d,
d.name
)
)
).render(root, { w: 520, h: 320 });Inside .flow(...) (the fluent chart API), treemap({ by, size, ... }) partitions the rows itself, mirroring spread/group: by groups the flow's rows (a field name or a field(...) accessor carrying domain ops, e.g. field("genre").dropNulls()), and size — an entry-flagged channel — sums a field per group (or takes an explicit per-entry array) to weight each tile's area. See spread for the by/entry-flagged-channel pattern this mirrors.
Signature
treemap(options); // .flow() operator form
treemap(options, children); // combinator formParameters
treemap — Operator form
d3-hierarchy treemap layout over the flow's rows, fare/weight-proportional.
| Option | Type | Default | Description |
|---|---|---|---|
x | number | string | FieldExpr | Left edge of the box the treemap tiles into, in the parent's space (pixels). Omitted, the parent places the treemap. | |
y | number | string | FieldExpr | Start edge on y (top where y reads top-down, bottom where it grows upward) of the box the treemap tiles into, in the parent's space (pixels). Omitted, the parent places the treemap. | |
w | number | string | FieldExpr | Length | Width of the box the treemap tiles into; a number is pixels, a data-driven value scales through the layout. Omitted, the treemap fills the slot its parent allots. Also percent(n), n percent of the room it is laid out in (its parent's, or the canvas), or fr(k), k shares of the room its nearest scope divides. | |
h | number | string | FieldExpr | Length | Height of the box the treemap tiles into; a number is pixels, a data-driven value scales through the layout. Omitted, the treemap fills the slot its parent allots. Also percent(n), n percent of the room it is laid out in (its parent's, or the canvas), or fr(k), k shares of the room its nearest scope divides. | |
dims | Record<string, AxisDimsValue> | The box the treemap tiles into, by axis name: x/y, or a name the enclosing coordinate space declares (polar theta/r, geo lon/lat). Each value is a position (like x) or an interval {min, center, max, size, embedded}. | |
by | string | FieldAccessor | ChunkKey | Field to partition rows by (like spread/group); also accepts a field(...) accessor carrying domain ops (sort/reverse/bin/dropNulls), or chunk(size) to group consecutive rows. Without by, each row is its own group. | |
spacing | number | 0 | Gap between sibling tiles, in pixels. |
padding | number | 0 | Inset around the outer edge of the treemap, in pixels. |
round | boolean | true | Round pixel positions and sizes. Applies to the rectangular tilings; Tile.voronoi cells are not rounded. |
tile | Tile | {"kind":"squarify"} | The tiling strategy, made by a call in the Tile family: Tile.squarify({ ratio? }), Tile.slice(), Tile.dice(), Tile.binary(), or Tile.voronoi({ seed? }). The first four are d3-hierarchy's tiling methods and need a rectangular region: inside a Voronoi cell or an oval they are an error. Tile.voronoi tiles any convex region, so it can sit inside a Voronoi cell. |
sort | "asc" | "desc" | "none" | "desc" | Sort leaves by weight before layout. |
size | number | string | FieldExpr | Per-leaf weight driving tile area (entry-flagged per split entry); a field name aggregates (sums by default) per group. |
treemap — Combinator form
Low-level combinator form of treemap (single level). Same fields as the operator form (OPERATORS.treemap) plus key.
| Option | Type | Default | Description |
|---|---|---|---|
x | number | string | FieldExpr | Left edge of the box the treemap tiles into, in the parent's space (pixels). Omitted, the parent places the treemap. | |
y | number | string | FieldExpr | Start edge on y (top where y reads top-down, bottom where it grows upward) of the box the treemap tiles into, in the parent's space (pixels). Omitted, the parent places the treemap. | |
w | number | string | FieldExpr | Length | Width of the box the treemap tiles into; a number is pixels, a data-driven value scales through the layout. Omitted, the treemap fills the slot its parent allots. Also percent(n), n percent of the room it is laid out in (its parent's, or the canvas), or fr(k), k shares of the room its nearest scope divides. | |
h | number | string | FieldExpr | Length | Height of the box the treemap tiles into; a number is pixels, a data-driven value scales through the layout. Omitted, the treemap fills the slot its parent allots. Also percent(n), n percent of the room it is laid out in (its parent's, or the canvas), or fr(k), k shares of the room its nearest scope divides. | |
dims | Record<string, AxisDimsValue> | The box the treemap tiles into, by axis name: x/y, or a name the enclosing coordinate space declares (polar theta/r, geo lon/lat). Each value is a position (like x) or an interval {min, center, max, size, embedded}. | |
by | string | FieldAccessor | ChunkKey | Field to partition rows by (like spread/group); also accepts a field(...) accessor carrying domain ops (sort/reverse/bin/dropNulls), or chunk(size) to group consecutive rows. Without by, each row is its own group. | |
spacing | number | 0 | Gap between sibling tiles, in pixels. |
padding | number | 0 | Inset around the outer edge of the treemap, in pixels. |
round | boolean | true | Round pixel positions and sizes. Applies to the rectangular tilings; Tile.voronoi cells are not rounded. |
tile | Tile | {"kind":"squarify"} | The tiling strategy, made by a call in the Tile family: Tile.squarify({ ratio? }), Tile.slice(), Tile.dice(), Tile.binary(), or Tile.voronoi({ seed? }). The first four are d3-hierarchy's tiling methods and need a rectangular region: inside a Voronoi cell or an oval they are an error. Tile.voronoi tiles any convex region, so it can sit inside a Voronoi cell. |
sort | "asc" | "desc" | "none" | "desc" | Sort leaves by weight before layout. |
size | number | string | FieldExpr | Per-leaf weight driving tile area (entry-flagged per split entry); a field name aggregates (sums by default) per group. | |
key | string | Internal per-node key override. |
Strategies
tile holds the tiling strategy, a member of the Tile family. You make a strategy with a function call. A strategy with no required option is also a value as it is: Tile.voronoi is Tile.voronoi(). The family is also the module gofish-graphics/tile, so import { squarify } from "gofish-graphics/tile" gives the same function as Tile.squarify.
The first four are tiling methods from d3-hierarchy. They tile a rectangle, so they need a rectangular region: inside a Voronoi cell or the oval of an enclose, they are an error that names Tile.voronoi.
Tile.squarify({ ratio? })makes tiles as close as it can to the aspect ratioratio, the longer side over the shorter side.ratiomust be at least 1, and it does not choose between wide and tall tiles. It is the default. Withoutratio, it uses d3's default, the golden ratio.Tile.squarify({ ratio: 1 })aims for square tiles, which suits one circle per leaf.Tile.slice()puts the tiles in one column, stacked along y.Tile.dice()puts the tiles in one row, side by side along x.Tile.binary()splits the tiles into two halves of about equal weight, and repeats on each half.Tile.voronoi({ seed? })cuts the region into convex cells with rounded, irregular shapes, by a weighted Voronoi diagram (Nocaj and Brandes 2012). It tiles any convex region, so a Voronoi level can sit inside a Voronoi cell, inside a rectangle of a squarified level, or inside the oval of anenclose. The sites start at random positions drawn fromseed(default 0), so a render is the same every time. The cells are fitted to within 2% of their shares beforespacingtakes the gaps off the borders between them.
gf.treemap({
by: "genre",
size: "gross",
tile: gf.Tile.squarify({ ratio: 1 }),
});Each treemap in a flow is one level, and each level can use its own tiling. A level hands each child its cell, and region() draws the cell it is in. spacing is the gap between sibling cells, and padding the inset at the treemap's own edge, under every tiling.
import { Shape, Tile, chart, enclose, region, treemap } from "gofish-graphics";
import { countryPopulations } from "./dataset";
const container = document.getElementById("app");
chart(countryPopulations, { axes: false, w: 480, h: 480 })
.flow(
enclose({ shape: Shape.oval, fill: "none" }),
treemap({
by: "continent",
size: "pop",
spacing: 5,
tile: Tile.voronoi,
}),
treemap({
by: "region",
size: "pop",
spacing: 2.5,
tile: Tile.voronoi,
}),
treemap({ size: "pop", spacing: 1, tile: Tile.voronoi })
)
.mark(region({ fill: "continent" }))
.render(container);Dataset
/**
* Seventy countries grouped by continent, then by region, with a rough
* 2023 population in millions. Used by the bubble treemap stories (#1221).
*
* The `uncertainty` column is MADE UP for illustration: a per-region spread,
* in percent, standing in for the standard deviation the bubble treemap paper
* (Görtler et al., TVCG 2018) draws as contour distance. It is not a real
* measure of anything.
*/
export type CountryPopulation = {
continent: string;
region: string;
country: string;
pop: number;
uncertainty: number;
};
const rows: [string, string, string, number][] = [
// Asia
["Asia", "East Asia", "China", 1410],
["Asia", "East Asia", "Japan", 124],
["Asia", "East Asia", "South Korea", 52],
["Asia", "East Asia", "Taiwan", 24],
["Asia", "East Asia", "North Korea", 26],
// … 65 more rows
];
// A made-up spread per region, in percent of population (see above).
const regionUncertainty: Record<string, number> = {
"East Asia": 1,
"South Asia": 4,
"Southeast Asia": 3,
"Western Asia": 6,
"West Africa": 10,
"East Africa": 8,
"North Africa": 5,
"Central & South": 12,
"Western Europe": 1,
"Southern Europe": 1.5,
"Eastern Europe": 3,
"North America": 1.5,
"South America": 4,
};
export const countryPopulations: CountryPopulation[] = rows.map(
([continent, region, country, pop]) => ({
continent,
region,
country,
pop,
uncertainty: regionUncertainty[region],
})
);The classic slice-and-dice treemap alternates Tile.slice and Tile.dice by level, one flow step each:
chart(countryPopulations)
.flow(
treemap({ by: "continent", size: "pop", tile: Tile.slice }),
treemap({ by: "region", size: "pop", tile: Tile.dice })
)
.mark(rect({ fill: "continent" }));Notes
- The tile d3 places first sits at the top left. With the default
sort: "desc", that is the largest tile. - A treemap accepts a flat list of children; for multi-level treemaps, chain one
treemap(...)per level in.flow(...), or nesttreemap(...)calls. - A treemap with no size of its own fills the shape its parent hands it: a cell of the treemap around it, or the shape of an
enclosearound it. - In the combinator form,
sizeis an explicit array, one weight per child in child order — it does not read back off each child's bound datum.
