Axes
GoFish draws axes — an axis line, tick marks, tick labels, and (for categorical spaces) per-key labels — automatically from the position scales it infers. Axes are not a privileged node type. They are elaborated into ordinary GoFish shapes (rect, text) and operators (spread, layer) wired together with constraints (align, distribute, position), exactly the way the hand-drawn axes in stories/lowlevel/Axes.stories.tsx are written by hand. The layout engine has no axis-specific code at all.
For the design ideas behind axes (an axis shows a datatype, chrome and size, and where domains are decided), see How Axes Work.
The elaboration pass
elaborateChrome (src/ast/axes/elaborate.tsx) runs inside gofish.tsx's layout(), after resolveUnderlyingSpace (so domains are known) and resolveAxes (which flags which node owns an axis on each dimension — and leaves persistent axisDemand stamps that later gate demand-driven domain nicing at the σ-scope solves, issue #659, and carry the ticks the domain is niced to). An absolute axis's line and ticks span KeyedDomains.scope of the owning node's POSITION domain: the domain widened to its keyed domain and niced to the ticks of the axis drawn over it. Every sized node's solve reads the same function for the same keyed domain, so ticks and content agree by construction. It walks the node tree bottom-up. Each node that owns chrome is replaced by rings of Layers around the original content. Each ring holds the rings inside it plus its own shapes, and seats its shapes past everything inside it:
inner = Layer([ content, ...continuous shapes ])
axes = Layer([ inner, ...ordinal labels ])
titles = Layer([ axes, ...title anchors, ...titles ])
root = Layer([ titles, legend ])No ring and no shape has a name. A ring's constraints refer to what it seats by slot (wrapRing): the box inside the ring is slot 0, and its k-th shape is slot k + 1, so no lookup is involved. A ring is transparent to a user's name lookup (_transparent): it adds no depth, and the content keeps its own name, so ref("bars") on a chart with axes is the bars alone.
A node gets only the rings it has shapes for. Its chrome is:
- the axes
resolveAxesassigned it (the first two rings); - what its chrome request (
GoFishNode._chromeRequest) asks for: a title on each of those axes that the request'saxesoptions name (see Axis titles), and a legend ring (see Legends). The chart options stamp the request on the chart root;elaborateChromereads it, synchronously, and clears it.
The node's identity (name, key, visibility) moves onto the outermost ring. Nothing records the boxes inside it. Each ring is marked GoFishNode._chromeRing:
- A ring's first child is the ring inside it (or the content); its other children are its chrome.
GoFishNode.dressedBoxwalks the first children down to the content, the node without chrome. The render root reads its axis direction off it. - Each ring is an ordinary layer (#1257): it seats its content at its origin, claims the hull of its children, and hands its content what its chrome leaves of its room. Its plot is its content's plot. There is no separate record of how far the chrome reaches. See Chrome around a chart.
- The outermost ring itself is the box with all chrome.
- The content of the innermost ring is marked
GoFishNode._axesBeside: it is the plot its axes are seated beside, and it covers its whole niced domain (see Axis lines frame the domain).
Tick and category labels are chrome, so they lie outside the content.
Chrome sits outside its chart and takes room: every chrome shape claims its size (a text is measured when the claims are resolved), each ring claims the hull of what it wraps and of its shapes where its constraints place them (placeByClaims), and each ring hands its content what its chrome leaves of the ring's room (plotRooms in layer). A category label is centered on its slot's ref. The claim walk knows where the slot lands (planPlacement): on a data axis (time or number bins) through the data, and on a category axis because a band is a share, which claims one σ (#493 piece 3, GoFishNode.sharesRoom). So the label takes room, and only its overhang past the ends of the axis reaches past the ring's hull. One wider than its band overdraws its neighbors (#1115) instead of widening the bands, and a label in a ring that a spread along its axis holds (one group's labels in a grouped bar chart) is ink, so it does not widen the gap between groups. The boxes a category label is centered on (axisSpan, runStartBox) read their place along the axis from refs (GoFishNode.inkOn), so they are ink there too; one without a line has no depth across the axis and is not seated there, so it is ink across it as well. A divider is cross pixels deep across the axis and claims that.
The inner tier holds the constraint-pinned axes (continuous and time); the outer tier holds the ordinal label rows, which need the inner tier fully laid out so they can seat past its bounding box. In each tier the wrapped child is pinned with position({ x: 0, y: 0, anchor: "baseline" }) — a literal-pixel pin at the origin, meaning "stay exactly where you were laid out". The pin exists because the content is referenced by distribute constraints, and a constraint-referenced child skips the layer's phase-1 baseline placement (placement is first-write-wins, so constraints must run against unplaced targets); the origin pin re-states that phase-1 placement explicitly. The anchor must be baseline, not start: start pins the bounding-box corner, which slides the marks off the tick grid once the box overhangs the origin (nested facet labels, negative bars).
The content is pinned on both dims, a free content included (a bar chart's bars, lined up on one baseline, are one free magnitude). The render root and a chart place a free space's baseline (placeBaseline, GoFishNode.placedSpace), so they own an absolute axis over it, niced about its 0. The ticks read their datums in the content's frame (position's in), so value 0 sits at the 0 tick wherever the ring puts the content, negative bars included. A content the gutter chain could move instead would leave those ticks with no frame to read.
Everything else then seats around the stationary content in negative gutter space (the ring's box reaches past its origin, and the ring claims that room, see above): the axis line distributes off the content's near edge, tick marks align flush with the line, labels hang outward. Keeping the content at its origin — rather than letting the gutter chain push it, as the single-axis hand-drawn story does — is what keeps two continuous axes on one grid: a shifted content would land at gutter + scale(v) while the other axis's datum-pinned ticks sit at scale(v).
Axis lines frame the domain
A plot covers its whole niced domain, not only the hull of its marks: on each axis with an origin, the content its axes are seated beside (_axesBeside) widens its claim and its plot to the domain, rounded as the axis over it is (KeyedDomains.scope, the same widen-then-nice the marks are placed by). On a dimension with no origin the domain is a width: it draws no axis (it is a length scale, and its guide is a length entry in the legend), and the plot covers the width from the content's start (differenceSpan), in the content's frame. The claim walk widens its plan (domainPlan in layer) and layout widens its box (GoFishNode.domainSpan), so the two agree. Every axis line then distributes just past the content's box without its dressing, like any other chrome (see the layout passes): an outline or a label whose type is undefined draws over the line. The two lines of a scatter frame the domain corner even when no datum reaches it (a scatter whose y domain is niced below the lowest point does not draw its x axis at the lowest point), and a mark that reaches past the floor (a dot's radius, a histogram bin's dressing) pushes the line out instead of straddling it.
A facet panel that owns only its y axis covers the shared domains, so its y axis sits at the floor of the shared x domain, past its own marks, and every panel's axis sits on one line (#753). Turning the rounding off, or setting a custom domain, is #1301.
Which side the axis seats on
Each axis seats in a gutter on one cross-edge, chosen in the owner's axis order ("start" or "end", see Axis direction). The default is defaultAxisSide (axes/elaborate.tsx), read off the owner's axisDirection on the cross axis:
- a continuous x-axis renders at the visual bottom: the
startof a y that grows upward (a scatter, a vertical bar chart), theendof a y that reads top-down (a horizontal bar's category y, a faceted stack's facet y); - every other axis takes
startin its frame: a y-axis on the left, and a category x-axis at the start of its y (the bottom of a bar chart, the top of a heatmap).
The public axes: { x: { side: "start" | "end" } } option is the override: when specified it is honored literally (frame-relative: "start"=near, "end"=far), bypassing the bottom-default so a caller can force the opposite edge. resolveAxisSides returns undefined for an unspecified side precisely so the elaboration can tell an explicit "start" apart from the default. The per-dim side is threaded elaborateChrome → elaborationsFor → elaborate{Continuous, Difference,Ordinal}Axis, and each seating decision reads the resolved edge: gutterConstraints flips the innerAlign edge and the order of the distribute that seats the line past the content, the ordinal label row flips its distribute([label, content]) pair, and the axis titles follow their axis to the same edge (see below). The tick-and-label pair (tickMark) is a plain spread, which reads in pixel order, so it orders its two parts by the axis's SCREEN side (the side in axis order, turned into the screen side by the owner's cross direction) to keep the tick facing the content.
Axis titles are ordinary shapes seated by constraints in the title ring's axis order. elaborationsFor returns the side it chose for each axis, and the title ring uses that same side, so a title and its axis always land on the same edge.
Label rotation (label.angle)
The public axes: { x: { label: { angle: number | number[] | "auto" } } } option (#746, extended to per-level arrays afterward, nested under label in #1133) rotates a tick or category label about its anchor, authored screen-clockwise to match Vega-Lite's labelAngle. It is threaded the same way side is — elaborateChrome → elaborationsFor → elaborate{Continuous,Ordinal}Axis → tickMark / elaborateOrdinalAxis — landing on the Text mark's rotate prop, which is SVG's rotation, clockwise on screen, so it passes through unchanged. A number or array is a manual, always-on angle; "auto" picks one of 0°, 45°, and 90° per label row (see Automatic label angle below).
The hanging-point rule. resolveLabelRotation (axes/elaborate.tsx) turns the authored angle a into a LabelRotation descriptor — rotate (the value passed to Text), trackAlign, and textAnchor — that governs how the label attaches to its tick/key along the TRACK axis (the axis's own direction): the label is anchored at whichever of its points ends up nearest the axis line, not at its rotated bbox's middle.
ais0/undefined:trackAlign: "middle"— plain bbox-middle centering, IDENTICAL to the unrotated path (no rotation is even applied).|a| === 90: alsotrackAlign: "middle"— the rotated column's bbox middle already centers it horizontally on the tick.0 < a < 90(slants down-right):trackAlign: "baseline",textAnchor: "start"— the label hangs from its FIRST character (Vega-Lite's 45° look).-90 < a < 0(slants up-right):trackAlign: "baseline",textAnchor: "end"— the label hangs from its LAST character (matplotlib'sha="right"look).
"baseline" is AlignAnchor's existing "pin the target's own local origin" mode (_node.ts's _pinAnchor). A text's x origin is its textAnchor point, and Text's rotation is applied about a point with that x (text.tsx), so on an x track pinning "baseline" pins the rotation pivot directly — no bbox-edge arithmetic needed. (A text's y origin is its box's start edge, as for a rect, so on a y track the pin lands the rotated box's start edge.) textAnchor (a Text prop) picks which end of the pre-rotation label is that x: "start" (the default) the first character, "end" the last, so the SAME "baseline" anchor reaches either hanging corner depending on the angle's sign. Accepted approximation: the pivot sits on the label's baseline (dominantBaseline: "auto"), not the ascender-top corner an idealized "nearest point on the rotated bbox" derivation would use — the two differ by ascent·sin(a), a couple of pixels at these sizes, invisible in practice.
For an ordinal axis, elaborateOrdinalAxis expresses this directly: Constraint.align's anchor accepts a per-child array ([trackAlign, "middle"]), so the label pivots to "baseline" while the key node it tracks stays "middle"-anchored on its own extent — one constraint, heterogeneous anchors. A continuous axis can't do the same by nesting the tick and label into one tickMark node the way the unrotated/±90° path does: an oblique label's rotated bbox is NOT symmetric about its pivot, so positionAxis's per-tick Constraint.position(pos(v), [tick]) — which defaults to anchor: "middle", i.e. the target's bbox middle — would pin the PAIR's lopsided union bbox middle at the data value instead of the pivot, dragging the hanging point off the tick by however asymmetric the rotated label is. So for an oblique continuous axis, elaborateContinuousAxis keeps the tick bare (tickRect, unaffected by the label) and gives positionAxis a separate tickLabel builder: the DATA pin still targets the bare tick alone, and the label is a sibling related to it by the same heterogeneous Constraint.align + a cross-axis Constraint.distribute, mirroring elaborateOrdinalAxis's approach. The unrotated/±90° path is untouched code (still tickMark + Spread's uniform "middle" alignment), not just untouched geometry, so those angles stay pixel-identical to before the hanging-point rule.
Levels
Every axis on a dim has levels, its bands of labels, numbered by depth from the plot outward: a numeric axis has one (its ticks), a time axis one per row, and an ordinal axis one per split, plus one per bin before the last of a chained key (field(x).bin(Calendar.year).bin(Calendar.month): a month level, then a year level). Axes nest, since ordinal axes nest: resolveAxes lets a distinct ordinal grouping claim its own axis at every depth (_node.ts's resolveAxes), so a grouped bar chart has one node owning the city axis and, independently, one sibling-node-per-city each owning that city's year axis, and a DEEPER call in the bottom-up elaborateChrome walk always elaborates an inner axis before an ancestor elaborates an outer one on the same dim.
The depths come from a LevelFold bubbled UP through the recursion: per dim (a DimFold), the names of the levels drawn so far (nearest the plot first), whether one of them is ordinal, how deep the ordinal rows reach and the column their outer level bins; and the per-level entries that could not apply. elaborateChrome folds it over its own children (the longest list of names; ordinal if any child's is), so a node's fold depends only on ITS OWN subtree and two independent grouped-bar regions don't interfere, then hands it to elaborationsFor. An axis on dim d starts at depth names.length and appends the names of its own levels.
Four options are read at those depths: levels, label.angle, label.align and divider (LevelOptions in axes/levels.ts, read once per chart by readAxisOptions in gofish.tsx, which checks the options object against the IR's declared AxisOptions with Frontend.checkOption). One reader serves all four (readAtDepth): a plain value is the setting at every depth, and a list's entry is the setting at its own. Each level kind says which settings it cannot take: a continuous axis's level, numeric or time, has ticks, not regions, so it takes no divider: true and no label.align: "start", and a time axis does not rotate its labels yet. A plain value applies to every level where it can, so it skips such a level. A list entry names its level, so one that cannot apply there is an issue.
axes.x.levels (AxisOptions.levels in gofish.tsx; read once by levelsFromOption in axes/levels.ts) is a list by depth. true keeps a level as inferred, false hides it (a hidden level draws nothing and takes no space; the node still claims the axis and its depths, so no ancestor draws it instead), and a Calendar value names its cells: a time row's partition (timeRows in elaborate.tsx), or, on an ordinal axis over cells of time, the cells that group its slots (calendarLevel: each slot falls in the cell of the partition that holds its start, read off a timeline cell's start, or off a part of a cycle's cell in the reference cycle, CycleCell.ref; the partition must be a part of one cell of the cycle, which the cycle's own unit says, HasCycle.unit.whyNotAPart, so a part of a week is grouped only by a weekday that starts the week on the same day). A slot that nests in the partition lies in that cell. One that does not, a week over months, is grouped with the month it starts in, as a calendar labels its weeks. The slots are in order, so each slot's cell is found once per run of slots. A partition finer than the slots' level, by the levels' nominal lengths, as a chain compares them (a week over months), groups nothing, and is an error. An axis with no axis above it on its dim (hasOuterAxis reads the ancestors' still-set axis flags) also takes the Calendar entries past its inferred levels, as more levels. Time rows and ordinal levels apply their entries through one function, applyLevelEntries; each axis kind supplies only its inferred levels and how a Calendar entry resolves. An entry of any per-level option that cannot apply records an issue, and layout raises the first one, or an entry past the last level, with the dim's level names (levelOptionsError). So an error lists every level of the chart's dim, not only the axis that found it.
Automatic label angle (label.angle: "auto")
label.angle: "auto" picks each label row's setting from 0°, 45°, 90°, and (for a category row only) hidden, in that order of preference: the first setting at which no two labels in the row collide wins. Hidden always fits (a hidden row has no labels to collide), so a category row never reaches the least-overlap fallback; a continuous tick row cannot be hidden, since no legend can carry tick values (a domain fact; the future answer there is tick thinning), and keeps the angle with the least overlap. It is a v0 of a general choice mechanism, split into two modules:
choice/choose.tsholds the generic strategy,chooseFirstFit(candidates, run, score, fits): run candidates in order, return the first whose score fits, else the lexicographic minimum (ties go to the earlier candidate).axes/autoLabelAngle.tsholds the label policy: the candidate list, the collision score, andlayoutWithAutoLabelAngles, whichrunLayout(gofish.tsx) calls when some axis asks for"auto". A chart without"auto"takes the singlelayoutOncepath, unchanged.
Why the whole chart is the unit. An axis label is a Text whose underlying space is UNDEFINED, so its angle never changes σ (bar widths); it only changes how far the labels hang into the margin. But layout measures and places in one recursive pass and writes each node's box once (the bbox ledger), so a subtree cannot be laid out again with a different angle. And the rows that can collide are not local to one node: a grouped bar chart's inner year level is elaborated separately inside each city group, so a 2024 label under Austin can hit a 2022 label under Boston, which only the root can see. So v0 lays out the whole chart once per candidate, on a freshly built tree each time, scores the finished geometry, and returns the winning layout as is (see "Per-row choice" for the one case that needs one more run). The fresh tree comes from GoFishNode.rebuild, which the surface that built the root sets: the builder terminals (marks/terminals.ts) and the gofish() component thunk path. A node built by hand has no rebuild, and "auto" on it throws.
Tagging and reading labels. Axis elaboration tags every tick and category label Text with axisLabel = { dim, kind, depth } (kind is "ordinal" or "continuous"; depth is the label's level depth on its dim, see Levels). After a run, collectLabelBoxes walks the laid-out tree, and for each tagged label reads its unrotated text box and rotation from the Text node and its pivot: its origin, found by summing its own and every ancestor's projectedTranslate, plus the glyph offset the text keeps (glyphDy, the box's top in pixels less the glyphs' top). That puts every label in the root's layout frame, which is screen pixels up to the gutter offset, so overlap measured there equals overlap on screen.
The score. Labels are grouped into rows, one per (axis, kind, depth), and scoreLabelRows scores each row on its own. Within a row all labels share one angle, so the scorer turns every origin back by that angle and compares the labels as plain axis-aligned boxes in their own frame. That is exact for parallel slanted text, where axis-aligned bounding boxes would report collisions between labels that do not touch. Each box is widened by half of a 2px clearance (AUTO_LABEL_GAP) on every side; a pair whose widened boxes overlap collides. A row's score is [unwidened overlap area, colliding pairs], and an angle fits the row when the pair count is 0. Pairs are found with a sweep along the row, so any two labels are compared, not only neighbors.
Per-row choice. Every row of every "auto" axis is chosen independently, so a grouped bar chart's crowded product row can slant to 45° (or be hidden) while its region row stays at 0°. Axis elaboration takes a LabelRowSettings function, (row) => angle | "hidden" | undefined, asked once per row; a manual label.angle becomes one via labelRowSettingsFromAngles, and runLayout hands layout() the chosen one directly (an internal option, not a public value). A hidden ordinal row is simply not elaborated: the node still claims the axis and its depth, but adds no labels, so the row takes no space. The runs are uniform: each applies one candidate to every row of every "auto" axis (memoized by candidate; in the "hidden" run a continuous row stays upright and is never scored), and each row runs its own chooseFirstFit over its candidates (ORDINAL_CANDIDATES or CONTINUOUS_CANDIDATES) and those runs' per-row scores. If the winners are not all the same, that combination is laid out once more. This rests on two assumptions that hold today. Axes don't interact: labels do not feed σ, so one axis's angles cannot move the other axis's labels along their track. Rows don't interact for collisions: each level is its own cross-axis row, and a level's angle pushes the rows outside it further into (or back out of) the margin without changing their spacing along the track. "auto" inside a per-level array is an error.
Warning when categories go unlabeled. A hidden category row is fine when a legend still names its categories. Ordinal labels carry the field their row labels (axisLabel.field, the ordinal space's title), and layout() reports the fields the rendered legend shows (LayoutData.legendFields, read off the color scale's recorded fields; see Color Scale Resolution). After the choice, warnUnlabeledRows logs one console.warn per hidden row whose field the legend does not show: the legend is suppressed, it colors by another field, or the color came from a function accessor (the scale knows no field for it). Only the chosen layout is checked, so a render warns at most once per row.
Where it goes next. The compositional form is a node-local choice that lays out its own alternatives and prunes dominated ones (#486, #630). That replaces the whole-chart strategy in choose.ts; the policy half (candidates plus score) is meant to carry over unchanged.
The wrapper inherits the wrapped node's key, so faceting keeps resolving to it. The wrapped node keeps its _name, and the wrapper is transparent to a name lookup, so an external ref resolves to the node itself. After the rewrite, the whole tree's underlying space is recomputed (the cache is cleared); then normal layout runs, and each σ-scope's solve nices its own domain on demand — there is no tree-wide nice pass.
Because the axis is now a real shape occupying real space, everything the old bespoke pipeline hand-coded falls out of ordinary layout:
- Cross-facet alignment — facets are the same structure, so they line up.
- Stacked outer/inner labels — an inner facet's axis sits below its content, the outer facet's axis below the whole group; they stack naturally (the former
innerBaseline2×AXIS_WIDTH special case is gone). - Per-facet local scales — each facet wrapper resolves its tick
positionconstraints in its own frame, the frame of the keyed domain its content maps, so the old per-facet local-posScale special case is gone too. The ticks are detached in the ring's sharing sets (wrapRing), so their datums are no part of the type the ring reports: a chart's box reports its content's type to its parent, whatever chrome it wears (#1170). - Shared (overlay) axes — a
"budget"sibling is elaborated identically to thetrueowner; overlapping siblings simply overdraw the same axis, which keeps their content aligned without a reserved budget.
The three kinds
elaborateAxis is a pure function (returns { nodes, constraints }, no mutation), one branch per axis flavor — the seam a future public API would override. Since the #586 collapse POSITION and DIFFERENCE are no longer distinct space kinds but two origin states of the single continuous kind, so the branches dispatch on one read of the origin state, axisOver(space) ("absolute" for a pinned space, none for an origin-less one or a free magnitude), and isORDINAL rather than a kind tag, and the data interval is read off the type alone (continuousInterval(space)), never off the size claim. An origin-less space draws no axis: domainOver(space) reads it as "widths", a length scale, whose guide is a length entry in the legend:
POSITION (continuous, numeric origin) —
d3.nice+d3.ticksover the interval; an axis line (a 1pxrectauto-spanning the domain viadatumendpoints), and aspread([text, tickMark])per tick pinned withConstraint.position({ [axis]: datum(v) }). The gutter is negative space, which the ring claims;distribute([line, content])seats the line just past the plot's box, which covers the niced domain (see Axis lines frame the domain).align(end)sets the ticks flush against the line (their inner edge is the tick mark, so the label text ends up offset by the tick + gap inside each tick's spread). Over a mirrored space (CONTINUOUS_TYPE.mirrored, e.g. a stack centered on aHasMidpointcolumn, see Underlying Space) both sides of 0 hold amounts measured away from it, so each tick is labeled with its distance from 0 (60 40 20 0 20 40 60). The label follows from the space's type; there is no format option.TIME (continuous, pinned,
calendarset) — a partitioned axis (elaborateTimeAxis, #1057). It is a position axis: the same line, the same gutter seating, and every tick and label pinned at its instant withConstraint.position, so nothing sits in an ordinal slot: it is built by the samepositionAxisas a numeric axis, its row labels passed asextraLabels(each with its row's offset past the line).label.angledoes not rotate them yet (a rotated row would need its depth from the rotated label boxes), so they carry noaxisLabeltag andlabel.angle: "auto"does not score them. Its ticks and labels come from calendar partitions (CalendarPartitionincalendar.ts) instead ofd3.ticks, one row per partition (axes/timeRows.ts). Its domain is niced like a numeric axis's, by the sameniceContinuous, but outward to the cells of the inner row instead of to round numbers, so both ends of the axis are inner ticks. A row's ticks are where its labels sit (rowLabels): its cells' starts inside the domain, and each label is centered on its cell's start tick, as a numeric axis centers its labels. A row is just aCalendarPartition, and its labels are the partition's (label): the function given with.format(fn), else the level's default. A partition with a format has no wire form, so itstoJSONthrows. An outer row's first cell may start before the domain: its label is centered on the axis's first tick, under the inner row's first label ("2023" under "Nov"). A cell starting at the domain's end is labeled at the last tick. Like a numeric axis, it labels every tick and never drops a label; choosing ticks from the labels' room is #1063. Rows stack outward from the line by a fixed offset each, the row's text height (its widest label on a y axis) plus a gap, so the axis emits all its rows in one elaboration rather than one axis per row. Rows are independent partitions, so they need not nest. A tick both rows share is drawn once, short; an outer-row tick between inner ticks is longer. This is the opposite of an ordinal axis's dividers (below), on purpose. A time tick marks a point and aims at the middle of its label, so an outer tick stops where an inner row has its own tick and label at that point (they are aligned), and runs through the inner rows that lack one (unaligned) to reach its own label. The rows are the axis's levels (timeRows): a Calendar entry names a row, the outer row follows the inner row as named, andfalsehides a row's ticks and labels. The axis stamps its rows on its axis demand when it is elaborated, before any solve nices its domain, so the scope's nicing and the drawing read the same inner row. Without entries the inner row is the level and step whose cells are nearest in length to a tenth of the domain (tickPartitionincalendar.ts, like d3's time ticks, and like a numeric axis's ~10 ticks), and the outer row is that level's parent. Both choices read the domain only, never pixels. A time axis over calendar cells (CONTINUOUS_TYPE.cells, the months apartitiongives its groups; see Underlying Space) ticks at the cells' own partition instead (cellPartition, read byaxisTickPartition, so the nicing and the drawing agree), with its parent as the outer row. A row that cuts the same cells as the cells' partition (CalendarPartition.sameCells: the same level, step, and week start) names cells, not points: each label is the row's label of the cell, centered between the cell's two boundary ticks. Any other row, and every row of an axis over points, keeps its labels on its ticks. The axis's ticks reach its scope's nicing through the axis demand (AxisTicks: the tick count, and a time axis's rows, which the axis stamps when it is elaborated and records against its keyed domain,KeyedDomains.recordDemand), and the axis is drawn from the same stamp, so nicing and drawing read one source (see Underlying Space).ORDINAL — per key, a
text(key)plus aref(keyNode)stand-in bound directly to the laid-out key node. The labelalignsmiddlewith its ref along the axis (tracking its mark), anddistributes against the wrapped content layer (__axisInner) in the gutter dimension — so all labels share one row seated past the group's box (below the most-negative bar; below an inner facet's own label row), not each mark's own extent. This is the chain that makes nested facet labels stack: the inner row joins the facet's box, the facet boxes join the spread's box, and the outer row distributes against that. Key discovery uses_ordinalKeyMap(set by operators such astable) or a subtree walk bynode.key.An ordinal axis draws one row per level (
elaborateOrdinalAxis). A level groups the slots: each slot's group at that level, and a run of neighboring slots in one group is labeled once. The first level of a split has one group per slot, its label the key's text, or, over cells (ORDINAL_TYPE.cells, from a binned keyfield(x).bin(p); see Underlying Space), the cell's label (the partition'sformat,"0.5–1","Jan", or a product's"Jun 2015"). A chained key's cells hold their parent cells (KeyCell.parent), so the axis infers one more level per bin before the last: the slots grouped by theirk-th ancestor (the year of each month). A slot's label is centered on its key node, as above. A run's label is centered on anaxisSpan(axes/axisSpan.tsx) from the run's first slot's start to its last slot's end: a node whose layout reads the two nodes throughrefs, as a label reads its slot, so it is placed along the axis by its own layout and is free across it.The label rows of a dim form one stack measured from the plot edge, whichever axis draws them: the first row sits
ORDINAL_LABEL_GAPpast the edge, a row that divides the row before it (it partitions that row's value, ordividersays so; see below)ROW_GAPpast that row, and any other rowORDINAL_LABEL_GAPpast it, so spacing and dividers always agree, each by its depth as rotated (the boxturnedBoxingeometry/plane.tsmeasures). So one chained key and the same levels as nested splits stack alike, and a lake row sits past its species row as any axis sits past the content inside it. An outer axis learns how deep the rows inside it reach from the fold (LevelFold.rowEnd, the deepest any child drew) and seats its rows past them. This assumes the inner rows are the outermost part of the content on that side, which holds when the inner groups share a plot edge.Which levels draw dividers is a question about the data. A level partitions the value of the level inside it when both bin the same column: a year level over a month level of one date. The column cells bin is the field their ordinal space groups by (its title, the split's
by), so eachOrdinalLevelof cells knows its column, and two levels compare columns. A chained key's levels and aCalendarentry oflevelsare over one key, so they always partition; nested splits that bin one column (spreadbyfield("date").bin(Calendar.year), then byfield("date").bin(Calendar.month)), and numeric bins inside bins, do so across axes, where the fold carries the column of the inner axes' outer level (LevelFold.column, kept only when every child agrees). Categories nested in other categories (a lake over its species, months over weather) do not partition anything, so they draw no dividers. A level draws them when it partitions the level inside it, or when the axis'sdivideroption says so at its depth (trueon,falseoff), which wins. A plaindividerapplies to every ordinal level and skips continuous ones.Where they are drawn follows one rule: a divider runs through the rows of every level that has a boundary in its gap. In each gap between neighboring slots, the dim's visible rows, nearest the plot first, are the inner axes' rows and then this axis's levels. The inner axes' rows break in every gap, since an inner group never crosses this axis's slots. Each run of neighboring rows that break there gets one divider when one of its rows draws dividers: an
axisSpanfrom one slot's end to the next slot's start, which draws a 1px line in its middle across those rows. The first row's divider starts at the plot edge, and a later one's at the far edge of the row before it. A chart of months over weather categories, with a chained year above the months, thus has one divider, between the years, and it runs from the plot edge through the weather row, the month row and the year row.This is the opposite of a time axis's ticks, on purpose. A divider separates regions, so it runs through every level whose regions also break at that gap (they are aligned) and stops at a level whose region continues across it (unaligned). A time tick marks a point, so it runs through the rows that do not share it to reach its label. It is the same points-versus-cells rule that places labels: a point's label centers on its tick, and a cell's label is placed by its region.
Where a level's labels sit along the axis is the axis's
label.alignoption, per depth likelabel.angle, else inferred from what the label means. A centered label collects the groups beneath it, which have no order. A start-aligned label marks where a run of ordered values begins, as a calendar's month labels do. So an outer level over ordered groups (cells, or a split over a column withHasOrder, read off the space'sORDINAL_TYPE.hasOrder; calendar levels fromlevelsentries are cells) puts each label at the start of its run, and every other level centers: an outer level over categories, and the innermost level, one label per slot. A start-aligned label centers on arunStartBox(axes/axisSpan.tsx), a box as long as the label that startsLABEL_TICK_GAPpast the divider before the run, or at the first slot's start for the axis's first run. The box reads which way the slots run off the layout (from the axis's first slot to its last), so a reversed or bottom-up axis puts it on the run's side. A continuous axis's labels name points, its ticks, so they stay centered on them: a plainlabel.align: "start"skips its levels, and"start"in a list at one of its depths is an error.axisSpanis a bake boundary (BAKE_BOUNDARY_TYPESinbake.ts), since it draws itself and its children arerefstand-ins.
Axes are drawn at chart boundaries
A continuous axis is drawn only at a chart() boundary (#1114 step 6). GoFishNode.isAxisBoundary is the rule: a chart (_chartBox, set by the chart builder) draws its axes around itself, sized or not (#1257), and the render root is the outermost boundary, which draws the axes of the domains it solves, a bare low-level render's included. A tick does not need to share its plot's σ to sit on its scale: each tick, the axis line's span and the line's seat at the other axis's floor are position constraints that read their datums in the plot's frame (in, internal for now, #1289), so an axis outside a chart with a size of its own still maps with the σ that size solved. A chart is placed whole, its baseline with it, so a chart's own free baseline is placed (placedSpace): a bar chart beside a caption in a spread draws the value axis it draws on its own (#1170). On an axis the render gives no size, the root maps its domain at the σ the sized nodes below it solve it at, when they agree, so a bare spread of 160 px mini charts draws a 160 px axis (rootSizes in gofish.tsx, which reads the σ from ScopeRegistry.keyedSigma). The render root is an implicit chart and nothing more: a bare render draws the axes a chart() in its place would draw. A piece placed apart from the rest (detached by a literal position, so the root's type does not cover it) draws an axis only if it is a chart() itself. An ordinal axis the root draws on a dim still owns that dim, so a continuous level below it waits for hierarchical axes (#1115).
A chart's content is everything it draws. frameChart builds a chart's node as its frame over one content layer: a chart's marks and the transitions it draws over them, or every tier of a .layer(...) chart, the root tier's own nodes first (LayerBuilder.resolve). The frame (its w/h and its coord) has that one child, so a chart draws its axes around all of it, and every tier's marks and the axis map with the σ that frame solves. A tier that is a chart of its own is inside that content, below the node that claimed the axis, so it does not draw a second one. A chart nested in another chart's content is still a boundary, but it draws only an axis no node above it claimed: the outer chart claims each axis its type covers first, and a continuous axis has one owner.
Each chart's axes option applies at that chart. frameChart stamps it on the chart's node (_chartAxes, default true), and resolveAxes carries what the nearest chart decides on each dim (axesEnabled) down its walk; the root's is the render's axes, which is the outermost chart's own unless the render gives one. A node that claims an axis on a dim its chart turns off still owns it, so the axis is hidden, not drawn by a chart below. A nested chart with axes: false turns off only the axes it owns. A render that passes no axes and has no chart at its root (a bare render, or a combinator of charts such as spread({ dir: "y" }, [caption, chart])) decides neither dim, so its root claims no axis and each chart inside it draws its own, as it would rendered alone (#1170). The titles follow each chart's own options (see Axis titles below); the sides and per-level options (levels, label, divider) still come from the render's axes alone.
resolveAxes decides the boundaries in its one top-down walk, asking each node once. No other node claims a continuous axis, so a spreadY that middle-aligns a caption with a chart does not. Two exceptions remain until #1032 and #1115: an operator's explicit axes: override still draws at its node, and an ordinal axis still nests at every grouping level.
One axis per keyed domain
resolveAxes (_node.ts) is a top-down walk: a claimed map threads DOWN each branch so a continuous axis is single-owner (root-most unclaimed wins) and an ordinal axis nests by grouping signature ("o:<keys>"). A continuous claim carries a signature too: the keyed domain the axis is drawn over (its space root and its unit's key, KeyedDomains.axisKey, see Underlying Space), as "c:<key>". An explicit axes:{x:true} override on a node whose keyed domain an ancestor already draws is the same axis again, so it is suppressed, as an override on an already-drawn ordinal grouping is. A ridgeline's rows each ask for an x axis, and the chart draws the one axis over their shared domain.
The axis shows the node's keyed domain, not only the part of it the node's own data covers (elaborationsFor widens the node's space to it), so a facet panel's axis spans the domain every panel maps. elaborationsFor returns at once for a node that draws neither axis. A node that draws one widens and nices both dims, since an axis reads its own dim's nice and the other dim's floor, where a facet panel seats its axis line (#753).
The scale-sharing seam
The wrapper layer "owns" the POSITION axis via its tick position constraints, so content and ticks resolve against one scale. layer.tsx forwards that scale (effectivePosScales) to non-target content children whose own space is POSITION (e.g. a scatter's points), while withholding it from the ticks (placed by the constraint) and from SIZE content (bars), whose alignment would break if a posScale leaked in. This per-child decision is what lets a data-positioned chart and its elaborated axis share a coordinate frame.
Axis titles
A title is a ring of the chrome of the node that owns its axis. elaborateChrome titles each axis the node draws from the axes options in the node's chrome request (chartAxisTitle), with the title of that axis (spaceTitle: its quantity names joined with ", ", never its unit), read off the node's own space before elaboration re-resolves it. That is why a grouped bar chart's x title names the outer grouping ("lake") and not the inner one ("species"): the inner axes inserted below the root would change the root's space after elaboration.
Each chart titles the axes it draws, wherever it sits (#1170). layout() stamps every chart's axes options on it as its request: the render's on the root, and each nested chart's own (_chartAxes) on it. A node titles each axis it owns that its request turns on, with the option's title or else the space's title. So a chart beside a caption in a spread, or each panel of the Gapminder curves row, titles its own axes. A node that is no chart carries no request, so an axis an operator's override draws gets no title.
A coordinate space owns no cartesian axes (resolveAxes clears them), so a pie gets no cartesian title. It titles its own axes (the radial title, see Flattening the Scenegraph).
The title ring (axisTitles) centers each title on the axis shape it describes, not on the plot:
- The anchor is the axis's own span, which
AxisElaborationcarries asanchor: the axis line of a continuous axis, and for an ordinal axis anaxisSpanfrom its first slot's start to its last slot's end, which draws nothing. So a category axis's title centers on the plot, not on the owner's content box, which holds the other axis's gutter when the other axis is drawn by a node inside it. Only an ordinal axis with no slots falls back to the content box. - The anchor is referenced with a
ref(anchorNode)stand-in, the same direct-noderefformelaborateOrdinalAxisuses. The anchor sits in a ring inside the title ring, so it is placed by the time the constraints read the ref, andalign({ [dim]: "middle" }, [ref, title])moves only the title. - A
distributethen seats the titleTITLE_CONTENT_GAP = 8pixels past the ring inside it, which holds the tick and category label rows, so the title never overlaps them. Listing the title before the box seats it on the start edge, and after the box on the end edge. - The y title is built with the
Textrotate: -90option, so it reads bottom to top in the left gutter. The x title is horizontal.
The legend ring is outside the title ring, so the legend is seated past the titles, and the title centering never sees the legend column.
The two builders xAxisTitle and yAxisTitle are pure, exported functions. They are the place to change how a title looks, like legendColumn for the legend.
What this replaced
The former bespoke pipeline — shapes/axis.tsx (custom GoFishNodes with hand-written SVG render()), plus ~260 lines of axis budget / innerBaseline / content-shift / per-facet local-posScale machinery in _node.ts and a baseline cancellation in spread.tsx — has been deleted. resolveAxes remains (it feeds the pass, and its persistent axisDemand stamps drive the demand-driven per-scope domain nicing at the σ-scope solves); the former resolveNiceDomains tree walk is gone (issue #659 — nicing now happens once per σ-scope, at the solve). The chart-level axes option still drives both the axes and their titles. Axis titles used to render as raw <text> elements in gofish.tsx's render() behind fixed 40px margins, and later as one wrapper around the whole chart. Both are gone: a title is now a ring of its axis owner's chrome. Polar/coord axes are still drawn by coord.tsx and are not yet elaborated.
