spread
Partitions data by the by field and lays out one child per partition along an axis. The primary layout operator.
gf.chart(seafood, { axes: true })
.flow(gf.spread({ by: "lake", dir: "x" }))
.mark(gf.rect({ h: "count" }))
.render(root, { w: 400, h: 250 });Signature
// Operator form (inside .flow):
spread({ by?, dir, spacing?, alignment?, glue?, ... })
// Combinator form (apply n marks to one datum):
spread({ dir, ... }, [m1, m2, ...])Parameters
spread — Operator form
Arrange children along dir with spacing, aligning them on the cross axis.
| Option | Type | Default | Description |
|---|---|---|---|
by | string | FieldAccessor | ChunkKey | Field to partition rows by; also accepts a field(...) accessor carrying domain ops (sort/reverse/bin), or chunk(size) to group consecutive rows. Without by, each row is its own group. | |
dir | string | Axis to spread along: x, y, or an axis name the enclosing coordinate space declares (polar theta/r, geo lon/lat). | |
spacing | number | Length | Spacing | 8 | How far apart neighbors are, made by a call in the Spacing family: Spacing.box(gap), a gap between facing edges, or Spacing.pitch(distance, { at }), a fixed distance between the same point on each child. A bare amount is Spacing.box(amount): pixels, percent(n), n percent of the spread's room, or fr(k), k shares of its scope, so the gaps are flexible. |
alignment | string | "baseline" | Cross-axis alignment ("start" | "middle" | "end" | "baseline"). |
reverse | boolean | false | Reverse the children's order along dir. |
glue | boolean | false | Stack semantics: children glued, sizes sum; spacing forced to 0. |
axes | AxesOptions | ||
x | number | string | FieldExpr | Left edge of this operator's box, in the parent's space (pixels). Omitted, the parent places it. | |
y | number | string | FieldExpr | Start edge on y (top where y reads top-down, bottom where it grows upward) of this operator's box, in the parent's space (pixels). Omitted, the parent places it. | |
w | number | string | FieldExpr | Length | Width of this operator's box: pixels, or a field name sizing it from data. 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 this operator's box: pixels, or a field name sizing it from data. 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. | |
size | number | string | FieldExpr | Per-entry stack-axis extent (field/datum-sized children); a field(...).normalize() accessor makes it a space-filling spine. |
spread — Combinator form
Low-level combinator form of spread. Same fields as the operator form (OPERATORS.spread) plus key and the full box-dims group.
| Option | Type | Default | Description |
|---|---|---|---|
x | number | string | FieldExpr | Left edge of this operator's box, in the parent's space (pixels). Omitted, the parent places it. | |
w | number | string | FieldExpr | Length | Width of this operator's box: pixels, or a field name sizing it from data. 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. | |
y | number | string | FieldExpr | Start edge on y (top where y reads top-down, bottom where it grows upward) of this operator's box, in the parent's space (pixels). Omitted, the parent places it. | |
h | number | string | FieldExpr | Length | Height of this operator's box: pixels, or a field name sizing it from data. 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. | |
by | string | FieldAccessor | ChunkKey | Field to partition rows by; also accepts a field(...) accessor carrying domain ops (sort/reverse/bin), or chunk(size) to group consecutive rows. Without by, each row is its own group. | |
dir | string | Axis to spread along: x, y, or an axis name the enclosing coordinate space declares (polar theta/r, geo lon/lat). | |
spacing | number | Length | Spacing | 8 | How far apart neighbors are, made by a call in the Spacing family: Spacing.box(gap), a gap between facing edges, or Spacing.pitch(distance, { at }), a fixed distance between the same point on each child. A bare amount is Spacing.box(amount): pixels, percent(n), n percent of the spread's room, or fr(k), k shares of its scope, so the gaps are flexible. |
alignment | string | "baseline" | Cross-axis alignment ("start" | "middle" | "end" | "baseline"). |
reverse | boolean | false | Reverse the children's order along dir. |
glue | boolean | false | Stack semantics: children glued, sizes sum; spacing forced to 0. |
axes | AxesOptions | ||
size | number | string | FieldExpr | Per-entry stack-axis extent (field/datum-sized children); a field(...).normalize() accessor makes it a space-filling spine. | |
key | string | Internal per-node key override. |
Box dimensions
| Option | Type | Default | Description |
|---|---|---|---|
cx | number | string | FieldExpr | Center x. | |
x2 | number | string | FieldExpr | Right edge position. | |
emX | boolean | Embed x in the parent's x space. | |
cy | number | string | FieldExpr | Center y. | |
y2 | number | string | FieldExpr | Other y edge position. | |
emY | boolean | Embed y in the parent's y space. | |
dims | Record<string, AxisDimsValue> | Box dimensions 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}. |
Examples
// Horizontal bar chart: one bar per "letter"
.flow(spread({ by: "letter", dir: "x" }))
// Vertical layout with fixed width per group
.flow(spread({ by: "category", dir: "y", w: 40 }))
// Combinator form: apply different marks to the same datum
spread({ dir: "x" }, [rect({ h: "v" }), text({ text: "n" })])Naming the axis with dir
dir: "x" and dir: "y" mean the first and second axis in any coordinate space. dir also takes the names the enclosing coordinate space declares, so under polar you can write dir: "theta" or dir: "r", and under geo dir: "lon" or dir: "lat":
chart(data, { coord: Coord.polar() })
.flow(spread({ by: "month", dir: "theta", spacing: 0 }))
.mark(rect({ w: 0.5, h: "value" }));dir: "theta" lays the months out exactly as dir: "x" does. A name the enclosing space does not declare throws an error that lists the names it does. stack takes the same dir.
Path-aware by
by accepts a field name, a lodash path string, a function, a field(...) accessor, or a chunk(size) key:
spread({ by: "species", dir: "x" }); // field name
spread({ by: "origin.country", dir: "x" }); // nested path
spread({ by: (r, i) => r.species, dir: "x" }); // function of the row and its position
spread({ by: field("species").sort(), dir: "x" }); // field(...) accessor
spread({ by: chunk(5), dir: "y" }); // consecutive rows, five to a groupWithout by
With no by, the split is by row identity: each row is its own group, keyed by its position. The mark under it gets that group, a one-row array [row], just as it gets a group of rows under a by field. An item that is itself an array is still one item, so it becomes [item]. The keys are positions, not data, so they draw no axis and no labels.
chunk(size)
chunk(size) groups consecutive rows: row i goes to group Math.floor(i / size). It is a bin of width size over row position, like lodash _.chunk, Rust chunks(n) and Python itertools.batched. Like no by, its keys name no field, so they draw no axis and no labels. chunk(1) is the same split as no by.
chart(seafood)
.flow(
spread({ by: "lake", dir: "x" }),
derive((d) => d.flatMap((row) => repeat(row, "count"))),
spread({ by: chunk(5), dir: "y", reverse: true }), // rows of five units
spread({ dir: "x" })
)
.mark(rect({ w: 8, h: 8, fill: "species" }));The same bare field name works after a ref / selectAll selection. The stream items are then refs, not raw records, but a ref is read through its .datum rows automatically, so you still write by: "species". Do not add a datum. prefix: by: "datum.species" looks for a field named datum inside each row, finds nothing, and puts every ref in one group.
How by resolves on a ref (homogeneity collapse)
A ref's .datum is the raw bag of rows that flowed into the node (an array; a fully-split leaf is a 1-row array). A by: "field" path on a ref does not just _.get the field off the first row — it projects with homogeneity collapse:
fieldresolves to a scalar iff every row in the node's bag agrees on that field; otherwise it isundefined— the "this field is multi-valued here, grouping by it is ill-posed" signal.
This is exactly SQL's ONLY_FULL_GROUP_BY / functional-dependency rule: you may only group by a column that is constant within each row-bag.
Example. After selectAll("bars") where each ref is a lake aggregate of 5 species rows:
group({ by: "lake" }); // resolves — all 5 rows share one lake
group({ by: "species" }); // undefined — 5 distinct species; ill-posedTo group by a field that is multi-valued in the current bag, disaggregate first (split the bag so each child is homogeneous in that field). A fully-split cell (1 row) trivially collapses, so by: "species" works once each node holds a single record. A function by gets the ref itself, not a row, so it must read the bag through r.datum (an array) on its own.
To read every value at a multi-valued path instead of collapsing to a scalar, use pluck — the un-collapsed counterpart of by.
So a ribbon chart reads:
chart(selectAll("bars")) // stream of refs
.flow(group({ by: "species" })) // bare field, read through each ref's rows
.mark(ribbon({ opacity: 0.8 }));spacing vs glue
spacing controls the visual gap between children. glue controls whether children's data-driven sizes get summed into a positional axis at this level:
glue: false(default): real spread. Each child keeps its data-driven size; the underlying-space kind ondiris SIZE (or ORDINAL when children are categorical).glue: true: stack semantics. Children are pushed together (regardless ofspacing), and their cumulative size becomes a continuous POSITION domain ondir. This is whatstackdoes.
Use spread({ spacing: 0 }) if you want children touching but with each child still treated as its own thing (e.g. discrete-theta polar charts). Use stack(...) if you want a stacked-bar feel (continuous position axis running through the stack).
Field-expression pipeline
field(name) returns a chainable expression — a builder where each method appends one op to an ordered pipeline. It works in two disjoint places:
- As
by(a domain slot):.sort(by?, order?),.sort(values)(an explicit order list),.reverse(),.bin(partition?), and.dropNulls()decide which groups exist and in what order. - As a mark or
sizechannel value (a value slot):.sum(),.mean(),.median(),.count(), and.distinct()fold a group's rows to one number, overriding the channel's own default aggregation (sum for size, mean for position).
Mixing the two — an aggregate op on by, or a domain op on a value channel — throws.
One method is neither: .between(lo, hi, { closed }) returns a row predicate for filter rather than appending an op, because a predicate never takes part in grouping, folding or scaling. For the same reason it throws if the expression already carries ops.
// Keep the rows whose day falls in (100, 120]
.flow(filter(field("day").between(100, 120, { closed: "right" })))closed is polars' is_between argument: "both" (the default), "left", "right" or "none", choosing which ends of the interval are inclusive. The comparison is by value, not by row count. lo and hi are plain numbers.
The same test on a bare value is exported as between(v, lo, hi, { closed }), which is how a window follows a timer(): the clock read goes in the predicate.
Sort a stack's groups by another field's total, instead of data order:
// Bars ordered ascending by their own total `value`
.flow(spread({ by: field("category").sort("value"), dir: "x" }))
.mark(rect({ h: "value" }))Omit the by argument to sort by the group key itself; pass order: "desc" for descending.
Sort groups by an explicit order, for a domain-specific sequence no aggregate expresses (severity, calendar order, a fixed ranking):
// Weather categories in a fixed order, not alphabetical or by aggregate
.flow(stack({ by: field("weather").sort(["sun", "fog", "drizzle", "rain", "snow"]), dir: "y" }))Groups whose key isn't in the list are appended after, in natural sort order.
Bin a field into cells — a histogram, with no precomputed bins:
// One bar per half-point cell of `rating`, height = row count per cell
.flow(spread({ by: field("rating").bin(Bin.step(0.5)), dir: "x" }))
.mark(rect({ h: field("rating").count() }))
// One bar per month of the year, all Junes in one bar
.flow(spread({ by: field("date").bin(Calendar.month), dir: "x" }))
.mark(rect({ h: field("value").sum() }))
// One bar per month of each year, labeled "Jun 2015"
.flow(spread({ by: field("date").bin([Calendar.year, Calendar.month]), dir: "x" }))
// The months of each year: a month level and a year level on the axis
.flow(spread({ by: field("date").bin(Calendar.year).bin(Calendar.month), dir: "x" })).bin(partition) maps each value to its cell: an interval [start, end) that holds its start and not its end. The partition is one of:
| Partition | Cells |
|---|---|
| a Calendar value | The calendar cells of a time column, in the column's zone. A level that is a part of a larger one gives its parts, a cycle: Calendar.month is the month of the year, so all Junes are one cell. Calendar.year and Calendar.week are parts of nothing and give cells of the time line. |
| a list of Calendar values | A product, [Calendar.year, Calendar.month]: one cell where one cell of each level meets one of the next (the June of 2015), labeled "Jun 2015". |
Bin.step(size) | Cells size wide, starting at multiples of size. |
Bin.thresholds(n) | About n cells, with the step a numeric axis with n ticks uses. Default: Bin.thresholds(10). |
Bin.thresholds([t1, t2, ...]) | Cells cut at the given edges, with the smallest and largest values as the outer edges. |
Bin.step and Bin.thresholds are members of the Bin family. A thresholds partition includes its top edge, so the largest value falls in the last cell. Each partition takes .format((cell) => string) for its labels, as in Bin.step(10).format((c) => String(c.start)). A partition with a format is JS-only, and serializing it is an error.
A second .bin(...) splits each cell of the first, a chain: .bin(Calendar.year).bin(Calendar.month) gives the months of each year, and each cell keeps the cell it was split from. See Calendar › Bins for which levels a product or a chain combines.
The groups are the cells over the column's values in the chart's data (or the result of the last derive), not over the rows of one group. So every group of a nested split has the same cells in the same order, a cell with no rows is kept as an empty group, and a count picks its step from the chart's values. Ops after .bin reorder the cells. The mean of an empty group has no value, so a mark whose color is that mean is not drawn, and keeps its slot; a sum or a count of no rows is 0, and draws.
Each group's key is its cell. Its id is the cell's start, as text, or, for a part of a cycle, its field values ("6" for June). An axis over cells labels each cell (its edges, "0.5–1", or the calendar label "Jan"), with no ticks. A chained key adds a level per bin before the last, e.g. years under months, each year label at the start of its run of months, just past the divider between neighboring years. A part of a cycle covers the whole cycle: an axis over the months of the year shows all twelve. See chart › Axes for the levels and label.align options.
spread gives each cell an equal slot. To place each cell at its true width on a continuous axis, use partition with the same key.
Drop rows with a missing/null grouping field, before grouping:
// Rows with a null/undefined "genre" are excluded entirely, instead of
// forming their own "null" group
.flow(treemap({ by: field("genre").dropNulls(), size: "worldwideGross" }))Override a channel's default aggregation:
// The bar height is each species' MEAN weight, not the sum
.flow(spread({ by: "species", dir: "x" }))
.mark(rect({ h: field("weight").mean() })).count() and .distinct() are in the unit "count" (they're counts, not the source field's own units).
Space-filling spines (mosaic / marimekko)
size: field(<name>).normalize() turns a stack's entries into a space-filling spine: each entry's size becomes its SHARE of the window (the operator's own split entries, v_e / Σv_e), so the axis reads as a local 0–100% conditional distribution. It replaces the removed normalize: true layout flag — .normalize() is a data transform on the size channel (a windowed share, computed once up front), not a layout mode, so the same field can drive both a cross-axis marginal size and the normalized fill with no preprocessing.
That is exactly a mosaic. Nest two stacks on alternating axes: the outer sizes each column by its raw total (size: "count" — the marginal), the inner sizes by each entry's share (the conditional). Both come off one raw field — no per-cell aggregation or precomputed totals:
chart(passengers, { axes: true })
.flow(
// columns by class — width ∝ each class's count (marginal)
stack({ by: "pclass", dir: "x", size: "count" }),
// survival share within each column (conditional), filling height
stack({ by: "survived", dir: "y", size: field("count").normalize() })
)
.mark(rect({ fill: "survived", stroke: "white", strokeWidth: 1 }))
.render(container, { w: 400, h: 300 });.normalize() composes to any depth: a third alternating level gives a nested mosaic (class → sex → survived). Because each level's stacking axis is a local self-scaling region and the count is read raw everywhere, the marginal × conditional × … area factorization holds all the way down.
WARNING
Inner conditional axes are local scopes, so they don't yet render 0–1 tick labels — only the outermost marginal axis is labeled.
