# Elicit.js documentation
> Elicit.js is a grammar for visual elicitation: declarative charts that people edit to tell you what they think. Each gesture maps back through the chart's scales and writes the dataset. Elicit.js 0.5.0-alpha.0. Generated from https://elicitjs.github.io/; the index is https://elicitjs.github.io/llms.txt.
---
# Elicit.js
> Source: https://elicitjs.github.io/ · Elicit.js 0.5.0-alpha.0
Elicit.js is a grammar for **visual elicitation**. It gives you a concise way to build visualisations that work as elicitation interfaces: charts people can change to tell you what they think.
- [Get started →](https://elicitjs.github.io/start.md)
- [API reference](https://elicitjs.github.io/api.md)
- $ npm install elicitjs
Alpha: pre-1.0 and under active development, so expect breaking changes. ESM-only, with `d3` v7 as a peer dependency.
## Turn a chart into a question
Scroll down to learn what you can build with Elicit.js. Things are interactive so feel free to touch the bars when it looks like it is interactive!
## Ask with any mark
Pick a chart from the grid to try it large. The large chart and its small copy share one dataset, so the small one follows your answer.
## Where to go next
- [**Getting started** Build a chart from scratch and read its answer](https://elicitjs.github.io/start.md)
- [**Core concepts** Schema, channels, scales, and the encode/edit duality](https://elicitjs.github.io/concepts.md)
- [**Editing** Gestures, handles, and multi-step stages](https://elicitjs.github.io/editing.md)
- [**Marks** The drawing vocabulary, one page per mark](https://elicitjs.github.io/marks/bar.md)
- [**JSON specs** The same grammar as data, for storage and models](https://elicitjs.github.io/json.md)
- [**Playground** Compose a chart from menus and read the code](https://elicitjs.github.io/playground/)
---
# Getting started
> Source: https://elicitjs.github.io/start/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
Install Elicit.js, build an elicitation interface with `Elicit(spec)`, make it editable by putting an `edit` on a channel, and read the answer back through `onChange`. Every example on these pages runs the code beside it.
## Install
Elicit.js is ESM-only. Use it with a bundler (Vite, webpack, Next) or an import map.
```bash
npm install elicitjs
```
`d3` v7 is a peer dependency. npm 7+ and pnpm 8+ install it for you; on Yarn, add it yourself with `yarn add elicitjs d3`.
```javascript
export const Elicit = globalThis.__llms.comp("Elicit");
export const plot = globalThis.__llms.comp("plot");
export const edit = globalThis.__llms.comp("edit");
export const constraints = globalThis.__llms.comp("constraints");
```
Types ship with the package, so TypeScript needs no separate `@types` install. `elicitjs/dist` is a prebuilt single-file bundle if you would rather not bundle the source.
For a plain HTML page, map both names in an import map:
```html
```
## Built through a spec
An elicitation interface is built through a declarative spec. `Elicit(spec)` takes one object and returns a chart. Append `chart.dom()` to the page. A spec has three main keys:
- `data` — the rows of the dataset. Every mark is a view over them.
- `schema` — each field's **type** and **domain**. Scales are derived from this, so no mark declares one.
- `marks` — how the rows are drawn.
Only `schema` is required. Leave out `data` to start from an empty chart. To draw one dataset in several charts, see [Datasets & linked charts](https://elicitjs.github.io/dataset.md).
### Example: A static bar chart
A complete spec: data, schema and one mark. Nothing here is editable yet.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
// The DATA — one dataset, and every mark is a view over it.
data: [
{ cat: "A", n: 30 }, { cat: "B", n: 55 },
{ cat: "C", n: 22 }, { cat: "D", n: 44 },
],
// The SCHEMA — what each field IS. Every scale is derived from this.
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
// The MARKS — how the rows are drawn.
marks: [
barY({
fill: "#50AEB7",
channels: { x: { field: "cat" }, y: { field: "n" } },
}),
],
});
mount(chart.dom());
```
A mark names its columns in `channels`. `x: { field: "cat" }` encodes `cat` on the x position. The schema declares `cat` as `categorical` and a bar needs an interval, so that resolves to a band scale.
## Reading the examples
The examples on this site name each mark, element, constraint and universal edit bare: `barY(...)`, `axisX(...)`, `clamp(...)`, `move()`. In your code they are members of the namespaces you import. Destructure them to write the same short form:
```javascript
export const Elicit = globalThis.__llms.comp("Elicit");
export const plot = globalThis.__llms.comp("plot");
export const elements = globalThis.__llms.comp("elements");
export const edit = globalThis.__llms.comp("edit");
export const constraints = globalThis.__llms.comp("constraints");
const { barY } = plot;
const { axisX } = elements;
const { clamp } = constraints;
const { move, when } = edit;
```
Scoped edits, guides, layouts, looks and widgets keep their namespace in the examples, as in `edit.line.draw()`, `guides.rule()` and `widgets.likert()`.
`mount(node)` is the docs page's helper: it places the node beside the code. In your page, write `parent.append(chart.dom())`.
## Make it editable
An edit is the inverse of encoding. A channel encodes data to pixels through a scale. An `edit` on that channel maps a gesture back through the same scale, and writes the column the channel names.
### Example: The same chart, now editable
`edit: move()` on the y channel. Dragging a bar inverts the y scale and writes `n`.
Try: **Drag** any bar up or down.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
data: [
{ cat: "A", n: 30 }, { cat: "B", n: 55 },
{ cat: "C", n: 22 }, { cat: "D", n: 44 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
marks: [
barY({
fill: "#50AEB7",
channels: {
x: { field: "cat" },
// One added word. `move()` inverts the y scale, so a drag writes `n`.
y: { field: "n", edit: move() },
},
}),
],
});
mount(chart.dom());
```
A mark is inert until an edit names the column it writes.
`move()` is one of the universal edits, which work on any mark. Others create and delete rows, draw a path, turn a needle, pick a category from a legend, or rewrite a scale's domain. See [Editing](https://elicitjs.github.io/editing.md) for the vocabulary, or the [API index](https://elicitjs.github.io/api.md) for every name.
## Read the answer back
Three ways to get the elicited data:
- `onChange(data)` fires after every committed edit, with the whole dataset.
- `chart.getData()` returns it on demand.
- `chart.on("change", cb)` subscribes a listener to the same commits.
### Example: Reading the elicited data
`onChange` writes the current values under the chart.
Try: **Drag** a bar — the numbers below follow.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
data: [
{ cat: "A", n: 30 }, { cat: "B", n: 55 },
{ cat: "C", n: 22 }, { cat: "D", n: 44 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
// Fires after every committed edit, with the whole dataset.
onChange: (data) => {
readout.textContent = data.map((d) => `${d.cat}: ${Math.round(d.n)}`).join(" ");
},
marks: [
barY({
fill: "#50AEB7",
channels: { x: { field: "cat" }, y: { field: "n", edit: move() } },
}),
],
});
const readout = document.createElement("pre");
readout.style.cssText = "font-size:12px;margin:8px 0 0;color:#6F8294";
readout.textContent = chart.getData().map((d) => `${d.cat}: ${d.n}`).join(" ");
mount(chart.dom());
mount(readout);
```
The chart also carries `getSchema()`, `setData()`, `on("stage" | "select", cb)`, `undo()`, `redo()` and `destroy()`. Call `destroy()` when you unmount it in a framework, to release its resize observer and pointer handlers.
## Constrain what can be said
A constraint is a rule over the dataset. It applies to every edit and every mark, so declare it once in `constraints: [...]` on the spec.
### Example: Four bars that always sum to 100
`clamp` keeps values non-negative. `maintainSum` with `strategy: "redistribute"` holds the bar you drag and adjusts the others so the total stays 100.
Try: **Drag** a bar — the others compensate.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
data: [
{ cat: "A", n: 25 }, { cat: "B", n: 25 },
{ cat: "C", n: 25 }, { cat: "D", n: 25 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 100] },
},
// A rule about the DATA, not about any one mark. It holds for every edit.
constraints: [
clamp({ min: 0 }),
maintainSum({ total: 100, strategy: "redistribute" }),
],
marks: [
barY({
fill: "#50AEB7",
channels: { x: { field: "cat" }, y: { field: "n", edit: move() } },
}),
],
});
mount(chart.dom());
```
A constraint can reject a proposed change, or repair it by returning corrected rows. See [Constraints](https://elicitjs.github.io/constraints.md) for the full set.
## Widgets
Common survey instruments are one call each. Each returns a spec you pass to `Elicit`, so you can start from a widget and edit its spec.
```javascript
export const Elicit = globalThis.__llms.comp("Elicit");
export const widgets = globalThis.__llms.comp("widgets");
const chart = Elicit(widgets.likert({
question: "How confident are you?",
options: ["Not at all", "Slightly", "Moderately", "Very", "Extremely"],
}));
document.body.append(chart.dom());
```
`likert`, `multipleChoice`, `slider`, `matrix`, `lineCone`, `ranking`, `allocation`, `probabilityTokens`, `interval`, `histogram`, `region`, `thermometer` and `labeledValue` are documented on [Widgets](https://elicitjs.github.io/widgets.md).
## API reference
### `Elicit(spec)`
The entry point: `import { Elicit } from "elicitjs"`. Builds a dataset and one chart over it from one spec, and returns the **chart**. Append `chart.dom()` to the page. The spec takes the dataset keys and the chart keys below. For several charts over one dataset, call `Elicit.dataset` and `ds.chart` instead — see [Datasets & linked charts](https://elicitjs.github.io/dataset.md).
JSON keyword: `spec`
```ts
Elicit({ schema, data?, marks, width?, height?, … }) → Chart
parent.append(chart.dom())
Elicit.dataset({ schema, data?, … }).chart({ marks, … }) // the same thing, in two calls
```
Returns / emits: A **Chart**, which also carries the dataset’s methods. The dataset deep-copies `data` and owns it; marks re-derive from the committed rows on every render.
### `Dataset keys`
What `Elicit.dataset(spec)` reads, and the part of an `Elicit(spec)` spec that describes the data. Every chart over the dataset shares these.
JSON keyword: `spec`
```ts
Elicit.dataset({ schema, data?, constraints?, lock?, context?, onChange? }) → Dataset
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `schema` | `Schema` | `required` | Field → measurement type / domain / default. Owns every field’s data type and **domain** — marks never declare one. See [Data schema](https://elicitjs.github.io/schema.md). |
| `data` | `Datum[]` | `[]` | The seed rows. Every mark in every chart is a *view* over them. May be empty when `create` will mint rows from the schema. |
| `constraints` | `Constraint[]` | `[]` | Dataset invariants that gate or repair every edit, from every chart. The only place they go. See [Constraints](https://elicitjs.github.io/constraints.md). |
| `lock` | `LockSpec` | | Read-only rows. See [Locked rows](https://elicitjs.github.io/editing/existence.md#seed). |
| `context` | `ContextSpec` | | Reference rows: drawn, read-only, and left out of `getData()`. See [Context rows](https://elicitjs.github.io/editing/existence.md#context). |
| `onChange` | `(data) => void` | | Called with the committed data once per commit, whichever chart made it. Hover previews never fire it. |
### `Chart keys`
What `ds.chart(spec)` reads: how one chart draws and edits the dataset. Each chart over a dataset has its own.
JSON keyword: `spec`
```ts
ds.chart({ marks, width?, height?, … }) → Chart
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `marks` | `Mark[]` | `[]` | The marks — `bar(...)`, `point(...)`, `composite(...)`, … drawn in array order (later marks on top). Auto-axes and edit guides keep their own layers behind / in front of marks. |
| `elements` | `ChartElement[]` | `[]` | Scale chrome — [axis](https://elicitjs.github.io/marks/axes.md), grid, [legend](https://elicitjs.github.io/marks/legend.md), [axisRadial](https://elicitjs.github.io/marks/axis-radial.md). Drawn alongside `marks`; the split only separates chrome from data in your own source. |
| `scales` | `Record` | `derived` | Chart-level scale overrides keyed by channel (`x`, `y`, `fill`, …). Domains stay on the schema. See [Scales & channels](https://elicitjs.github.io/scales.md). |
| `width / height` | `number` | `600 / 400` | Outer pixel size of the chart. |
| `margins` | `{top,right,bottom,left}` | `{20,20,30,40}` | Inset around the inner plot (leaves room for axes). |
| `responsive` | `'fixed' \| 'scale' \| 'reflow' \| true` | `'fixed'` | Sizing mode — see [Responsive sizing](https://elicitjs.github.io/sizing.md). |
| `motion` | `false \| { duration }` | `{ duration: 220 }` | Eased drawing. A hierarchy's layout, and every mark with `motion: true`, glides to its new place over `duration` ms. Effects fade over the same time (see [Effects](https://elicitjs.github.io/effects.md#motion)). `false` draws every change at once. Off when the reader's system asks for reduced motion. See [Hierarchy](https://elicitjs.github.io/marks/hierarchy.md#gestures) and [Ranking](https://elicitjs.github.io/widgets.md#ranking). |
| `looks` | `Look[]` | `none` | Experimental. How the finished chart is drawn: by hand, or through a shader. See [Looks](https://elicitjs.github.io/looks.md). |
| `layout` | `LayoutSpec[]` | `none` | Spatial layouts. Each settles the marks in pixels after an edit and writes the result back to the rows. See [Layout](https://elicitjs.github.io/layout.md). |
| `clip` | `boolean \| { padding }` | `on with edit.view.zoom or edit.view.pan` | Confine the marks to the plot rect, so a zoomed mark stops at the axes. `padding` grows the rect by that many pixels. See [Clip to the plot](https://elicitjs.github.io/editing/axis.md#clip). |
| `focusOutline` | `boolean` | `false` | Browser focus ring on editable marks. Off by default — Tab / arrow keys still work. See [Keyboard nudging](https://elicitjs.github.io/editing/gestures.md#keyboard). |
| `axes` | `object \| false` | `auto` | Global axis convenience — desugars into axis/grid marks; `false` drops them. |
| `view` | `{ edits }` | | Edits on the view itself: `edit.view.zoom()` and `edit.view.pan()`. See [Zoom & pan](https://elicitjs.github.io/editing/axis.md#wheel). |
| `guides` | `Guide[]` | `[]` | Non-interactive annotations rebuilt every render. |
| `effects` | `object` | `defaults` | Feedback for interaction state: `hovered`, `selected`, `target` and `grabbed`. See [Hover & selection effects](https://elicitjs.github.io/effects.md). |
| `legends` | `boolean \| object` | `none` | `true` draws one legend per bound non-positional scale; an object configures or suppresses each. Off by default, unlike `axes`, because a legend reserves layout space. See [Legend](https://elicitjs.github.io/marks/legend.md). |
| `title / subtitle / caption` | `string` | | Text above the plot (title, then subtitle) and below it (caption). Like a legend, they reserve layout space, so the chart keeps its declared size and the plot shrinks. Styled by the theme’s `title` / `subtitle` / `caption` tokens. See [Theming](https://elicitjs.github.io/theming.md#titles). |
| `theme` | `object \| string` | `the app default` | Per-chart theme, over whatever `setTheme()` set. See [Theming](https://elicitjs.github.io/theming.md). |
| `projection` | `string \| object` | | Turns the plane into a map; auto-axes go off when it is set. See [Geo](https://elicitjs.github.io/marks/geo.md). |
| `stage / stageLabels` | `number / string[]` | `0 / []` | The stage a multi-step elicitation starts on, and the caption for each. See [Stages](https://elicitjs.github.io/editing/probe.md#basics). |
| `overflow` | `'hidden' \| 'visible'` | `'hidden'` | Whether marks are clipped to the plot viewport. 'visible' lets a radial or gauge label sit in the margin band. |
| `renderer` | `'svg' \| 'canvas' \| Renderer` | `'svg'` | Draws the scene and reports gestures. `'svg'` draws SVG; `'canvas'` draws to a canvas. A JSON spec takes the same names. A renderer instance of your own works too. See [Renderers](https://elicitjs.github.io/renderers.md). |
### `The dataset`
What `Elicit.dataset` returns. It reads and writes the data from outside any chart, and every chart over it redraws on a change. A chart carries the same methods, so `chart.getData()` is `chart.dataset.getData()`.
No JSON form: this is called in JavaScript.
```ts
ds.chart(spec) → Chart
ds.getData() → Datum[]
ds.getSchema() → Schema
ds.setData(data) → void
ds.setDomain(field, domain, { table? }) → boolean
ds.set(field, value, { index?, table? }) → boolean
ds.on("change" | "select" | "hover", cb) → () => void
ds.undo() · ds.redo() · ds.canUndo() · ds.canRedo()
ds.transaction() → () => void
ds.hover(row) · ds.getHover()
ds.select(i) · selectWhere · toggleSelection · selectAll · clearSelection
ds.getSelection() · ds.getSelectionAll()
```
Options:
| Option | Type | Description |
| --- | --- | --- |
| `chart(spec)` | `→ Chart` | A chart over this dataset. Make as many as you need. See [Datasets & linked charts](https://elicitjs.github.io/dataset.md). |
| `getData()` | `→ Datum[]` | A deep **copy** of the committed data — the elicited answer. Copy, because handing out the live rows would let a caller mutate past every constraint the dataset just enforced. |
| `getSchema()` | `→ Schema` | A deep copy of the dataset’s schema, including any domain an [editable axis](https://elicitjs.github.io/editing/axis.md) reshaped. Your original `spec.schema` is never mutated. |
| `setData(data)` | `void` | Replace the rows and redraw every chart. Bypasses constraints — it is a trusted seed or reset, not an edit — and clears the [undo history](https://elicitjs.github.io/editing/history.md) for the same reason. |
| `setDomain(field, domain)` | `→ boolean` | Set a field’s domain, for a zoom button or a reset. One undo step; `null` restores the declared domain. Every chart shares the domain. See [Zoom & pan](https://elicitjs.github.io/editing/axis.md#set-domain). |
| `set(field, value, options?)` | `→ boolean` | Write one cell from outside any chart. Runs the dataset’s constraints and the lock; one undo step. See [Write from outside a chart](https://elicitjs.github.io/dataset.md#set). |
| `on(type, cb)` | `→ unsubscribe` | `change` fires once per commit with the new data; `select` fires when the [selection](https://elicitjs.github.io/editing/selection.md) moves; `hover` fires when the [linked hover](https://elicitjs.github.io/dataset.md#hover) moves. Returns a function that removes the listener. |
| `undo() / redo()` | `→ boolean` | Step one **gesture**, whichever chart it happened in, and report whether they moved. See [History & undo](https://elicitjs.github.io/editing/history.md). |
| `transaction()` | `→ () => void` | Hold one undo step open. Every write until you call the returned function undoes as one step. See [Several writes, one undo step](https://elicitjs.github.io/editing/external-controls.md#transaction). |
| `hover(row) / getHover()` | `→ boolean / row` | Set and read the hovered row, which every chart with a linked hover shows. A row of the primary table is its index, another table's row is `{ table, index }`. `hover(null)` clears it. See [Linked hover](https://elicitjs.github.io/dataset.md#hover). |
| `select(i) / selectWhere / toggleSelection / selectAll / clearSelection` | `→ boolean` | Set which rows are selected, by index or by a field match. Every chart shows the selection. See [Selection](https://elicitjs.github.io/editing/selection.md). |
| `getSelection() / getSelectionAll()` | `→ row \| row[]` | The selected row (the lowest index), and every selected row. A row of the primary table is its index; a row of another table is { table, index }. |
Returns / emits: `change` is the seam to the rest of your app: a survey posts `getData()` on submit, a live app writes it through on every commit.
### `The chart`
What `Elicit` and `ds.chart` return: a plain object, not a DOM node. `dom()` is the node to append. It carries every dataset method above, plus its own.
No JSON form: this is called in JavaScript.
```ts
chart.dom() → HTMLDivElement
chart.dataset → Dataset
chart.on("change" | "select" | "hover" | "stage" | "render" | "destroy", cb) → () => void
chart.getStage() · chart.setStage(i) · chart.nextStage() · chart.getStageLabel()
chart.control(name, target?) → EditControl
chart.scene(query?) · chart.hit(point) · chart.scale(channel) · chart.edits(query?)
chart.metrics() · chart.toInner(point) · chart.toClient(point)
chart.theme → Theme
chart.emit(event) → void
chart.destroy() → void
chart.destroyed → boolean
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `dom()` | `→ HTMLDivElement` | | The chart's container. Append it where you like; it is the same node on every call. |
| `dataset` | `Dataset` | | The dataset this chart reads and writes. For `Elicit(spec)`, the one built from the same spec. |
| `on("stage" \| "render" \| "destroy", cb)` | `→ unsubscribe` | | `stage` fires when this chart’s [stage](https://elicitjs.github.io/editing/probe.md#basics) changes. `render` fires after every frame the chart draws, and `destroy` once when `destroy()` is called. `change`, `select` and `hover` are the dataset’s. |
| `getStage() / setStage(i) / nextStage() / getStageLabel()` | `→ number \| string \| void` | | Read and drive a multi-step elicitation from outside. Stages are per chart. See [Stages](https://elicitjs.github.io/editing/probe.md#basics). |
| `control(name, target?)` | `→ EditControl` | | Replay a gesture on this chart through a named edit (a slider, a picker). Same dispatch as the pointer — constraints, undo, and `change` all run. `target` is a row index (default `0`), or `{ index, channel, side }` to name [one handle of a row](https://elicitjs.github.io/editing/external-controls.md#targets). See [External controls](https://elicitjs.github.io/editing/external-controls.md). |
| `scene() / hit() / scale() / edits()` | `→ views` | | Read what the chart draws: the drawn pieces, the piece at a point, a channel’s scale, and the edits that can run now. Every value is a copy. See [Reading the chart](https://elicitjs.github.io/editing/external-controls.md#reading). |
| `metrics() / toInner(point) / toClient(point)` | `→ ChartMetrics / Point` | | The chart’s size and margins, and the conversion between viewport pixels (`clientX`, `clientY`) and plot pixels. |
| `theme` | `Theme` | | A copy of the chart’s resolved theme: the defaults, then `setTheme()`, then `spec.theme`. |
| `emit(event)` | `void` | | Low-level: inject a renderer-shaped gesture event (inner pixels). Prefer `control` unless you already hold pixels. |
| `destroy()` | `void` | | Detach the chart from its dataset and stop its observers. Call it when you unmount the chart — a resize-observing chart outlives its node otherwise. Other charts on the dataset keep working. |
| `destroyed` | `boolean` | `false` | True once destroy() has run. Read-only. |
## Where to go next
- [**Core concepts** Schema, channels, scales, and the encode/edit duality](https://elicitjs.github.io/concepts.md)
- [**API index** Every name in the grammar, searchable](https://elicitjs.github.io/api.md)
- [**Marks** The drawing vocabulary, one page per mark](https://elicitjs.github.io/marks/bar.md)
- [**Editing** Gestures, handles, and multi-step stages](https://elicitjs.github.io/editing.md)
- [**Widgets** Ready-made survey instruments](https://elicitjs.github.io/widgets.md)
- [**Playground** Compose a chart from menus and read the code](https://elicitjs.github.io/playground/)
---
# Using Elicit.js with coding agents
> Source: https://elicitjs.github.io/start/agents/ · Elicit.js 0.5.0-alpha.0
An agent can ask you with a chart instead of a question in words. In a chat, it shows an Elicit.js card, you answer by dragging, drawing or clicking, and it reads your answer as rows. In a codebase, it writes Elicit.js into your app. The `elicitjs-mcp` server and the agent skill that ships with the package give it both.
## Quick start
Paste this into your agent. It sets up the server, checks it, and asks you a first question.
```text
Help me set up Elicit.js for my agent.
1. Add the Elicit.js MCP server to my client. It runs with: npx -y elicitjs-mcp
Set ELICITJS_MCP_MODE to "chat" if you will ask me questions in this chat,
or "build" if you are writing Elicit.js into this project.
2. If we are in a project folder, run: npx -y elicitjs-mcp setup
so every agent here reads the Elicit.js skill.
3. Check it works: list the Elicit.js widgets.
4. Then ask me something with a chart: how I split my week between
work, sleep, people and play.
```
To set it up by hand, see [Install and configure](#install).
## What you can ask
Each chat below is live. Answer the card: the line under it is what the agent reads while you work, and **Submit** sends it as your next message.
### Split a budget
You: We have $100k for next quarter. Ask me how I'd split it across hiring, marketing, tools and travel.
Agent: Drag each bar to set its share. The four always add up to 100.
```json
{
"widget": {
"type": "allocation",
"question": "How would you split next quarter’s budget?",
"categories": [
"Hiring",
"Marketing",
"Tools",
"Travel"
],
"total": 100
}
}
```
### Draw a forecast
You: I have a hunch about our sign-ups for the next ten weeks. Let me draw it instead of typing numbers.
Agent: Draw your forecast on the card. I'll compare it with the real numbers as they come in.
```json
{
"title": "Weekly sign-ups, the next 10 weeks",
"caption": "Draw the line from left to right. Draw again to redo a stretch.",
"width": 440,
"height": 300,
"margins": {
"top": 14,
"right": 16,
"bottom": 30,
"left": 40
},
"data": [],
"schema": {
"s": {
"type": "categorical"
},
"week": {
"type": "quantitative",
"domain": [
1,
10
]
},
"signups": {
"type": "quantitative",
"domain": [
0,
500
]
}
},
"marks": [
{
"type": "lineY",
"stroke": "#50AEB7",
"strokeWidth": 3,
"curve": "catmullRom",
"channels": {
"series": {
"field": "s"
},
"x": {
"field": "week"
},
"y": {
"field": "signups"
}
},
"edits": [
{
"type": "line.draw",
"along": "x",
"value": "y",
"series": "s",
"samples": 10
}
]
}
]
}
```
### Show a feeling
You: The launch is next week. Ask me how I'm feeling about it.
Agent: Shape the face until it looks the way you feel.
```json
{
"title": "How do you feel about the launch?",
"caption": "Drag the mouth up or down, and an eye sideways.",
"width": 300,
"height": 320,
"margins": {
"top": 12,
"right": 12,
"bottom": 12,
"left": 12
},
"data": [
{
"valence": 0,
"arousal": 0
}
],
"schema": {
"valence": {
"type": "quantitative",
"domain": [
-1,
1
]
},
"arousal": {
"type": "quantitative",
"domain": [
-1,
1
]
}
},
"marks": [
{
"type": "face",
"channels": {
"mouthCurve": {
"field": "valence",
"edit": {
"type": "slide",
"axis": "y",
"increase": "up"
}
},
"eyeScale": {
"field": "arousal",
"edit": {
"type": "slide",
"axis": "x",
"increase": "right"
}
}
}
}
]
}
```
### Point to a likelihood
You: How likely is it that we ship by March? Ask me in words, not percentages.
Agent: Point the needle at how likely you think it is.
```json
{
"title": "Will we ship by March?",
"caption": "Drag the needle.",
"width": 380,
"height": 255,
"margins": {
"top": 64,
"right": 80,
"bottom": 20,
"left": 80
},
"axes": false,
"overflow": "visible",
"data": [
{
"chance": "Toss-up"
}
],
"schema": {
"chance": {
"type": "ordinal",
"domain": [
"Very unlikely",
"Unlikely",
"Somewhat unlikely",
"Toss-up",
"Somewhat likely",
"Likely",
"Very likely"
]
}
},
"marks": [
{
"type": "axisRadial",
"outerRadius": 110,
"bands": true,
"bandWidth": 22,
"tickSize": 0,
"tickPadding": 18,
"fontSize": 8,
"channels": {
"theta": {
"field": "chance",
"scale": {
"range": [
180,
0
]
}
},
"fill": {
"field": "chance",
"scale": {
"scheme": "dddiverging"
}
}
}
},
{
"type": "needle",
"length": 95,
"fill": "#EE7B5E",
"channels": {
"theta": {
"field": "chance",
"scale": {
"range": [
180,
0
]
},
"edit": {
"type": "rotate",
"pivot": "mark",
"fold": false,
"pick": "direct"
}
}
}
},
{
"type": "text",
"fontSize": 14,
"dy": 32,
"channels": {
"text": {
"field": "chance"
},
"textAnchor": {
"value": "middle"
},
"lineAnchor": {
"value": "middle"
}
}
}
]
}
```
### Build a diagram together
You: Help me map what drives churn. Start a diagram and I'll add to it.
Agent: Here's a start with three ideas. Add yours, link what causes what, and rename anything.
```json
{
"title": "What drives churn?",
"caption": "Drag a node to move it. Click empty space to add one. Shift-drag from one node to another to link them. Double-click a label to rename it.",
"width": 460,
"height": 300,
"margins": {
"top": 24,
"right": 24,
"bottom": 24,
"left": 24
},
"axes": false,
"schema": {
"structure": "network",
"tables": {
"nodes": {
"id": {
"type": "categorical",
"key": true,
"open": true
},
"label": {
"type": "categorical",
"open": true
},
"x": {
"type": "quantitative",
"domain": [
0,
100
]
},
"y": {
"type": "quantitative",
"domain": [
0,
100
]
}
},
"links": {
"source": {
"type": "ref"
},
"target": {
"type": "ref"
}
}
}
},
"data": {
"nodes": [
{
"id": "n1",
"label": "Price",
"x": 20,
"y": 72
},
{
"id": "n2",
"label": "Onboarding",
"x": 22,
"y": 26
},
{
"id": "n3",
"label": "Churn",
"x": 78,
"y": 50
}
],
"links": [
{
"source": "n1",
"target": "n3"
}
]
},
"marks": [
{
"type": "link",
"inset": 3,
"stroke": "#94A5B3",
"strokeWidth": 1.5
},
{
"type": "node",
"size": 10,
"fill": "#50AEB7",
"edits": [
{
"type": "network.connect",
"when": "shift"
},
{
"type": "create",
"defaults": {
"label": "New idea"
}
},
{
"type": "remove",
"when": "alt"
}
],
"channels": {
"x": {
"field": "x",
"edit": {
"type": "move",
"channels": [
"x",
"y"
],
"when": "noShift"
}
},
"y": {
"field": "y"
},
"text": {
"field": "label",
"edit": {
"type": "editText"
}
}
}
}
]
}
```
### Write it into your app
In `build` mode the agent writes the card into your code and tests it with `check_spec` before it hands it over.
You: Add a question to our onboarding survey where people rank five features.
Agent: I've added it to the survey. Here's the code, and the card it draws:
```javascript
import { Elicit, compile } from "elicitjs";
const chart = Elicit(compile({
widget: {
type: "ranking",
question: "Rank these features by how much you would use them",
items: ["Offline mode", "Shared lists", "Reminders", "Dark theme", "Export"],
},
}));
document.querySelector("#feature-rank").append(chart.dom());
// The rows are the answer: save them with the rest of the survey.
chart.on("change", (rows) => survey.save("featureRank", rows));
```
```json
{
"widget": {
"type": "ranking",
"question": "Rank these features by how much you would use them",
"items": [
"Offline mode",
"Shared lists",
"Reminders",
"Dark theme",
"Export"
]
}
}
```
## What the server provides
- **Ask in a chat** (`ask_with_visual`, `read_chart`, `update_chart`): Shows a card in the conversation. The agent reads the chart as you leave it and can change it too; your edits and its edits show on the same card. Submit carries on the chat without typing. The card can go full screen or float.
- **Look it up** (`elicitjs_docs`): The skill, a keyword, a docs page or example, or a search, by one string.
- **Check and test** (`check_spec`): Builds a spec headlessly, lists what to fix, answers it as a person would, and renders it to PNG.
- **Export** (`export_html`): Writes a page with the card and the library, which opens from disk.
- **Prompts** (`author_elicit_chart`, `design_elicitation`): Slash commands in hosts that list prompts: ask with a card, or design a new way to ask.
`ELICITJS_MCP_MODE` picks the tools:
- `chat` asks a person in a chat host, such as Claude Desktop: `ask_with_visual`, `read_chart`, `update_chart` and `elicitjs_docs`.
- `build` is for an agent writing Elicit.js into an app: `elicitjs_docs`, `check_spec` and `export_html`.
Leave out `ELICITJS_MCP_MODE` for all six tools. Specs are JSON, the form `compile()` reads. The server is alpha.
## Install and configure
In Claude Code, add the server in `build` mode:
```bash
claude mcp add elicitjs-build -e ELICITJS_MCP_MODE=build -- npx -y elicitjs-mcp
```
In Claude Desktop, add it in `chat` mode to `claude_desktop_config.json`, then restart the app:
```json
{
"mcpServers": {
"elicitjs": {
"command": "npx",
"args": ["-y", "elicitjs-mcp"],
"env": { "ELICITJS_MCP_MODE": "chat" }
}
}
}
```
Other clients take the same command, `npx -y elicitjs-mcp`. For PNG rendering in `check_spec`, also run `npx playwright install chromium` once.
## The skill
The `elicit` skill is a short `SKILL.md` with reference files: how to write a spec, ask well, design a new technique, and build Elicit.js into an app. It ships inside the npm package, so an agent reads the version that matches the library you installed: `node_modules/elicitjs/skills/elicit/SKILL.md`.
To tell every agent that works in a project to read it, run this in the project's folder:
```bash
npx -y elicitjs-mcp setup
```
It adds a short block to the project's `AGENTS.md`, and to its `CLAUDE.md` when that file does not already read `AGENTS.md`. Running it again refreshes the block and leaves the rest of the file alone.
To add the skill to your agent's own skills folder instead:
```bash
npx skills add elicitjs/elicitjs --skill elicit
```
`skills add` copies the skill from the GitHub repository, so it follows the latest source rather than your installed version.
## The docs as Markdown
The site publishes three plain-text forms of these pages:
- [`/llms.txt`](https://elicitjs.github.io/llms.txt) lists every page with a one-line description, grouped as the sidebar groups them.
- [`/llms-full.txt`](https://elicitjs.github.io/llms-full.txt) holds every page in one file.
- Each page's route plus `.md` is that page alone: its prose, each example's title and code, and its API reference. This page is [`/start/agents.md`](https://elicitjs.github.io/start/agents.md).
The examples name keywords bare and call the docs' `mount(node)`. [Reading the examples](https://elicitjs.github.io/start.md#examples) shows how they map to your own code.
---
# Core concepts
> Source: https://elicitjs.github.io/concepts/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
The model behind every elicitation interface: a dataset, marks that encode it, and edits that write it back.
## Marks are views over one dataset
A chart draws one dataset. Each mark is a *view* over that dataset: it encodes some fields onto visual channels, and where a channel carries an `edit`, it writes them back. Two marks over the same rows stay in sync — an edit on one commits to the shared data, and the other re-renders from it. Several charts can share one dataset in the same way; see [Datasets & linked charts](https://elicitjs.github.io/dataset.md).
### Example: Two marks, one dataset
Bars and points share the dataset and schema. The point mark carries the drag edit and writes the 'n' field over the y channel, the bar mark updates when the data commits.
Try: **Drag** a point — both marks update from the same rows.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ cat: "A", n: 30 }, { cat: "B", n: 55 },
{ cat: "C", n: 22 }, { cat: "D", n: 44 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
marks: [
// Both marks read the same rows — neither owns data.
bar({
fill: "#EDF7F8",
channels: {
x: { field: "cat" },
y: { field: "n" },
},
}),
point({
fill: "#50AEB7", size: 7,
channels: {
x: { field: "cat" },
y: { field: "n", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## The schema owns type and domain
Elicitation often starts from an empty chart, so the data can't tell you what a field is or how wide its axis runs. The `schema` states this once: each field's **type** (`quantitative`, `categorical`, `ordinal`, or `temporal`) and its **domain**. A mark may name the scale a field encodes through; when it doesn't, the scale is inferred from the type. See [Data schema](https://elicitjs.github.io/schema.md) and [Scales & channels](https://elicitjs.github.io/scales.md).
### Example: Schema owns the domain
Nothing names a scale. Schema says cat is categorical and n is quantitative; the bar needs an interval for discrete data — band and linear fall out.
Try: **Drag** a bar — the edit inverts through the derived scale.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
// Type + domain live here — once. Marks never declare a domain.
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
data: [
{ cat: "A", n: 34 }, { cat: "B", n: 58 },
{ cat: "C", n: 22 }, { cat: "D", n: 47 },
],
marks: [
bar({
fill: "#50AEB7",
channels: {
x: { field: "cat" }, // categorical + bar → band
y: { field: "n", edit: move() }, // quantitative → linear
},
}),
],
});
mount(chart.dom());
```
## Channels
A mark encodes data onto channels — `x`, `y`, `fill`, `stroke`, `size`, and so on. Every mark exposes the same channel set, plus top-level style shorthands. A channel takes one of four serializable forms:
- `{ field: "n" }` — a field, mapped through its scale.
- `{ value: 25 }` — a visual-space constant; on `y` it is pixel 25, skipping the scale.
- `{ datum: 25 }` — a data-space constant, mapped through the scale; on `y` it lands where the value 25 sits.
- `{ field: "n", scale: null }` — a raw field, used as-is with no scale.
### Example: Field-driven colour (ordinal palette)
channels: { fill: { field: "kind" } } — a category drives fill through the ordinal palette.
```javascript
const chart = Elicit({
width: 340, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ cat: "A", n: 34, kind: "low" }, { cat: "B", n: 58, kind: "high" },
{ cat: "C", n: 22, kind: "low" }, { cat: "D", n: 47, kind: "high" },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
kind: { type: "categorical", domain: ["low", "high"] },
},
marks: [
bar({
channels: {
x: { field: "cat" },
y: { field: "n" },
fill: { field: "kind" },
},
}),
],
});
mount(chart.dom());
```
### Example: Constant style shorthands
stroke, strokeWidth, opacity as top-level shorthands on a point — a constant channel needs no scale.
```javascript
const chart = Elicit({
width: 340, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 12, y: 40 }, { x: 30, y: 22 }, { x: 48, y: 55 },
{ x: 66, y: 33 }, { x: 80, y: 68 }, { x: 22, y: 60 },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 80] },
},
marks: [
point({
fill: "#F2B94B", opacity: 0.85,
size: 9,
channels: {
x: { field: "x" },
y: { field: "y" },
},
}),
],
});
mount(chart.dom());
```
### Example: value vs datum
Solid teal rule: y: { datum: 40 } (data units, through the scale). Dashed gold: y: { value: 28 } (pixel 28, skips the scale).
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ cat: "A", n: 30 }, { cat: "B", n: 55 },
{ cat: "C", n: 22 }, { cat: "D", n: 44 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
marks: [
bar({
fill: "#EDF7F8",
channels: {
x: { field: "cat" },
y: { field: "n" },
},
}),
// datum: data units → through the scale (lands where n = 40 is)
ruleY({
stroke: "#50AEB7", strokeWidth: 2,
channels: { y: { datum: 40 } },
}),
// value: visual units → skips the scale (pixel 28 from the top of the plot)
ruleY({
stroke: "#F2B94B", strokeWidth: 2, strokeDash: "4 3",
channels: { y: { value: 28 } },
}),
],
});
mount(chart.dom());
```
## Derived channels
A fifth form computes the channel from a function, one datum at a time: `fill: { fn: d => d.x > 50 ? "red" : "blue" }` (the shorthand `fill: d => …` desugars to it). The function runs in **visual space** — its return value is used as-is (on `y`, a pixel), never through a scale.
A derived channel is **read-only**. It is opaque to the edit layer, so it can't carry an `edit`; put the edit on the source field instead (here `x`). Every mark re-derives from the committed rows on each render, so the colour recomputes live during the drag. On a line or area, a paint function (`fill`/`stroke`) runs once per **series**, against that series' first row.
### Example: Threshold fill (derived)
fill: { fn: d => d.x > 50 ? "#dc2626" : "#2563eb" } — the drag writes x; the colour re-derives on every render.
Try: **Drag** a point across the dashed line — its colour flips.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 16, right: 16, bottom: 32, left: 40 },
data: [{ x: 25, y: 50 }, { x: 75, y: 50 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
// Dashed threshold at x = 50 (data units, through the scale).
ruleX({
stroke: "#94A5B3", strokeWidth: 1.5, strokeDash: "4 3",
channels: { x: { datum: 50 } },
}),
point({
size: 10,
channels: {
x: { field: "x", edit: move() },
y: { field: "y" },
// Derived channel: computed per datum in VISUAL space (a colour, used
// as-is). Read-only — the drag lives on x; fill re-derives on commit.
fill: { fn: (d) => d.x > 50 ? "#EE7B5E" : "#50AEB7" },
},
}),
],
});
mount(chart.dom());
```
## Marks, elements, and guides
Three kinds of thing draw on an interface, and each **views** something different.
| Kind | Namespace | Spec key | One node per | Writes | | --- | --- | --- | --- | --- | | **mark** | `plot.*` | `marks` | a row | rows | | **element** | `elements.*` | `elements` | a tick or swatch | the schema's domain | | **guide** | `guides.*` | `guides` | a derived statement | nothing |
A mark draws the data. An element — `axisX`, `gridY`, `legendColor` — draws a scale, so it takes a singular `channel` rather than a `channels` map, and an edit on it reshapes that field's domain. A guide draws the rule and the state: a target line, the range you should stay inside, how much of a budget is left.
A guide is **read-only**. Every guide option takes a literal or a function of the chart context, so `guides.rule({ y: ({ data }) => d3.mean(data, d => d.y) })` follows the rows — but a guide has no `table`, no channels and no `edit`. A guide differs from a [derived channel](#derived): a derived channel is per-row and its mark can still be edited, while a guide's expressions run once per render and never write.
`guides.remaining({ field: "y" })` reads its target from a `maintainSum` constraint when you don't pass one, so the total you enforce and the total you show stay the same number.
## Edits
An edit is the inverse of an encoding. Encoding maps data → visual; an edit maps a gesture → data, back through the same scale. Put it on a channel (`y: { field, edit: move() }`) to write one field, or at mark level (`edits: [...]`) for a gesture that writes several at once. Full catalogue on [Editing](https://elicitjs.github.io/editing.md).
### Example: Mark-level drag (x and y together)
edits: [move({ channels: ["x", "y"] })] — one gesture writes both fields.
Try: **Drag** a point in two dimensions.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: 20, y: 30 }, { x: 50, y: 62 }, { x: 78, y: 40 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#50AEB7", opacity: 0.85,
size: 9,
channels: {
x: { field: "x" },
y: { field: "y" },
},
// Joint gesture: one drag writes both channels.
edits: [ move({ channels: ["x", "y"] }) ],
}),
],
});
mount(chart.dom());
```
## Constraints
A constraint is a pure rule over **the dataset**. It holds no matter which edit fired it or which mark it was aimed at, which is why it is declared once on the spec rather than inside a mark. A constraint can reject a proposed edit or repair it by returning corrected rows. Catalogue on [Constraints](https://elicitjs.github.io/constraints.md).
### Example: Clamped drag
clamp keeps n in [10, 50]. guide: true draws the live bound while you drag.
Try: **Drag** a bar — it stops at 10 and 50.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ cat: "A", n: 30 }, { cat: "B", n: 55 },
{ cat: "C", n: 22 }, { cat: "D", n: 44 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
// Dataset invariant — holds for every edit from every mark.
constraints: [ clamp({ field: "n", min: 10, max: 50 }) ],
marks: [
bar({
fill: "#50AEB7",
channels: {
x: { field: "cat" },
y: { field: "n", edit: move({ guide: true }) },
},
}),
],
});
mount(chart.dom());
```
## Where next
- **[Marks](https://elicitjs.github.io/marks/bar.md)** — every mark factory, from bars and points to glyphs and geo.
- **[Editing](https://elicitjs.github.io/editing.md)** — drag, create/remove, pick modes, stages, history; drive named edits from outside the chart with [`control()`](https://elicitjs.github.io/editing/external-controls.md).
- **[Scales & data](https://elicitjs.github.io/scales.md)** — derived scales, schema, and constraints in depth.
- **[Widgets](https://elicitjs.github.io/widgets.md)** — survey instruments built on the same API.
- **[Authoring SDK](https://elicitjs.github.io/authoring.md)** — custom marks, edits, and drivers when the built-ins aren’t enough.
---
# Data schema
> Source: https://elicitjs.github.io/schema/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A `schema` declares the output dataset: each field's **type**, **domain**, and creation default. It is the source of truth for a field's scale, so an elicitation interface resolves scales, draws axes, and mints data with **zero starter data**. `structure` says which tables that dataset has: one by default, a network of nodes and links, or a hierarchy.
## API reference
### `schema — Record`
Required on `Elicit` — marks never own domains. Each field maps to a spec that fixes its measurement type, range and creation default — the source of truth a scale and a minted datum both read.
```ts
schema: { [field]: { type, domain?, default?, open?, key? } }
schema: { structure, tables: { [name]: { role?, fields } } }
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `type` | `'quantitative'\|'categorical'\|'ordinal'\|'temporal'\|'ref'` | | The field’s measurement type — picks the scale family (quantitative→linear, categorical→band/ordinal, temporal→time). `ref` means the value names a row of another table by its key; it scales as a category, and its domain comes from the column it points at. |
| `domain` | `any[]` | | The field’s data range or category list; feeds the resolved scale and the axis. |
| `open` | `boolean` | `false` | Is the domain a ceiling or a starting set? Closed (the default) means the declared categories are the whole vocabulary: `edit.stack.cut()` hands out the unused ones and refuses once they run out, and a seed value outside the domain is reported. `open: true` lets a cut append a new category and skips that check. A field with no `domain` is open either way — its domain is inferred from the data. |
| `key` | `boolean` | `false` | This field is the table’s identity — the column a `ref` points at, and the one `create` writes a fresh value into when it mints a row. One per table. Pair it with `open: true` so a gesture can mint an identity without asking you to type; a closed `domain` caps how many rows may exist. |
| `to` | `string` | `the nodes table’s key` | On a `ref` field, which column it points at: `"id"` for a column of the nodes table, `"links.id"` for another table’s. You rarely need it. |
| `structure` | `'table' \| 'network' \| 'hierarchy'` | `'table'` | Which tables the dataset has. `"table"` is one, and its schema is the bare field map above. `"network"` is two, under `tables` — see [Network](https://elicitjs.github.io/marks/network.md). `"hierarchy"` is a nodes table and a nesting table, with an optional links table — see [Hierarchy](https://elicitjs.github.io/marks/hierarchy.md). |
| `tables` | `Record` | | Under a multi-table `structure`, the tables by **name** — and the name is the key you seed `data` with and read `getData()` back by. A table whose value is a bare field map takes its role from its own name. |
| `role` | `string` | `the table's name` | Which role in the structure this table fills (`nodes`, `links`, `nesting`). Separate from the name, so an argument map can call its tables `claims` and `supports` and marks still find them. |
| `default` | `any` | `null` | The value a newly-created datum gets for this field (`null` = present but unset, editable later). |
Returns / emits: With a schema, a mark resolves scales and draws axes from **no starter data**; `create` seeds every declared field before the pointer places the positional ones.
## An empty chart that knows its axes
With no data, the axes come from the schema. Every created point carries all declared fields, from the pointer or the field's default, so it is editable at once.
### Example: Elicit from nothing
schema declares age / belief / class; create mints fully-formed data.
Try: **Double-click** to create · **drag** to move · **click** to cycle the class colour.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 16, right: 16, bottom: 30, left: 36 },
schema: {
age: { type: "quantitative", domain: [0, 100] },
belief: { type: "quantitative", domain: [0, 1], default: 0.5 },
class: { type: "categorical", domain: ["A", "B", "C"] },
},
axes: { x: { title: "age" }, y: { title: "belief" } },
data: [], // start from nothing
onChange: (d) => console.log("elicited", d),
marks: [
point({
size: 7,
channels: {
x: { field: "age" }, y: { field: "belief" },
fill: { field: "class" },
},
edits: [
create({ gesture: "dblclick" }),
move({ channels: ["x", "y"] }),
cycle({ channel: "fill", gesture: "click" }),
],
}),
],
});
mount(chart.dom());
```
## How many tables
`structure` says which tables the dataset has. Leave it out and you get one, whose columns are the schema itself:
```js
schema: {
age: { type: "quantitative", domain: [18, 80] },
belief: { type: "quantitative", domain: [0, 1] },
}
```
`structure: "network"` gives two tables under `tables`, filling the roles `nodes` and `links`. Each has its own columns, so a node and a link both carry their own attributes.
```js
schema: {
structure: "network",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
links: {
source: { type: "ref" },
target: { type: "ref" },
},
},
}
```
`data` is keyed by table name, and so are `getData()`, `onChange` and `setData`. Omit a table and it starts empty.
Give a table a `role` to name it for your data — `claims` and `supports` rather than `nodes` and `links`. Marks and edits find their table by role, so nothing else in the spec changes. See [Network](https://elicitjs.github.io/marks/network.md) for the marks and gestures that draw one.
The links table also takes `directed`, which says whether `source` → `target` is ordered:
```js
links: {
role: "links",
directed: true,
fields: { source: { type: "ref" }, target: { type: "ref" } },
}
```
`true` draws arrowheads and separates reciprocal links; `false` treats the pair as unordered, so `connect` refuses `b → a` once `a → b` exists. Leave it out and neither applies. See [Kinds of network](https://elicitjs.github.io/marks/network.md#directed).
`multi: true` lets a pair hold more than one link, and `selfLoops: true` lets a link join a node to itself. Both are off by default. See [Parallel links and loops](https://elicitjs.github.io/marks/network.md#multi).
`structure: "hierarchy"` gives a `nodes` table and a `nesting` table, whose rows say which node sits inside which. A `links` table is optional. See [Hierarchy](https://elicitjs.github.io/marks/hierarchy.md).
## Keys and references
Two field declarations join one table to another. `key: true` marks the column that identifies a row. `type: "ref"` marks a column that names one.
A `ref` reads its `domain` from the key column, so you list identities once. A value that names no row is reported when you seed it, and dropped when it becomes dangling: delete a node and its links go with it.
Pair `key` with `open: true` so a creating edit can mint a fresh identity automatically. Naming is a separate act: put `editText()` on a `text` mark and write the label in place.
A closed `domain` on a key is a fixed roster. `create` hands out the declared values one at a time and stops when they run out, which caps the number of rows.
None of this needs a network. A single table can declare a `key` too, and every row you create gets an identity:
### Example: A keyed table
One table, a `key` column, and `create`. New rows arrive already identified.
Try: **Click** empty space to add a row and watch its `id`. **Drag** a dot to move it, **Alt-click** to remove it.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 20, right: 16, bottom: 34, left: 44 },
data: [
{ id: "r1", effort: 30, value: 70 },
{ id: "r2", effort: 65, value: 40 },
],
schema: {
id: { type: "categorical", key: true, open: true },
effort: { type: "quantitative", domain: [0, 100] },
value: { type: "quantitative", domain: [0, 100] },
},
marks: [
node({
size: 9,
fill: "#50AEB7",
edits: [create(), remove({ when: when.alt })],
channels: {
x: { field: "effort", edit: move({ channels: ["effort", "value"] }) },
y: { field: "value" },
text: { field: "id" },
},
}),
],
});
mount(chart.dom());
```
## Which table a mark draws
Every mark draws exactly one table, named by its `table` option. A single-table interface needs no `table`.
With no `table`, a mark draws the **primary** table: the only one on a `structure: "table"` interface, and the nodes on a network or hierarchy. `link()` draws the links instead.
Use `table` when you want an ordinary mark over another table:
```js
barY({ table: "links", channels: { x: { field: "source" }, y: { field: "strength" } } })
```
An edit on that mark writes rows of that table, and `getData()` shows the change there. A name the schema does not declare is reported, and the mark falls back to the primary table.
Positional scales are shared across the interface. Two tables that encode different kinds of field on the same axis disagree about its type, and this is reported. Give the second mark its own chart instead.
### Example: A bar of link weights
An ordinary barY over the links table. Same channels, same edits — only `table` differs.
Try: **Drag** a bar. The change lands in the `links` table.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 20, right: 16, bottom: 34, left: 44 },
schema: {
structure: "network",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
links: {
source: { type: "ref" },
target: { type: "ref" },
strength: { type: "quantitative", domain: [0, 1] },
},
},
},
data: {
nodes: [
{ id: "a", x: 20, y: 70 },
{ id: "b", x: 70, y: 82 },
{ id: "c", x: 78, y: 26 },
],
links: [
{ source: "a", target: "b", strength: 0.9 },
{ source: "b", target: "c", strength: 0.3 },
{ source: "c", target: "a", strength: 0.6 },
],
},
marks: [
barY({
table: "links",
fill: "#50AEB7",
channels: {
x: { field: "source" },
y: { field: "strength", edit: move({ channels: ["y"] }) },
},
}),
],
});
mount(chart.dom());
```
## A temporal axis
`type: "temporal"` on a field. Dates place, drag, and invert like any continuous axis. A temporal column holds `Date`s: an ISO string or epoch number in `data` or `setData()` is stored as a `Date`, so `getData()` returns `Date`s.
### Example: Beliefs over time
A temporal domain drives a time scale; created points carry real Dates.
Try: **Double-click** to record a belief at a point in time · **drag** to adjust.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 16, right: 16, bottom: 30, left: 36 },
schema: {
when: { type: "temporal", domain: ["2020-01-01", "2026-01-01"] },
belief: { type: "quantitative", domain: [0, 1], default: 0.5 },
},
axes: { x: { title: "when" }, y: { title: "belief" } },
data: [],
marks: [
point({
size: 7, fill: "#1B3F60",
channels: {
x: { field: "when" }, y: { field: "belief" },
},
edits: [
create({ gesture: "dblclick" }),
move({ channels: ["x", "y"] }),
],
}),
],
});
mount(chart.dom());
```
---
# Scales & channels
> Source: https://elicitjs.github.io/scales/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A **data type** says what a field *is*: `quantitative`, `categorical`, `ordinal` or `temporal`. You declare it once, on the [schema](https://elicitjs.github.io/schema.md). A **scale type** says how a channel *draws* it: `linear`, `log`, `band`, `ordinal`, and so on. The scale type is normally **derived**. A categorical field on a bar’s x is a band, because a bar needs an interval; on a dot’s x it is a point, because a dot sits on a tick. When you do name a scale, `scale` takes a name, a spec, or a live d3 scale. Every positional scale is invertible, which is what makes editing possible.
## API reference
### `Channel spec`
Each entry in a mark’s `channels` is one channel: a field, a constant, or a raw field — plus an optional co-located `edit`. No `domain` here; a domain belongs to the data, not to a mark’s view of it.
JSON keyword: `channel`
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `field` | `string` | | The data field to read and map through the channel’s scale. |
| `value` | `any` | | A **visual-space** constant — it skips the scale. `fill: "red"` desugars to this. |
| `datum` | `any` | | A **data-space** constant — it goes *through* the scale. `y: { datum: 25 }` lands where y = 25 is, not at pixel 25. |
| `fn` | `(d, i, data) => any` | | A **derived** channel, computed per datum in visual space — the result is used as-is, never scaled. `fill: d => …` is the shorthand. It is **read-only**: a derived channel cannot carry an `edit`, because it is opaque to the edit layer. Put the edit on the source field’s channel; the function re-derives from the committed rows on every render. |
| `type` | `MeasureType` | `from schema` | The field’s **data** type. An override for a field the schema doesn’t cover — normally you declare it once on the schema instead. |
| `scale` | `string \| ScaleSpec \| d3 scale \| null` | `derived` | How to draw it. `null` passes the field through unscaled (a literal colour / pixel). See **Scale forms**. |
| `frame` | `number \| [lo, hi] \| boolean` | | Position this channel **locally**, inside the enclosing [composite](https://elicitjs.github.io/marks/composite.md)’s box, and switch that composite into box mode. Shorthand for a `frame` scale. |
| `legend` | `boolean \| object \| null` | | Draw a key for this encoding. Non-positional channels only — an axis is the key for x and y. See [Legend](https://elicitjs.github.io/marks/legend.md). |
| `edit` | `Edit` | | Co-locate an edit so a gesture writes this channel back through the same scale. |
Returns / emits: The engine resolves **one global scale per channel**, unioning across marks and across `x/x1/x2` and `y/y1/y2` — including their **schema domains**, so an error bar’s `mean`, `lo` and `hi` share one y axis spanning all three. Scales reach `build` as `scales.x`, `scales.y`, ….
### `Scale forms`
The three ways to name a scale, when the derived one isn’t what you want. A d3 scale is adopted as you built it; for a positional channel we hand it the plot’s pixel range (pixels are ours to know, palettes and radii are yours).
```ts
scale: "log" // by name
scale: { type: "sqrt", range: [4, 20] } // by spec
scale: d3.scaleBand().padding(0.3) // a live d3 scale
scale: null // unscaled passthrough
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `ScaleSpec.type` | `ScaleType` | `derived` | `linear`, `log`, `symlog`, `pow`, `sqrt`, `time`, `band`, `point`, `ordinal`, `sequential`, `diverging`. |
| `ScaleSpec.constant` | `number` | `1` | For `symlog` — how wide the linear region around zero is. `symlog` is `log` for a domain that **crosses zero** or goes negative, where plain `log` has no answer. It stays continuous and invertible, so it drags. |
| `ScaleSpec.pivot` | `number` | `0, or the domain midpoint` | For `diverging` — the data value that takes the middle colour, with each side scaled independently so the pivot keeps its colour even on a lopsided domain like `[-2, 10]`. Defaults to 0 when the domain straddles it. Like `sequential`, it is a colour scale: not invertible, so it can’t carry an edit. |
| `ScaleSpec.range` | `any[]` | `from geometry` | The output extent — pixels, radii, colours. Positional ranges default to the plot size. |
| `ScaleSpec.scheme` | `string` | | A named colour palette (`"RdBu"`, `"Tableau10"`, …), used when no explicit `range` is given. An explicit range still wins. |
| `ScaleSpec.reverse` | `boolean` | `false` | Flip the range end for end — a scheme read the other way, or an axis that counts down. |
| `ScaleSpec.padding` | `number` | `0.1 / 0.5` | Band / point padding. |
| `ScaleSpec.nice / clamp` | `boolean` | `false` | Continuous-scale refinements. |
| `ScaleSpec.base / exponent` | `number` | `10 / 1` | For `log` and `pow`. |
| `spec.scales` | `Record` | | The chart-level override, keyed by channel. Scales are global, so this is their honest home; it wins over a channel’s own `scale`. |
Returns / emits: A scale carries what it can **do** — `kind` (`band` | `point` | `continuous` | `discrete`) and `invertible` — sniffed from the scale object itself. Marks and edits branch on that, never on a type name, which is why an adopted d3 scale drags exactly like a built-in one. On a map, `lon` and `lat` are `paired`: the projection places them together, so `chart.scale('lon')` encodes a longitude with its latitude and inverts a whole point.
## The scale is derived from the data type
Nothing below names a scale. The schema says `cat` is categorical and `n` is quantitative; the bar says it needs an interval for discrete data. Band and linear fall out. Swap `bar` for `point` and x becomes a point scale, with no other change.
### Example: No scale named anywhere
Data type (schema) + what the mark needs = the scale. Drag a bar to see it invert.
Try: **Drag** a bar.
```javascript
const chart = Elicit({
width: 340, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
data: [
{ cat: "A", n: 34 }, { cat: "B", n: 58 },
{ cat: "C", n: 22 }, { cat: "D", n: 47 },
],
marks: [
bar({
fill: "#50AEB7",
channels: {
x: { field: "cat" }, // categorical + bar -> band
y: { field: "n", edit: move() }, // quantitative -> linear
},
}),
],
});
mount(chart.dom());
```
## Continuous → colour & size
The same numeric field through a colour channel becomes a ramp, and through the size channel a radius. A size channel’s output `range` (radii, in px) is a property of the scale, so it rides on `scale`.
### Example: Sequential ramp + size
fill: { field } → ramp, size: { field } → radius, from one numeric field.
```javascript
const chart = Elicit({
width: 340, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 34 },
schema: {
h: { type: "quantitative", domain: [140, 200] },
weight: { type: "quantitative", domain: [40, 100] },
},
data: [
{ h: 150, weight: 48 }, { h: 160, weight: 57 }, { h: 170, weight: 66 },
{ h: 180, weight: 78 }, { h: 190, weight: 92 }, { h: 165, weight: 61 },
],
marks: [
point({
channels: {
x: { field: "h" },
y: { field: "weight" },
fill: { field: "weight" }, // -> sequential ramp
size: { field: "weight", scale: { range: [4, 16] } }, // -> radius, in px
},
}),
],
});
mount(chart.dom());
```
## Crossing zero — symlog & diverging
Elicited quantities are often *differences*: a revision, an error, a surprise. They can span orders of magnitude in both directions. `log` is undefined at 0 and below, and a `sequential` ramp has no reference point. `symlog` is linear near zero and logarithmic beyond it. `diverging` colours by distance from a pivot, scaling each side on its own.
### Example: symlog position, diverging colour
A domain that crosses zero — where log has no answer and a sequential ramp has no reference.
Try: **Drag** a dot across zero: the position stays readable at ±3 and at ±400 alike, and the colour turns as it passes the pivot.
```javascript
const chart = Elicit({
width: 440, height: 220,
margins: { top: 16, right: 24, bottom: 34, left: 88 },
schema: {
metric: { type: "categorical", domain: ["Signups", "Revenue", "Churn", "Support load"] },
delta: { type: "quantitative", domain: [-100, 1000] },
},
data: [
{ metric: "Signups", delta: 400 },
{ metric: "Revenue", delta: 25 },
{ metric: "Churn", delta: -60 },
{ metric: "Support load", delta: 3 },
],
marks: [
point({
size: 9,
channels: {
y: { field: "metric" },
// symlog: the deltas span orders of magnitude AND cross zero, where
// plain `log` has no answer. `constant` sets how wide the linear
// region around zero is. Still continuous and invertible — it drags.
x: { field: "delta",
scale: { type: "symlog", constant: 10 },
edit: move() },
// diverging: colour by distance from a PIVOT. Each side is scaled on
// its own, so 0 keeps the neutral colour even though the domain is
// lopsided (-100 vs 1000).
fill: { field: "delta",
scale: { type: "diverging", pivot: 0,
range: ["#EE7B5E", "#EAF0F4", "#50AEB7"] } },
},
}),
// The zero line, through the symlog scale (`datum`, not `value` — `value`
// would put it 0 pixels from the left edge).
ruleX({ channels: { x: { datum: 0 } }, stroke: "#94A5B3", strokeDash: "3 3" }),
],
});
mount(chart.dom());
```
## Naming a scale: by name, by spec, by d3
`scale` takes three forms: a name (log x), a spec (a sqrt size range), or a d3 scale (a band with custom padding). A d3 scale is used as built. A positional d3 scale with no range gets the plot’s pixel range. It keeps its padding and stays invertible, so the drag works.
### Example: log · sqrt · an adopted d3 scale
x is logarithmic, size ramps by sqrt, and the categorical fill uses a d3 ordinal scale.
Try: **Drag** a dot vertically — an adopted scale inverts like any other.
```javascript
const chart = Elicit({
width: 380, height: 250,
margins: { top: 14, right: 14, bottom: 30, left: 40 },
schema: {
t: { type: "quantitative", domain: [1, 1000] },
w: { type: "quantitative", domain: [0, 100] },
g: { type: "categorical", domain: ["a", "b", "c"] },
},
data: [
{ t: 2, w: 20, g: "a" }, { t: 20, w: 55, g: "b" },
{ t: 120, w: 40, g: "c" }, { t: 700, w: 80, g: "a" },
],
marks: [
point({
channels: {
x: { field: "t", scale: "log" },
y: { field: "w", edit: move() },
size: { field: "w", scale: { type: "sqrt", range: [5, 16] } },
fill: { field: "g", scale: d3.scaleOrdinal(["#50AEB7", "#2B5D87", "#EE7B5E", "#F2B94B"]) },
},
}),
],
});
mount(chart.dom());
```
## Categorical → ordinal palette
A categorical field on a colour channel resolves through the ordinal palette — one hue per category.
### Example: Ordinal palette
fill: { field: "kind" } assigns palette colours across the category domain.
```javascript
const chart = Elicit({
width: 340, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
kind: { type: "categorical", domain: ["low", "high"] },
},
data: [
{ cat: "A", n: 34, kind: "low" }, { cat: "B", n: 58, kind: "high" },
{ cat: "C", n: 22, kind: "low" }, { cat: "D", n: 47, kind: "high" },
],
marks: [
bar({
channels: {
x: { field: "cat" },
y: { field: "n" },
fill: { field: "kind" },
},
}),
],
});
mount(chart.dom());
```
## Ordered data gets an ordered ramp
Colour follows the field's data type as well as its scale. `categorical` values are unordered, so they get distinct hues. `ordinal` values run low to high, so they get a **ramp sampled to one swatch per category**, light to dark, in order. A Likert scale then reads as a scale rather than as four unrelated colours.
Declare the difference and the colour follows:
```js
agree: { type: "ordinal", domain: ["disagree", "neutral", "agree", "strongly agree"] }
team: { type: "categorical", domain: ["north", "south", "east"] }
```
### Example: Ordinal above, categorical below
One ramp for the ordered field, distinct hues for the unordered one.
```javascript
const rows = [
{ q: "Q1", agree: "disagree", team: "north" },
{ q: "Q2", agree: "neutral", team: "south" },
{ q: "Q3", agree: "agree", team: "north" },
{ q: "Q4", agree: "strongly agree", team: "east" },
];
const chart = Elicit({
width: 420, height: 210,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
schema: {
q: { type: "categorical", domain: ["Q1", "Q2", "Q3", "Q4"] },
// ORDERED: the values run low -> high, so colour should too.
agree: { type: "ordinal", domain: ["disagree", "neutral", "agree", "strongly agree"] },
// UNORDERED: three labels with no sequence.
team: { type: "categorical", domain: ["north", "south", "east"] },
},
data: rows,
legends: true,
marks: [
point({ size: 13, channels: {
x: { field: "q" },
y: { value: 60 },
fill: { field: "agree" },
} }),
point({ size: 13, channels: {
x: { field: "q" },
y: { value: 110 },
fill: { field: "team" },
} }),
],
});
mount(chart.dom());
```
Use `categorical` for a group identifier, even when you list its values in an order. A series key is unordered.
## Two encodings on one channel
A scale belongs to one **encoding**: a (channel, field) pair. Two marks colouring by *different* fields get two scales, each with its own domain and legend. They also get different scheme **families**, so the two stay perceptually distinct.
Two marks colouring by the *same* field share one scale, one set of colours, and one legend, so a shared colour means a shared value.
## Categorical position → point scale
When a positional channel is categorical, a dot resolves it to a point scale and sits on the category’s tick. Two categorical axes make a discrete grid. Here `y` is `ordinal`, so its domain’s *order* is meaningful.
### Example: A discrete grid
Both positions are categories, so each dot lands on an (x, y) cell.
```javascript
const chart = Elicit({
width: 360, height: 300,
schema: {
x: { type: "categorical", domain: ["A", "B", "C"] },
y: { type: "ordinal", domain: ["Low", "Mid", "High"] },
group: { type: "categorical", domain: ["alpha", "beta", "gamma"] },
},
data: [
{ x: "A", y: "Low", group: "alpha" },
{ x: "B", y: "Mid", group: "beta" },
{ x: "C", y: "High", group: "gamma" },
],
marks: [
point({
size: 12,
channels: {
x: { field: "x" },
y: { field: "y" },
fill: { field: "group" },
},
}),
],
});
mount(chart.dom());
```
---
# Constraints
> Source: https://elicitjs.github.io/constraints/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A constraint is a rule over the dataset, so it applies to every edit on every mark. It can reject a proposed change, or repair it by returning corrected rows. Every mark reads the same rows, so a repair shows up everywhere on the next render. Declare constraints in `constraints: [...]` on the `Elicit` spec, or on `Elicit.dataset` for [several charts](https://elicitjs.github.io/dataset.md). `clamp` and `snap` bound a field, `maintainSum` fixes a total, `count` caps the number of rows, and `unique` forbids duplicate keys. `ordering` keeps a row's fields in order (lo ≤ mean ≤ hi), `monotonic` keeps a cumulative curve from dipping, `spacing` keeps neighbours apart, `follow` and `symmetric` couple a range to its centre, and `contain` governs membership in a [hierarchy](https://elicitjs.github.io/marks/hierarchy.md). `constraints.custom` defines your own.
## API reference
### `Built-in constraints`
Import `constraints` from `elicitjs` and pass on the `Elicit` spec’s `constraints: [...]`. That is the only place they go: a constraint gates every edit from every mark, so writing one inside a mark would say something the engine does not mean. All are pure data invariants — they run on every commit and never see pixels.
JSON keyword: `constraints.clamp`, `constraints.maintainSum`, `constraints.count`, `constraints.unique`, `constraints.snap`, `constraints.ordering`, `constraints.monotonic`, `constraints.spacing`, `constraints.follow`, `constraints.symmetric`, `constraints.contain`
```ts
clamp({ min, max, field, table }) → Constraint
maintainSum({ total, field, strategy, table }) → Constraint
count({ max, strategy, table }) → Constraint
unique({ field, max, strategy, table }) → Constraint
snap({ field, step, origin, table }) → Constraint
ordering({ field, strategy, table }) → Constraint
monotonic({ field, along, direction, series, table }) → Constraint
spacing({ field, min, series, table }) → Constraint
follow({ field, lead, table }) → Constraint
symmetric({ field, about, table }) → Constraint
contain({ parent, child, maxDepth, maxChildren, table }) → Constraint
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `table` | `string` | `the primary table` | Every constraint takes it: the table the rule is about, by name or by role. `contain` defaults to the `nesting` role. A name that matches no table warns, and the rule runs on the primary table. |
| `clamp.min / max` | `number` | `field domain` | Bounds every cell the edit changed to [min, max]. An omitted bound falls back to the field’s declared domain. |
| `clamp.field` | `string \| string[]` | `the edited column` | The column(s) to bound. Every cell the proposal changed in them is clamped, including a neighbour another constraint pushed. |
| `maintainSum.total` | `number` | | Target total for the field. |
| `maintainSum.field` | `string` | `the edited column` | The column whose rows must sum to the total. |
| `maintainSum.strategy` | `'cap' \| 'normalize' \| 'redistribute'` | `'cap'` | `cap` bounds the touched datum (≤ sum); `normalize` scales all values to exact sum; `redistribute` holds the edited value and proportionally adjusts siblings. |
| `count.max` | `number` | `required` | Maximum number of data rows. Context rows are not counted. The rule judges an edit that adds rows. Without `max` it does nothing and warns. |
| `count.strategy` | `'replace' \| 'reject'` | `'replace'` | Over the limit: drop the oldest rows (keep the newest max, and every context row) or refuse the interaction. |
| `unique.field` | `string \| string[]` | `the edited column` | Category key(s); an array makes a composite (per-cell) key. |
| `unique.max / strategy` | `number / string` | `1 / 'reject'` | How many may share a key, and whether to reject or replace the resident. |
| `snap.step / origin` | `number` | `1 / 0` | Quantize the field to a grid (slider steps, waffle cells): the spacing, and the value the grid is anchored at. |
| `snap.field` | `string \| string[]` | `the edited column` | The column(s) to quantize. Every cell the proposal changed in them is snapped, so both rows of a stack edge stay on the grid. A temporal cell stays a Date, snapped in milliseconds. |
| `ordering.field` | `string[]` | | Columns of one row that must stay in this order, as one ordered list — `["lo", "mean", "hi"]` means lo ≤ mean ≤ hi. At least two are needed. |
| `ordering.strategy` | `'push' \| 'reject'` | `'push'` | `push` repairs — the field you dragged wins and its neighbours give way, so the interval *moves*. `reject` refuses the edit instead, for an elicitation where the bounds are given and only the estimate inside them moves. |
| `monotonic.field / along` | `string` | `the edited column / 'x'` | The value that may never reverse, and the axis it runs along. Where `ordering` keeps **fields** of one row in order, this keeps **rows** in order along an axis. Rows are sorted by `along`, not by array position, so an appended anchor lands in the right place. |
| `monotonic.direction` | `'up' \| 'down'` | `'up'` | `up` = non-decreasing (a CDF, a budget burning up); `down` = non-increasing (a survival curve). |
| `spacing.field / min` | `string / number` | `the edited column / 1` | Adjacent values of `field` stay at least `min` apart, in **data** units — never pixels. Implies an order too (pushing apart preserves the sort), so a field with `spacing` needs no `ordering`. |
| `follow.field / lead` | `string[] / string` | | When `lead` moves, each column in `field` moves by the same amount. A column the edit set itself is left alone, so dragging an end moves only that end. Both are required. |
| `symmetric.field / about` | `[string, string] / string` | | When one column of the pair moves, the other is set to its mirror image about `about`. Declare after `follow` and before `ordering` and `clamp`. |
| `monotonic.series / spacing.series` | `string \| null` | `null` | Group rows by this field first, so each line of a multi-series chart is judged on its own. |
| `contain.parent / child` | `(d, i, rows) => boolean` | | Predicates over the `nodes` table of a [hierarchy](https://elicitjs.github.io/marks/hierarchy.md): which rows may hold others, and which may sit inside a container. |
| `contain.maxDepth / maxChildren` | `number` | `∞` | Limits on nesting depth (root = 0) and on direct children per container. Targets the `nesting` table automatically. Rows in `data` or `setData()` that break the rule are kept, and one warning names them. An edit is refused only for a break it adds. |
Returns / emits: Each returns a **Constraint** — a reducer the engine runs on the proposed dataset after every edit.
### `constraints.custom(apply, meta?)`
Author your own. One word for “author your own X” in every grammar namespace — cf. `edit.custom` and `guides.custom`. Every constraint is a descriptor — `{ type, field?, options, apply }` — and `field` left out means the column the dispatching edit writes, so a one-column instrument names nothing twice. The rule gets a pure-data context and returns the shape that’s natural.
JSON keyword: `constraints.custom`
```ts
constraints.custom(({ data, oldData, activeIndex, active, field, fields, value, domain, table, tables }) => result, meta?) → Constraint
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `return number` | | | The constrained value for the active datum’s `field`. |
| `return object` | | | Fields merged into the active datum. |
| `return array` | | | A full replacement dataset (cross-datum rules: sum, unique, count). |
| `return false` | | | Reject the whole interaction. |
| `return true / undefined` | | | Accept unchanged. |
| `meta.field` | `string \| string[]` | `the edited column` | The column the rule is about, or an ordered list of them. Left out, the rule reads the column the edit writes. |
| `meta.table` | `string` | `the primary table` | The table the rule is about, by role or name. |
| `meta.type` | `string` | `'custom'` | The rule’s name, as its descriptor reports it. |
| `meta.options` | `object` | `{}` | The rule’s own settings, kept on the descriptor so a `guide` can read them. |
| `meta.guide` | `function` | | Optional drawer so an edit with `guide:true` can show this constraint’s bounds. |
Returns / emits: A **Constraint**. The `ctx.active` is the datum the gesture touched; `domain` is that field’s declared data range.
## maintainSum — a total held at 100
`maintainSum` holds the total for every edit on every mark. Drag one bar and the others give way to keep the total at 100. `guide: true` draws the live bound.
### Example: Bars that compensate
maintainSum bounds the touched bar so the total stays 100; a rule guide marks the even split.
Try: **Drag** any bar — the others compensate.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
guides: [ guides.rule({ y: 25, label: "even split (25)" }) ],
data: ["A", "B", "C", "D"].map((c) => ({ x: c, y: 25 })),
// Invariants on the DATA — they gate every edit, from every mark.
constraints: [
clamp({ field: "y", min: 0 }),
maintainSum({ field: "y", total: 100 }),
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
bar({
fill: "#50AEB7",
channels: {
x: { field: "x" },
y: { field: "y", edit: move({ guide: true }) },
},
}),
],
});
mount(chart.dom());
```
## clamp — bound a field
`clamp` holds a field inside `[min, max]`. It bounds the field you name, or the column the edit writes when you name none. An omitted bound falls back to the field's declared domain. `field` also takes a list, so one `clamp` can bound every column of a glyph. Pair it with a nearest pick and `guide: true` to show the bounds while you drag.
`clamp` and `snap` repair every cell the proposal changed. A neighbour that `ordering` or `monotonic` pushed is bounded too. Both rows of a stack edge land on the grid together, so the stack keeps its total. `snap` keeps a temporal field a `Date`, and its `step` is in milliseconds.
### Example: Clamped drag with a guide
The y edit is clamped to 0–90; guide: true draws the bounds and the snap ring.
Try: **Drag** from anywhere in a column (clamped to 0–90).
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
constraints: [ clamp({ field: "y", min: 0, max: 90 }) ],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
bar({
fill: "#50AEB7",
channels: {
x: { field: "x" },
y: { field: "y",
edit: move({ pick: "nearest", threshold: 40, guide: true }) },
},
}),
],
});
mount(chart.dom());
```
## unique — one per key
`unique` forbids two rows with the same key. A single field guards one axis. An array is a composite key: at most one mark per cell, for both create and move.
### Example: One bar per category
create mints wherever you click, but unique({ field: "x" }) rejects a filled slot.
Try: **Click** an empty column to fill it · a filled column rejects.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: "A", y: 40 }, { x: "C", y: 60 }],
constraints: [ unique({ field: "x", max: 1 }) ],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
bar({
fill: "#1B3F60",
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
},
edits: [ create({ defaults: { y: 20 } }) ],
}),
],
});
mount(chart.dom());
```
### Example: Composite key — a band × band grid
unique({ field: ["x","y"] }) allows at most one mark per (x, y) cell.
Try: **Drag** to another cell · **Click** an empty cell to add · **`Alt`+click** to delete.
```javascript
const chart = Elicit({
width: 400, height: 320,
data: [
{ x: "A", y: "Low", group: "alpha" },
{ x: "B", y: "Mid", group: "beta" },
{ x: "C", y: "High", group: "gamma" },
],
constraints: [ unique({ field: ["x", "y"], max: 1 }) ],
schema: {
x: { type: "categorical", domain: ["A", "B", "C"] },
y: { type: "ordinal", domain: ["Low", "Mid", "High"] },
group: { type: "ordinal", domain: ["alpha", "beta", "gamma"] },
},
marks: [
point({
size: 12,
channels: {
x: { field: "x" },
y: { field: "y" },
fill: { field: "group" },
},
edits: [
move({ channels: ["x", "y"] }),
create({ defaults: { group: "alpha" } }),
remove({ when: when.alt }),
],
}),
],
});
mount(chart.dom());
```
## ordering — fields of a row, in order
An error bar's caps and mean are separate marks over separate fields of one row. `ordering` keeps those fields in order across all three marks, whichever handle you drag. A low cap dragged above the high one would otherwise turn the interval inside-out.
### Example: An interval that can’t invert
ordering({ field: ["lo", "mean", "hi"] }) — one rule across three marks.
Try: **Drag** the low cap up past the mean: the mean and the high cap move up with it.
```javascript
const chart = Elicit({
width: 320, height: 260,
margins: { top: 20, right: 20, bottom: 30, left: 44 },
axes: { y: {}, x: false },
schema: {
q: { type: "categorical", domain: ["2027 GDP"] },
lo: { type: "quantitative", domain: [0, 10] },
mean: { type: "quantitative", domain: [0, 10] },
hi: { type: "quantitative", domain: [0, 10] },
},
data: [{ q: "2027 GDP", lo: 2, mean: 4, hi: 6 }],
// Declared ONCE, on the dataset — so it holds whichever of the three
// handles you grab, and would hold for a create or a keyboard nudge too.
constraints: [ ordering({ field: ["lo", "mean", "hi"] }) ],
marks: [
// An interval glyph is three marks over three FIELDS of one row.
ruleY({ channels: { x: { field: "q" },
y1: { field: "lo" }, y2: { field: "hi" } },
stroke: "#94A5B3", strokeWidth: 2 }),
tickY({ channels: { x: { field: "q" }, y: { field: "lo",
edit: move() } }, stroke: "#6F8294" }),
tickY({ channels: { x: { field: "q" }, y: { field: "hi",
edit: move() } }, stroke: "#6F8294" }),
point({ size: 7, fill: "#50AEB7",
channels: { x: { field: "q" }, y: { field: "mean",
edit: move() } } }),
],
});
mount(chart.dom());
```
## follow and symmetric — a range that moves with its mean
`follow({ field: ['lo', 'hi'], lead: 'mean' })` moves the listed columns by the amount the `lead` column moved. Drag the mean and the whole interval travels with it. Drag an end and only that end moves, because `follow` reacts to the lead alone. The handles are plain `move()` edits.
### Example: A range that follows its mean
follow({ field: ["lo", "hi"], lead: "mean" }) — the ends move with the mean, and on their own.
Try: **Drag** the mean: the interval keeps its width and shape. **Drag** a cap: that end moves alone, so the interval can be lopsided.
```javascript
const chart = Elicit({
width: 320, height: 260,
margins: { top: 20, right: 20, bottom: 30, left: 44 },
axes: { y: {}, x: false },
schema: {
q: { type: "categorical", domain: ["2027 GDP"] },
lo: { type: "quantitative", domain: [0, 10] },
mean: { type: "quantitative", domain: [0, 10] },
hi: { type: "quantitative", domain: [0, 10] },
},
data: [{ q: "2027 GDP", lo: 2.5, mean: 4, hi: 7 }],
constraints: [
// Drag the mean: lo and hi move by the same amount.
follow({ field: ["lo", "hi"], lead: "mean" }),
ordering({ field: ["lo", "mean", "hi"] }),
clamp({ field: ["lo", "mean", "hi"] }),
],
marks: [
ruleY({ channels: { x: { field: "q" },
y1: { field: "lo" }, y2: { field: "hi" } },
stroke: "#94A5B3", strokeWidth: 2 }),
tickY({ channels: { x: { field: "q" }, y: { field: "lo",
edit: move() } }, stroke: "#6F8294" }),
tickY({ channels: { x: { field: "q" }, y: { field: "hi",
edit: move() } }, stroke: "#6F8294" }),
point({ size: 7, fill: "#50AEB7",
channels: { x: { field: "q" }, y: { field: "mean",
edit: move() } } }),
],
});
mount(chart.dom());
```
`symmetric({ field: ['lo', 'hi'], about: 'mean' })` mirrors the pair about the centre. Drag one end and the other moves to the same distance on the opposite side. It takes exactly two columns.
Declare them in the order `[follow, symmetric, ordering, clamp]`. Constraints run in the order you list them, so the coupling settles first, then `ordering` and `clamp` repair what it produced.
### Example: A symmetric interval
symmetric({ field: ["lo", "hi"], about: "mean" }) added — one end's drag mirrors the other.
Try: **Drag** the low cap down: the high cap rises by the same amount. **Drag** the mean: the interval travels with it, still symmetric.
```javascript
const chart = Elicit({
width: 320, height: 260,
margins: { top: 20, right: 20, bottom: 30, left: 44 },
axes: { y: {}, x: false },
schema: {
q: { type: "categorical", domain: ["2027 GDP"] },
lo: { type: "quantitative", domain: [0, 10] },
mean: { type: "quantitative", domain: [0, 10] },
hi: { type: "quantitative", domain: [0, 10] },
},
data: [{ q: "2027 GDP", lo: 2, mean: 4, hi: 6 }],
constraints: [
follow({ field: ["lo", "hi"], lead: "mean" }),
// Drag one end: the other mirrors it about the mean.
symmetric({ field: ["lo", "hi"], about: "mean" }),
ordering({ field: ["lo", "mean", "hi"] }),
clamp({ field: ["lo", "mean", "hi"] }),
],
marks: [
ruleY({ channels: { x: { field: "q" },
y1: { field: "lo" }, y2: { field: "hi" } },
stroke: "#94A5B3", strokeWidth: 2 }),
tickY({ channels: { x: { field: "q" }, y: { field: "lo",
edit: move() } }, stroke: "#6F8294" }),
tickY({ channels: { x: { field: "q" }, y: { field: "hi",
edit: move() } }, stroke: "#6F8294" }),
point({ size: 7, fill: "#50AEB7",
channels: { x: { field: "q" }, y: { field: "mean",
edit: move() } } }),
],
});
mount(chart.dom());
```
## monotonic — a curve that can’t go back on itself
A CDF, a survival function or a dose-response curve can't dip, but a drawn stroke can. `monotonic` repairs the drag: it pushes the rows the moved point would have crossed.
### Example: A curve that can only rise
monotonic({ field: "p", along: "year" }) — the rule behind every CDF.
Try: **Drag** a middle point up hard: the points to its right rise to meet it. Drag it down and the points to its left drop instead.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 16, right: 16, bottom: 32, left: 42 },
schema: {
year: { type: "quantitative", domain: [2025, 2032] },
p: { type: "quantitative", domain: [0, 1] },
},
data: [
{ year: 2025, p: 0.05 }, { year: 2026, p: 0.12 },
{ year: 2027, p: 0.20 }, { year: 2028, p: 0.34 },
{ year: 2029, p: 0.45 }, { year: 2030, p: 0.60 },
{ year: 2031, p: 0.72 }, { year: 2032, p: 0.80 },
],
// "By when will it have happened?" — a cumulative probability cannot dip,
// because a dip is negative probability mass. The gesture has no idea; the
// dataset invariant does.
constraints: [
monotonic({ field: "p", along: "year" }),
clamp({ min: 0, max: 1, field: "p" }),
],
marks: [
lineY({
stroke: "#50AEB7", handleSize: 5,
channels: { x: { field: "year" },
y: { field: "p", edit: move() } },
}),
],
});
mount(chart.dom());
```
A [locked](https://elicitjs.github.io/editing/existence.md#seed) row stays where it is. The dragged value stops at the nearest locked row on either side, and the push carries between them.
## spacing — neighbours that keep their distance
`spacing` keeps values a minimum distance apart. Use it where the values must stay distinct: thresholds of a scale, breakpoints of a piecewise curve, tiers of a rubric. Two points at the same value are usually a slip. Once they overlap, the top one takes every grab and you can't separate them.
### Example: Thresholds that stay apart
spacing({ field: "at", min: 8 }) — no two boundaries closer than 8 points.
Try: **Drag** one threshold into its neighbour: it pushes its neighbour, and the push carries down the line. The push keeps the values in order, so this field doesn't need `ordering` as well.
```javascript
const chart = Elicit({
width: 420, height: 170,
margins: { top: 20, right: 24, bottom: 34, left: 24 },
axes: { x: {}, y: false },
schema: {
grade: { type: "categorical", domain: ["D", "C", "B", "A"] },
at: { type: "quantitative", domain: [0, 100] },
},
data: [
{ grade: "D", at: 50 }, { grade: "C", at: 65 },
{ grade: "B", at: 78 }, { grade: "A", at: 90 },
],
// Where do the grade boundaries go? Two coincident thresholds are almost
// always a slip of the hand — they read as one, and the top one then takes
// every later grab, so they can never be separated again.
// `min` is in DATA units: a constraint never sees the scale, and a rule that
// changed meaning when the chart was resized wouldn't be an invariant.
constraints: [
spacing({ field: "at", min: 8 }),
clamp({ min: 0, max: 100, field: "at" }),
],
marks: [
tickX({
strokeWidth: 2, stroke: "#50AEB7",
channels: { x: { field: "at", edit: move() } },
}),
text({
dy: -14, fontSize: 11, fill: "#566A7C",
channels: { x: { field: "at" }, text: { field: "grade" } },
}),
],
});
mount(chart.dom());
```
The chain always fits inside the field's domain. With three thresholds beyond the one you drag, the dragged one stops `3 × min` short of the domain's edge, which leaves room for the three it pushes.
---
# Layout
> Source: https://elicitjs.github.io/layout/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A **layout** settles marks in pixel space after an edit commits, then writes the settled positions and sizes back into the dataset. Declare layouts in `layout: [...]` on the `Elicit` spec. The root layouts work on any table: `layout.dodge` keeps marks from overlapping, `layout.row`, `layout.column`, `layout.grid` and `layout.pack` arrange them into slots or clusters, `layout.tidy` lines a hand layout up, and `layout.custom` runs your own pass. A layout that needs a structure is scoped to it: `layout.network.layered`, `tree` and `force` place a [network](https://elicitjs.github.io/marks/network.md)'s nodes by its links, and `layout.hierarchy.contain` sizes containers in a [hierarchy](https://elicitjs.github.io/marks/hierarchy.md).
## API reference
### `Built-in layouts`
Import `layout` from `elicitjs` and pass in the `Elicit` spec’s `layout: [...]`. Each rule settles mark boxes in pixel space and writes the resulting positions and sizes back to the dataset.
JSON keyword: `layout.hierarchy.contain`, `layout.dodge`, `layout.row`, `layout.column`, `layout.grid`, `layout.pack`, `layout.tidy`
```ts
layout.hierarchy.contain({ padding?, fit?, where? }) → Layout
layout.dodge({ gap?, in?, where?, table? }) → Layout
layout.row({ gap?, in?, where?, table? }) → Layout
layout.column({ gap?, in?, where?, table? }) → Layout
layout.grid({ columns?, gap?, in?, where?, table? }) → Layout
layout.pack({ gap?, keep?, in?, where?, table? }) → Layout
layout.tidy({ snap?, gap?, in?, where?, table? }) → Layout
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `contain.where` | `(d, i, rows) => boolean` | `all containers` | Picks the containers this padding and fit apply to. Which rows may take a drop is `constraints.contain` or a mark’s `contains`. |
| `contain.padding` | `number \| { top, right, bottom, left }` | `10` | Room in px between a container’s edge and its contents. |
| `contain.fit` | `boolean \| 'x' \| 'y'` | `false` | Resize containers to enclose their contents on both axes (`true`), width only (`"x"`), height only (`"y"`), or keep their given size (`false`). |
| `dodge.gap` | `number` | `8` | Minimum space in px kept between overlapping siblings. |
| `where` | `(d, i, rows) => boolean` | `all rows` | Picks the rows the layout acts on: the rows that dodge, take a slot, line up, or (on `hierarchy.contain`) the containers its padding and fit apply to. The others stay where they are. |
| `in` | `'all' \| 'roots' \| 'containers' \| ((parent, i, rows) => boolean)` | `'all' (dodge, tidy) / 'containers' (row, column, grid, pack)` | Scopes a rule to a level of a hierarchy: top-level roots, every container, both, or containers matching a predicate. On a flat table, `"containers"` and a predicate match nothing and log a warning. |
| `gap` | `number` | `8` | Space in px between slots in `row`, `column`, `grid` or `pack`. A negative or non-number `gap` on any layout logs a warning and takes the default. |
| `grid.columns` | `number` | `as many as fit` | Cells per row in `layout.grid`. |
| `pack.keep` | `'distance' \| 'angle'` | `'distance'` | How a dropped mark moves in to touch the cluster: `"distance"` picks the nearest free spot; `"angle"` preserves its direction from the cluster’s centre. |
| `tidy.snap` | `number` | `16` | Centres this close, in px, share a row or a column. |
| `tidy.gap` | `number` | `8` | Space in px a mark needs clear of its neighbours to keep its cell. |
| `table` | `string` | `nodes (hierarchy) or primary table` | Table name or role the layout settles in a multi-table schema. Scoped layouts (`layout.network.*`, `layout.hierarchy.*`) always settle their structure’s nodes table. |
### `Network layouts`
Place nodes from their links. Each works on the nodes table of a dataset with a links table: a network, or a hierarchy that declares one.
JSON keyword: `layout.network.layered`, `layout.network.tree`, `layout.network.force`
```ts
layout.network.layered({ direction?, gap?, rankGap?, place?, where? }) → Layout
layout.network.tree({ direction?, gap?, rankGap?, place?, where? }) → Layout
layout.network.force({ length?, gap?, place?, where? }) → Layout
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `direction` | `'down' \| 'right' \| 'up' \| 'left' (tree also 'radial')` | `'down'` | Which way links run (`layered`) or the tree grows from its root (`tree`). |
| `gap` | `number` | `24 (layered), 12 (tree), 8 (force)` | Space in px between neighbouring boxes. |
| `rankGap` | `number` | `48 (layered), 40 (tree)` | Space in px between ranks or depths. |
| `force.length` | `number` | `100` | Distance in px between the centres of two linked nodes. |
| `place` | `'new' \| 'all'` | `'new'` | `"new"` positions only rows with no position; `"all"` redraws every row when the nodes or links change. Locked rows stay put. |
| `where` | `(d, i, rows) => boolean` | `every node` | Picks the nodes the layout places. The others stay where they are. |
### `layout.custom(fn, options?)`
Author your own pixel-space layout pass. It runs after the built-in layouts, and the rows it moves are written back to the dataset.
JSON keyword: `layout.custom`
```ts
layout.custom(({ rows, tables, tree, nodeBox, extentOf, scales, width, height, locked, anchors, yields, preview, shift, shiftTree, write }) => rows | void, { table?, where? }) → Layout
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `fn` | `(ctx) => rows \| void` | `required` | Reads a row’s drawn box with `ctx.nodeBox(i)` and moves it with `ctx.shift(i, dx, dy)`, in plot pixels, or sets its fields with `ctx.write(i, patch)`. It can also return a new array of rows. |
| `ctx.nodeBox(i) / ctx.extentOf(i)` | `→ { cx, cy, hw, hh } \| null` | | The row’s drawn box, and the space its whole glyph takes, in plot pixels. |
| `ctx.shift(i, dx, dy) / ctx.shiftTree(i, dx, dy)` | `→ void` | | Move a row by a pixel delta, alone or with every row nested inside it. A locked row stays where it is. |
| `ctx.write(i, patch)` | `→ void` | | Merge fields into a row. |
| `ctx.rows / ctx.tables / ctx.tree` | `Datum[] / Record / tree` | | The rows as the earlier layouts left them, every table, and the hierarchy’s containment. |
| `ctx.locked / ctx.anchors / ctx.yields / ctx.preview` | `fn \| null / Set / Set \| null / boolean` | | Which rows are locked, which hold their place, which the gesture moved, and whether a drag is still going. |
| `table` | `string` | `primary table` | Table name or role to settle. |
| `where` | `(d, i, rows) => boolean` | `all rows` | The rows `fn` may change. Changes to any other row are dropped. |
## Layout vs constraints
[Constraints](https://elicitjs.github.io/constraints.md) and layouts enforce two different kinds of rule:
- A **constraint** is a pure-data invariant (`maintainSum`, `clamp`, `ordering`, `constraints.contain`). It runs on committed data rows and applies across every chart sharing a dataset.
- A **layout** works in **pixel space**. It measures each mark's drawn box (its width, height, radius or label extent), resolves overlaps, slots or container fits, and inverts the settled pixels back into the data columns within the same undo step.
While you drag, overlapping or slotted neighbours preview live and ease with `motion`; the settled positions commit once on release.
The rows a layout settles then run through the dataset's constraints for that table, so a `clamp` still holds. If a constraint rejects them, the layout's rows are kept and a warning says so.
## dodge — keep marks apart
`layout.dodge({ gap, where, in })` pushes overlapping marks apart by `gap` pixels (default `8`). It works on any table of positioned marks — cards, scatter points, or network nodes — with no hierarchy required.
```js
layout: [
layout.dodge({ gap: 10 }),
]
```
When you drop a mark on top of another, the dropped mark holds its place and the others move the shortest distance that clears it. Locked rows stay put.
### Example: Non-overlapping cards on a flat table
layout.dodge({ gap: 10 }) keeps draggable cards apart without a hierarchy.
Try: **Drag** any card onto another and release: the others make room.
```javascript
const chart = Elicit({
width: 520, height: 300,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
id: { type: "categorical", key: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 400] },
h: { type: "quantitative", domain: [0, 200] },
},
data: [
{ id: "a", label: "Clarity", x: 25, y: 65, w: 96, h: 32 },
{ id: "b", label: "Speed", x: 50, y: 65, w: 96, h: 32 },
{ id: "c", label: "Cost", x: 75, y: 65, w: 96, h: 32 },
{ id: "d", label: "Safety", x: 35, y: 32, w: 96, h: 32 },
{ id: "e", label: "Trust", x: 65, y: 32, w: 96, h: 32 },
],
layout: [
layout.dodge({ gap: 10 }),
],
marks: [
rect({
cornerRadius: 6,
fill: "#EDF7F8",
stroke: "#46596B",
edits: [move({ channels: ["x", "y"], mode: "relative" })],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
},
}),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
},
}),
],
});
mount(chart.dom());
```
## row, column, grid and pack
Arrangement rules place marks into slots or tight clusters:
- `layout.row({ gap, in, where })` arranges left to right, wrapping at the available width.
- `layout.column({ gap, in, where })` arranges top to bottom, wrapping at the available height.
- `layout.grid({ columns, gap, in, where })` places equal cells in reading order.
- `layout.pack({ gap, keep, in, where })` draws marks together until they touch, edge to edge for boxes and circumference to circumference for circles.
On a flat table or a network, every row in the table takes part.
### Example: Packed circles on a flat table
layout.pack({ gap: 4 }) gathers dragged circles into a tight cluster.
Try: **Drag** any circle to the edge of the cluster and let go: it slides in to touch.
```javascript
const chart = Elicit({
width: 520, height: 300,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
id: { type: "categorical", key: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
r: { type: "quantitative", domain: [0, 100] },
},
data: [
{ id: "a", label: "Solar", x: 50, y: 50, r: 28 },
{ id: "b", label: "Wind", x: 50, y: 50, r: 24 },
{ id: "c", label: "Hydro", x: 50, y: 50, r: 22 },
{ id: "d", label: "Grid", x: 50, y: 50, r: 20 },
{ id: "e", label: "Heat", x: 50, y: 50, r: 18 },
],
layout: [
layout.pack({ gap: 4 }),
],
marks: [
point({
fill: "#C3B9DF",
stroke: "#46596B",
edits: [move({ channels: ["x", "y"], mode: "relative" })],
channels: {
x: { field: "x" },
y: { field: "y" },
size: { field: "r", scale: null },
},
}),
text({
fontSize: 10,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
},
}),
],
});
mount(chart.dom());
```
## Composing levels in a hierarchy
In a [hierarchy](https://elicitjs.github.io/marks/hierarchy.md), `in` scopes each rule to a level of the tree. `dodge`, `tidy`, `row`, `column`, `grid` and `pack` all take the same values:
- `"containers"` — inside every container (the default for `row`, `column`, `grid` and `pack`).
- `"roots"` — top-level nodes only.
- `"all"` — both roots and containers (the default for `dodge` and `tidy`).
- `(parent, i, rows) => boolean` — only inside containers matching the predicate.
A flat table's rows are all roots. There, `"containers"` and a predicate match nothing, so the layout does nothing and logs a warning.
Combine rules in `layout: [...]` to arrange roots one way and container contents another. `layout.hierarchy.contain({ padding, fit })` accepts `fit: true`, `"x"`, `"y"`, or `false` so containers can grow on a single axis while holding a fixed width.
### Example: Lanes in a row, cards in a column
layout.row({ in: "roots" }) aligns lanes side by side; layout.column stacks cards and fit: "y" grows each lane vertically.
Try: **Drag** a lane left or right to reorder the columns. **Drag** a card within a lane or into another lane: the lane grows or shrinks vertically while keeping its width.
```javascript
const chart = Elicit({
width: 560, height: 340,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["lane", "card"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600], default: 150 },
h: { type: "quantitative", domain: [0, 600], default: 72 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "todo", label: "To do", kind: "lane", x: 18, y: 80, w: 150, h: 72 },
{ id: "doing", label: "Doing", kind: "lane", x: 50, y: 80, w: 150, h: 72 },
{ id: "done", label: "Done", kind: "lane", x: 82, y: 80, w: 150, h: 72 },
{ id: "c1", label: "Write brief", kind: "card", x: 18, y: 78, w: 130, h: 28 },
{ id: "c2", label: "Recruit", kind: "card", x: 18, y: 66, w: 130, h: 28 },
{ id: "c3", label: "Pilot", kind: "card", x: 50, y: 78, w: 130, h: 28 },
{ id: "c4", label: "Ethics", kind: "card", x: 82, y: 78, w: 130, h: 28 },
],
nesting: [
{ child: "c1", parent: "todo" },
{ child: "c2", parent: "todo" },
{ child: "c3", parent: "doing" },
{ child: "c4", parent: "done" },
],
},
constraints: [
constraints.contain({ parent: (d) => d.kind === "lane", child: (d) => d.kind === "card" }),
],
layout: [
layout.hierarchy.contain({ padding: { top: 30, right: 10, bottom: 10, left: 10 }, fit: "y" }),
layout.row({ in: "roots", gap: 16 }),
layout.column({ in: (d) => d.kind === "lane", gap: 6 }),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "lane" ? "#EDF7F8" : "#FFFFFF") },
},
}),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
dy: { fn: (d) => (d.kind === "lane" ? -d.h / 2 + 15 : 0) },
},
}),
],
});
mount(chart.dom());
```
## Network layouts
`layout.network.*` places nodes from their links. Each one works on the nodes table of a dataset with links: a network, or a [hierarchy](https://elicitjs.github.io/marks/hierarchy.md) that declares a links table. On a dataset with no links it logs a warning and does nothing. `where` picks the nodes it places.
- `layout.network.layered({ direction, gap, rankGap, place, where })` draws ranks for flowcharts and causal maps. Every link runs one way (`direction`: `"down"`, `"right"`, `"up"` or `"left"`), and nodes in a rank are ordered to cut crossings. A cycle has to break somewhere, so one link in each loop points back.
- `layout.network.tree({ direction, gap, rankGap, place, where })` draws a tidy tree for trees and mind maps. Each parent sits centred on its children, and siblings keep the order you drew them in. `direction: "radial"` puts the root in the middle with a ring per depth. The root is a node no link points to. Links that make a cycle or give a node two parents are left out of the layout, with a warning.
- `layout.network.force({ length, gap, place, where })` spreads a concept map. Linked nodes sit about `length` px apart (default `100`), and other pairs sit farther apart the more links lie between them. The same rows always give the same drawing.
`gap` is the space in px between neighbouring boxes, and `rankGap` the space between ranks or depths.
### Example: A causal map laid out in ranks
layout.network.layered places factors that have no position. The loop through Supply points one link back up.
Try: **Drag** a factor anywhere: it stays where you drop it. **Drag** from a port to another factor to add a cause.
```javascript
const chart = Elicit({
width: 560, height: 440,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "network",
tables: {
factors: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
causes: {
role: "links",
directed: true,
fields: {
source: { type: "ref" },
target: { type: "ref" },
},
},
},
},
// No row has a position: the layout places them all.
data: {
factors: [
{ id: "rates", label: "Interest rates" },
{ id: "mort", label: "Mortgage cost" },
{ id: "wages", label: "Wages" },
{ id: "migr", label: "Migration" },
{ id: "demand", label: "Demand" },
{ id: "rents", label: "Rents" },
{ id: "price", label: "House prices" },
{ id: "build", label: "Construction" },
{ id: "supply", label: "Supply" },
],
causes: [
{ source: "rates", target: "mort" },
{ source: "mort", target: "demand" },
{ source: "wages", target: "demand" },
{ source: "migr", target: "demand" },
{ source: "migr", target: "rents" },
{ source: "demand", target: "price" },
{ source: "rents", target: "price" },
{ source: "price", target: "build" },
{ source: "build", target: "supply" },
{ source: "supply", target: "price" },
],
},
layout: [
layout.network.layered({ direction: "down", gap: 20, rankGap: 28 }),
],
marks: [
link({ arrow: true, stroke: "#7D8B99" }),
sticker({
fill: "#ECF3F9",
stroke: "#1D4467",
cornerRadius: 8,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "label" },
ports: { value: true, edit: edit.network.connect() },
},
}),
],
});
mount(chart.dom());
```
### Example: A mind map as a tidy tree
layout.network.tree({ direction: "right", place: "all" }) redraws the tree on every change.
Try: **Drag** Hiking below Museums and let go: the two swap places.
```javascript
const chart = Elicit({
width: 560, height: 440,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "network",
tables: {
ideas: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
branches: {
role: "links",
directed: true,
fields: {
source: { type: "ref" },
target: { type: "ref" },
},
},
},
},
data: {
ideas: [
{ id: "trip", label: "Trip", x: 50, y: 50 },
{ id: "travel", label: "Travel", x: 20, y: 80 },
{ id: "stay", label: "Stay", x: 80, y: 85 },
{ id: "budget", label: "Budget", x: 85, y: 20 },
{ id: "acts", label: "Activities", x: 25, y: 20 },
{ id: "flights", label: "Flights", x: 45, y: 90 },
{ id: "train", label: "Train", x: 8, y: 55 },
{ id: "hotel", label: "Hotel", x: 95, y: 55 },
{ id: "friends", label: "Friends", x: 70, y: 65 },
{ id: "hike", label: "Hiking", x: 50, y: 15 },
{ id: "museum", label: "Museums", x: 8, y: 8 },
{ id: "cap", label: "Daily cap", x: 68, y: 35 },
],
branches: [
{ source: "trip", target: "travel" },
{ source: "trip", target: "stay" },
{ source: "trip", target: "acts" },
{ source: "trip", target: "budget" },
{ source: "travel", target: "flights" },
{ source: "travel", target: "train" },
{ source: "stay", target: "hotel" },
{ source: "stay", target: "friends" },
{ source: "acts", target: "hike" },
{ source: "acts", target: "museum" },
{ source: "budget", target: "cap" },
],
},
layout: [
layout.network.tree({ direction: "right", gap: 8, place: "all" }),
],
marks: [
link({ stroke: "#7D8B99" }),
sticker({
fill: "#F3F0FA",
stroke: "#4B3D78",
cornerRadius: 8,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "label" },
},
}),
],
});
mount(chart.dom());
```
## Placing new rows or every row
`place` decides which rows a network layout moves.
- `place: "new"` (the default) positions only rows with no `x` or `y` yet: the seed, a `setData` call, or rows added from outside. Every row that has a position stays where it is, so a participant's arrangement is never redrawn.
- `place: "all"` redraws every row whenever the nodes or links change. It starts from the current drawing, so a dragged node changes its rank order, sibling order or starting point instead of springing back.
Locked rows stay put under both.
### Example: New concepts placed around the ones already drawn
layout.network.force({ length: 80 }) places the seven concepts with no position. The three placed ones stay where they are.
Try: **Drag** any concept: nothing else moves.
```javascript
const chart = Elicit({
width: 560, height: 360,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "network",
tables: {
concepts: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
relations: {
role: "links",
directed: false,
fields: {
source: { type: "ref" },
target: { type: "ref" },
},
},
},
},
// Three concepts are placed; the rest arrive with no position.
data: {
concepts: [
{ id: "co2", label: "CO₂", x: 50, y: 55 },
{ id: "temp", label: "Temperature", x: 75, y: 55 },
{ id: "emis", label: "Emissions", x: 25, y: 55 },
{ id: "energy", label: "Energy" },
{ id: "coal", label: "Coal" },
{ id: "solar", label: "Solar" },
{ id: "forest", label: "Forests" },
{ id: "ice", label: "Ice melt" },
{ id: "sea", label: "Sea level" },
{ id: "ocean", label: "Oceans" },
],
relations: [
{ source: "energy", target: "coal" },
{ source: "energy", target: "solar" },
{ source: "coal", target: "emis" },
{ source: "emis", target: "co2" },
{ source: "forest", target: "co2" },
{ source: "co2", target: "temp" },
{ source: "temp", target: "ice" },
{ source: "ice", target: "sea" },
{ source: "temp", target: "ocean" },
{ source: "ocean", target: "co2" },
],
},
layout: [
layout.network.force({ length: 80 }),
],
marks: [
link({ stroke: "#7D8B99" }),
sticker({
fill: "#EDF7F1",
stroke: "#22573A",
cornerRadius: 8,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "label" },
},
}),
],
});
mount(chart.dom());
```
## where — lay out some of the rows
Every layout takes `where: (d, i, rows) => boolean`. It picks the rows the layout acts on, and the others stay where they are. On `layout.dodge` the picked rows dodge, on `row`, `column`, `grid` and `pack` they take the slots, on `tidy` they line up, and a network layout places them, leaving links to other nodes out of the layout. On `layout.hierarchy.contain` it picks the containers its `padding` and `fit` apply to, and `layout.custom` can change only the rows it picks. Give two layouts different `where` rules to lay out two parts of one diagram differently.
In a hierarchy, a container with `fit: true` grows round the nodes the layout places inside it. A node the layout moves carries its own contents.
### Example: Two groups, each with its own layout
layout.network.layered({ where: (d) => d.kind === "step" }) places the sign-up steps, and layout.network.tree({ where: (d) => d.kind === "topic" }) the help topics. The groups and the note are left where they are.
Try: **Drag** a group: its nodes go with it. **Drag** a step away and let go: it goes back to its rank.
```javascript
const chart = Elicit({
width: 640, height: 420,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["group", "step", "topic", "note"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600] },
h: { type: "quantitative", domain: [0, 400] },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
links: {
directed: true,
fields: {
source: { type: "ref" },
target: { type: "ref" },
},
},
},
},
// The groups and the note are placed. The steps and topics have no position:
// each group's layout places them.
data: {
nodes: [
{ id: "signup", label: "Sign-up flow", kind: "group", x: 22, y: 55, w: 120, h: 120 },
{ id: "help", label: "Help topics", kind: "group", x: 68, y: 55, w: 120, h: 120 },
{ id: "visit", label: "Visit", kind: "step", w: 76, h: 26 },
{ id: "join", label: "Sign up", kind: "step", w: 76, h: 26 },
{ id: "verify", label: "Verify", kind: "step", w: 76, h: 26 },
{ id: "profile", label: "Profile", kind: "step", w: 76, h: 26 },
{ id: "skip", label: "Skip", kind: "step", w: 76, h: 26 },
{ id: "done", label: "Done", kind: "step", w: 76, h: 26 },
{ id: "faq", label: "Help", kind: "topic", w: 76, h: 26 },
{ id: "account", label: "Account", kind: "topic", w: 76, h: 26 },
{ id: "billing", label: "Billing", kind: "topic", w: 76, h: 26 },
{ id: "password", label: "Password", kind: "topic", w: 76, h: 26 },
{ id: "email", label: "Email", kind: "topic", w: 76, h: 26 },
{ id: "refunds", label: "Refunds", kind: "topic", w: 76, h: 26 },
{ id: "note", label: "Where do people drop off?", kind: "note", x: 70, y: 8, w: 190, h: 30 },
],
nesting: [
{ child: "visit", parent: "signup" },
{ child: "join", parent: "signup" },
{ child: "verify", parent: "signup" },
{ child: "profile", parent: "signup" },
{ child: "skip", parent: "signup" },
{ child: "done", parent: "signup" },
{ child: "faq", parent: "help" },
{ child: "account", parent: "help" },
{ child: "billing", parent: "help" },
{ child: "password", parent: "help" },
{ child: "email", parent: "help" },
{ child: "refunds", parent: "help" },
],
links: [
{ source: "visit", target: "join" },
{ source: "join", target: "verify" },
{ source: "verify", target: "profile" },
{ source: "verify", target: "skip" },
{ source: "profile", target: "done" },
{ source: "skip", target: "done" },
{ source: "faq", target: "account" },
{ source: "faq", target: "billing" },
{ source: "account", target: "password" },
{ source: "account", target: "email" },
{ source: "billing", target: "refunds" },
],
},
constraints: [
constraints.contain({ parent: (d) => d.kind === "group" }),
],
layout: [
layout.hierarchy.contain({ padding: { top: 30, right: 14, bottom: 14, left: 14 }, fit: true }),
// Each layout places only the nodes `where` picks.
layout.network.layered({ where: (d) => d.kind === "step", gap: 14, rankGap: 20, place: "all" }),
layout.network.tree({ where: (d) => d.kind === "topic", direction: "right", gap: 8, rankGap: 26, place: "all" }),
// Keep the groups and the note apart as the groups grow.
layout.dodge({ in: "roots", gap: 16 }),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [move({ channels: ["x", "y"], mode: "relative" })],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "group" ? "#F3F6F9" : d.kind === "note" ? "#FFF6DD" : "#DCEAF6") },
},
}),
link({ stroke: "#46596B", arrow: true }),
text({
fontSize: 11,
fill: "#20414F",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
dy: { fn: (d) => (d.kind === "group" ? -d.h / 2 + 15 : 0) },
},
}),
],
});
mount(chart.dom());
```
## Layouts and link shapes together
A layout places the nodes, and the link mark's `curve` draws the links between them. `sourceSide` and `targetSide` pin where a link leaves and arrives, so its ends follow the layout's direction. Links are drawn one at a time, so several can end at one point on a node, and long links in a layered drawing pass close to the nodes they skip.
## tidy — line a hand layout up
`layout.tidy({ snap, gap, where, in })` keeps the arrangement you drew and straightens it. Centres within `snap` px of each other (default `16`) share a row or a column. Rows and columns that are nearly evenly spaced become exactly even. A mark that overlaps another and stands alone in its column moves to the nearest free cell in its row, keeping `gap` px clear (default `8`). It works on any table, and `in` scopes it in a hierarchy as it does `dodge`.
### Example: A rough sketch lined up
layout.tidy({ snap: 20 }) snaps the cards into rows and columns and moves Docs off Ship.
Try: **Drag** a card near a row and let go: it lines up with it.
```javascript
const chart = Elicit({
width: 520, height: 300,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
id: { type: "categorical", key: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
// A rough sketch: nearly in rows and columns, one card on top of another.
data: [
{ id: "a", label: "Idea", x: 14, y: 78 },
{ id: "b", label: "Research", x: 47, y: 82 },
{ id: "c", label: "Sketch", x: 78, y: 75 },
{ id: "d", label: "Prototype", x: 12, y: 48 },
{ id: "e", label: "Test", x: 44, y: 44 },
{ id: "f", label: "Feedback", x: 80, y: 51 },
{ id: "g", label: "Ship", x: 15, y: 15 },
{ id: "h", label: "Docs", x: 24, y: 17 },
],
layout: [
layout.tidy({ snap: 20, gap: 10 }),
],
marks: [
sticker({
fill: "#FBF3E6",
stroke: "#6B4A1D",
cornerRadius: 6,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "label" },
},
}),
],
});
mount(chart.dom());
```
## Custom pixel-space layouts
`layout.custom(fn, { table?, where? })` runs your own pass after the built-in layouts. `fn` reads each row's drawn box and moves the row in plot pixels. The move is written back to the row's columns through the channels' scales.
```js
layout: [
// Keep every box inside the plot's left and right edges.
layout.custom(({ rows, nodeBox, shift, width }) => {
rows.forEach((row, i) => {
const box = nodeBox(i);
if (!box) return;
const cx = Math.max(box.hw, Math.min(width - box.hw, box.cx));
shift(i, cx - box.cx, 0);
});
}),
]
```
`fn` receives one context:
- `rows` and `tables` are the rows as the earlier layouts left them.
- `nodeBox(i)` is row `i`'s drawn box, `{ cx, cy, hw, hh }` in plot pixels, or `null` when no mark draws the row. `extentOf(i)` is the space the whole glyph takes, label included.
- `shift(i, dx, dy)` moves a row by a pixel delta. `shiftTree(i, dx, dy)` also moves every row nested inside it.
- `write(i, patch)` merges fields into a row.
- `width`, `height` and `scales` describe the plot.
- `tree` is the hierarchy's containment: `parentOf(i)`, `childrenOf(i)`.
- `locked(row, i)` tells a locked row. `anchors` is the set of rows that hold their place, and `yields` the set the gesture moved. `preview` is `true` while a drag is still going.
`shift` and `write` leave a locked row as it is, and a row outside `where`. `fn` can also return a new array of rows.
---
# Datasets & linked charts
> Source: https://elicitjs.github.io/dataset/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`Elicit.dataset(spec)` makes a dataset: the rows, the schema, the constraints and the undo history. `ds.chart(spec)` draws it, and any number of charts can read and write one dataset: an edit in one chart redraws every other. `Elicit(spec)` is the one-call form, a dataset and one chart from one spec.
## API reference
### `Elicit.dataset(spec)`
A dataset that any number of charts read and write. It holds the rows, the schema, the dataset’s rules, the undo history and the selection. Make a chart over it with `ds.chart(spec)`.
JSON keyword: `spec`
```ts
Elicit.dataset({ schema, data?, constraints?, lock?, context?, onChange? }) → Dataset
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `schema` | `Schema` | `required` | Each field’s type and domain. See [Data schema](https://elicitjs.github.io/schema.md). |
| `data` | `Datum[] \| Record` | `[]` | The seed rows. |
| `constraints` | `Constraint[]` | `[]` | Rules that gate and repair every edit from every chart, and every `set`. See [Constraints](https://elicitjs.github.io/constraints.md). |
| `lock / context` | `LockSpec / ContextSpec` | | Read-only rows and reference rows, in every chart. See [Locked rows](https://elicitjs.github.io/editing/existence.md#seed) and [Context rows](https://elicitjs.github.io/editing/existence.md#context). |
| `onChange` | `(data) => void` | | Called once per commit, from any chart, with the committed data. |
Returns / emits: A **Dataset**: `chart`, `getData`, `getSchema`, `setData`, `setDomain`, `set`, `undo` / `redo` / `canUndo` / `canRedo`, `transaction`, `hover` / `getHover`, `on("change" | "select" | "hover")` and the [selection](https://elicitjs.github.io/editing/selection.md) methods. See [Getting started](https://elicitjs.github.io/start.md#api) for each.
### `ds.chart(spec)`
A chart over the dataset. It takes every spec key the dataset doesn’t: `marks`, `elements`, size, `axes`, `theme`, `guides`, `effects`, `layout`, stages. Append `chart.dom()` to the page.
JSON keyword: `spec`
```ts
ds.chart({ marks, width?, height?, … }) → Chart
parent.append(chart.dom())
```
Returns / emits: A **Chart**: `dom()`, `dataset`, `control`, `emit`, `on("stage" | "render" | "destroy")`, the [stage](https://elicitjs.github.io/editing/probe.md#basics) methods, the [read methods](https://elicitjs.github.io/editing/external-controls.md#reading) and `destroy()`, plus the dataset’s methods.
### `ds.set(field, value, options?)`
Write one cell from outside any chart. Runs the dataset’s constraints, then the lock. One undo step; fires `change` and redraws every chart. A value outside a closed categorical domain is refused with a warning; one outside a numeric or temporal domain is clamped to it.
No JSON form: this is called in JavaScript.
```ts
ds.set("share", 40) // row 0 of the primary table
ds.set("share", "40", { index: 2 }) // stored as the number 40
ds.set("weight", 3, { index: 0, table: "links" })
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `index` | `number` | `0` | The row, counted as `getData()` reports them: context rows left out. |
| `table` | `string` | `the primary table` | The table the row is in. |
Returns / emits: `true` when it commits. `false` when a constraint rejects it, the row is locked or the value is unchanged, and, with a warning, for an undeclared field, an index out of range or a value the field’s type can’t hold.
### `ds.hover(row) / ds.getHover()`
The dataset’s hovered row, which every chart with a [linked hover](#hover) shows. It is interface state: no `change` event and no undo step. A row is named as the [selection](https://elicitjs.github.io/editing/selection.md) names it: a row of the primary table by its index, a row of another table as `{ table, index }`.
No JSON form: this is called in JavaScript.
```ts
ds.hover(2) // hover row 2 of the primary table
ds.hover({ table: "links", index: 0 }) // a row of another table
ds.hover(null) // clear it
ds.getHover() // 2, { table, index }, or null
ds.on("hover", (row) => { … })
```
Returns / emits: `hover` returns `true` when the hovered row changed.
## Two charts, one dataset
Split the spec in two. `Elicit.dataset` takes `schema`, `data`, `constraints`, `lock`, `context` and `onChange`. `ds.chart` takes everything else: `marks`, size, `axes`, `theme`, `guides`. A chart is a plain object, so append `chart.dom()` to the page.
```js
const ds = Elicit.dataset({ schema, data, constraints });
const split = ds.chart({ marks: [barX({ … })] });
const people = ds.chart({ marks: [waffleY({ … })] });
document.body.append(split.dom(), people.dom());
```
Give each chart the gesture it is best at. Here one bar of 100 patients takes `edit.stack.edge()`: drag the edge between two outcomes to trade one for the other. A waffle of the same counts takes `edit.waffle.fill()`: paint a block to say how many people land in it. An edit in either chart commits to the dataset, and both charts redraw from the new rows. `maintainSum` keeps the total at 100 in both, because it is the dataset's.
### Example: Out of 100 patients
The bar trades one outcome for its neighbour. The waffle sets one outcome's count, and maintainSum takes the difference from the others.
Try: **Drag** an edge in the bar, or **paint** a block of people. The other chart follows.
```javascript
// Four outcomes for 100 patients. The counts always sum to 100.
const outcomes = ["Recovers", "Improves", "No change", "Worse"];
const ds = Elicit.dataset({
schema: {
cohort: { type: "categorical", domain: ["100 patients"] },
outcome: { type: "categorical", domain: outcomes },
count: { type: "quantitative", domain: [0, 100] },
},
data: [
{ cohort: "100 patients", outcome: "Recovers", count: 40 },
{ cohort: "100 patients", outcome: "Improves", count: 30 },
{ cohort: "100 patients", outcome: "No change", count: 20 },
{ cohort: "100 patients", outcome: "Worse", count: 10 },
],
constraints: [
clamp({ min: 0, field: "count" }),
maintainSum({ total: 100, field: "count", strategy: "redistribute" }),
],
});
// One bar of 100. Drag the edge between two outcomes to trade one for the other.
const split = ds.chart({
width: 440, height: 140,
margins: { top: 8, right: 16, bottom: 26, left: 16 },
axes: { y: false },
elements: [legendColor({ anchor: "top" })],
marks: [
barX({
channels: {
y: { field: "cohort" },
x: { field: "count" },
stack: { field: "outcome" },
fill: { field: "outcome" },
},
edits: [edit.stack.edge()],
}),
],
});
// The same counts as people. Paint a block to set how many land in it.
const people = ds.chart({
width: 440, height: 170,
margins: { top: 8, right: 16, bottom: 26, left: 16 },
marks: [
waffleY({
multiple: 10,
channels: {
x: { field: "outcome" },
count: { field: "count", edit: edit.waffle.fill() },
fill: { field: "outcome" },
},
}),
],
});
mount(split.dom());
mount(people.dom());
```
## Three charts, two columns
A chart writes the columns its channels encode. Two line charts each draw one column over `year`, and `move({ pick: "sweep" })` writes it as you sweep. A third chart plots `unemployment` against `inflation`, one dot per year, joined by `path` in year order. `move({ channels: ["x", "y"] })` writes both columns of the dot you drag.
Draw the two lines over time and the third chart shows the trade-off they imply. Drag a year in the trade-off and both lines bend at that year.
### Example: Unemployment, inflation and the trade-off
The lines write one column each. The scatter writes both.
Try: **Sweep** across a line chart, or **drag** a year in the scatter.
```javascript
// Seven years, two columns to forecast.
const ds = Elicit.dataset({
schema: {
year: { type: "quantitative", domain: [2026, 2032] },
unemployment: { type: "quantitative", domain: [3, 8] },
inflation: { type: "quantitative", domain: [1, 6] },
},
data: [
{ year: 2026, unemployment: 7.4, inflation: 1.6 },
{ year: 2027, unemployment: 6.6, inflation: 1.9 },
{ year: 2028, unemployment: 5.8, inflation: 2.4 },
{ year: 2029, unemployment: 5.1, inflation: 3.0 },
{ year: 2030, unemployment: 4.6, inflation: 3.7 },
{ year: 2031, unemployment: 4.3, inflation: 4.4 },
{ year: 2032, unemployment: 4.1, inflation: 5.0 },
],
});
// Sweep across a chart to draw one column over time.
const overTime = (field, title, stroke) => ds.chart({
width: 440, height: 150,
margins: { top: 10, right: 16, bottom: 26, left: 44 },
axes: { x: { tickFormat: "d" }, y: { title } },
marks: [
lineY({
stroke, strokeWidth: 2.5,
channels: { x: { field: "year" }, y: { field, edit: move({ pick: "sweep" }) } },
}),
],
});
// Both columns at once, one dot per year, joined in year order.
// Drag a dot to set that year's unemployment and inflation together.
const tradeOff = ds.chart({
width: 440, height: 260,
margins: { top: 14, right: 16, bottom: 34, left: 44 },
axes: { x: { title: "Unemployment (%)" }, y: { title: "Inflation (%)" } },
marks: [
path({
stroke: "#94A5B3", strokeWidth: 1.5,
channels: { x: { field: "unemployment" }, y: { field: "inflation" } },
}),
point({
fill: "#1B3F60", size: 6,
channels: { x: { field: "unemployment" }, y: { field: "inflation" } },
edits: [move({ channels: ["x", "y"] })],
}),
text({
dx: 10, dy: -8, fontSize: 11, textAnchor: "start", fill: "#46596B", format: "d",
channels: { x: { field: "unemployment" }, y: { field: "inflation" }, text: { field: "year" } },
}),
],
});
mount(overTime("unemployment", "Unemployment (%)", "#50AEB7").dom());
mount(overTime("inflation", "Inflation (%)", "#EE7B5E").dom());
mount(tradeOff.dom());
```
## One chart per table
A dataset with `structure: "network"` holds two tables, `nodes` and `links`. Each mark draws one table, and `table:` names it. Here a network chart draws both tables, and a bar chart draws `nodes` alone. Add a factor in the graph and it gets a bar. Its circle grows with the weight you give it.
`create()` gives a new node the key `"Item 1"`, `"Item 2"` and so on, and each new node starts at the `default` you declare for `importance`.
### Example: A causal map with weights
The graph writes nodes and links. The bars write each node's importance.
Try: **Shift-drag** from one factor to another to add a cause. **Click** empty space to add a factor. **Drag** a bar to weigh it.
```javascript
// A network: factors (nodes) and what causes what (links).
const ds = Elicit.dataset({
schema: {
structure: "network",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
importance: { type: "quantitative", domain: [0, 10], default: 5 },
},
links: {
role: "links",
directed: true,
fields: {
source: { type: "ref" },
target: { type: "ref" },
},
},
},
},
data: {
nodes: [
{ id: "Interest rates", x: 16, y: 80, importance: 8 },
{ id: "Migration", x: 16, y: 20, importance: 5 },
{ id: "New supply", x: 50, y: 88, importance: 6 },
{ id: "Speculation", x: 50, y: 12, importance: 3 },
{ id: "House prices", x: 84, y: 50, importance: 9 },
],
links: [
{ source: "Interest rates", target: "House prices" },
{ source: "Migration", target: "House prices" },
],
},
});
// Draw the structure. Drag a factor to move it, shift-drag from one to another
// to say it causes it, click empty space to add a factor.
const graph = ds.chart({
width: 440, height: 260,
margins: { top: 24, right: 44, bottom: 24, left: 44 },
axes: false,
marks: [
link({ inset: 3, stroke: "#94A5B3", strokeWidth: 1.5 }),
node({
fill: "#50AEB7",
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], when: when.noShift }) },
y: { field: "y" },
size: { field: "importance", scale: { range: [4, 16] } },
text: { field: "id" },
},
edits: [
edit.network.connect({ when: when.shift }),
create(),
],
}),
],
});
// Weigh each factor. The bars draw the nodes table.
const weights = ds.chart({
width: 440, height: 200,
margins: { top: 10, right: 16, bottom: 30, left: 100 },
axes: { x: { title: "Importance" } },
marks: [
barX({
table: "nodes",
fill: "#50AEB7",
channels: { y: { field: "id" }, x: { field: "importance", edit: move() } },
}),
],
});
mount(graph.dom());
mount(weights.dom());
```
## A chart that only shows
A chart with no edits is a view. It redraws on every commit like any other chart. Here you set a rent estimate for each Vancouver local area on the bars, and the map shows where your estimates rise and fall. Both charts colour by `change` on a diverging scale, so a bar and its area share a colour.
### Example: Rent change by local area
The bars take move(). The map takes no edits.
Try: **Drag** a bar left or right. Its area on the map recolours.
```javascript
// One row per Vancouver local area: its outline and your estimate.
const guess = {
"Kitsilano": -3, "West Point Grey": -4, "Dunbar-Southlands": -3, "Kerrisdale": -5,
"Arbutus Ridge": -4, "Shaughnessy": -6, "Fairview": 1, "West End": 2,
"Downtown": 3, "South Cambie": 0, "Oakridge": -1, "Marpole": 2,
"Riley Park": 3, "Mount Pleasant": 5, "Strathcona": 7, "Grandview-Woodland": 6,
"Kensington-Cedar Cottage": 4, "Sunset": 3, "Victoria-Fraserview": 4,
"Hastings-Sunrise": 6, "Renfrew-Collingwood": 5, "Killarney": 4,
};
const areas = vancouver.features
.map((f) => ({ area: f.properties.name, geometry: f.geometry, change: guess[f.properties.name] ?? 0 }))
.sort((a, b) => a.area.localeCompare(b.area));
const ds = Elicit.dataset({
schema: {
area: { type: "categorical" },
geometry: { type: "categorical" },
change: { type: "quantitative", domain: [-10, 10] },
},
data: areas,
});
const colour = { field: "change", scale: { type: "diverging", scheme: "dddiverging" } };
// Set each estimate here.
const bars = ds.chart({
width: 440, height: 400,
margins: { top: 10, right: 16, bottom: 30, left: 160 },
axes: { x: { title: "Rent change next year (%)" } },
marks: [
barX({
channels: {
y: { field: "area", scale: { reverse: true } },
x: { field: "change", edit: move() },
fill: colour,
},
}),
],
});
// The map has no edits. It recolours on every change.
const map = ds.chart({
width: 440, height: 300,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
marks: [
geoPolygon({
stroke: "#fff", strokeWidth: 1,
channels: { geometry: { field: "geometry", scale: null }, fill: colour },
}),
],
});
mount(map.dom());
mount(bars.dom());
```
## Write from outside a chart
`ds.set(field, value, { index, table })` writes one cell from your own code: a slider, an input or a script. `index` counts the rows `getData()` reports, from 0, and defaults to 0. `table` defaults to the primary table. The value is stored as the field's type, so a slider's `"40"` becomes the number `40`.
A value outside the field's declared domain follows one rule, for `ds.set` and for the `set()` and `editText()` edits. A closed categorical or ordinal domain refuses it and logs a warning. A numeric or temporal domain clamps it to its ends, as a drag does. An `open` domain takes it.
The write runs the dataset's constraints and then the lock, as an edit does. An edit's own `constrain` doesn't run, because no edit is involved. Each `set` is one undo step, fires `change` once and redraws every chart.
`set` returns `true` when it commits. It returns `false` when a constraint rejects the value, the row is locked or the value is unchanged. An undeclared field, an index out of range or a value the field's type can't hold also logs a warning.
`set` writes rows that exist. To add rows from code, call `setData`, or replay a `create` gesture with `chart.emit`. To drive a named edit through a chart's scales, use [`chart.control`](https://elicitjs.github.io/editing/external-controls.md).
### Example: A slider beside two charts
The slider calls ds.set("share", value, { index: 0 }). maintainSum repairs the other shares.
Try: **Move** the slider, or **drag** a bar. The pie, the bars and the slider stay in step.
```javascript
// Three shares that always sum to 100. The rule is the dataset's, so it holds
// for a drag in either chart and for the slider below.
const ds = Elicit.dataset({
schema: {
party: { type: "categorical", domain: ["D", "R", "O"] },
share: { type: "quantitative", domain: [0, 100] },
},
data: [
{ party: "D", share: 45 },
{ party: "R", share: 40 },
{ party: "O", share: 15 },
],
constraints: [clamp({ min: 0, field: "share" }), maintainSum({ total: 100, strategy: "redistribute" })],
});
const pie = ds.chart({
width: 340, height: 200,
margins: { top: 10, right: 10, bottom: 10, left: 10 },
axes: false,
marks: [
arc({
outerRadius: 85,
channels: { theta: { field: "share" }, fill: { field: "party" } },
}),
],
});
const bars = ds.chart({
width: 340, height: 180,
margins: { top: 10, right: 16, bottom: 28, left: 36 },
marks: [
barY({
channels: {
x: { field: "party" },
y: { field: "share", edit: move() },
fill: { field: "party" },
},
}),
],
});
mount(pie.dom());
mount(bars.dom());
// A plain HTML slider. `ds.set` writes row 0's share; the constraints repair
// the other rows, and both charts redraw.
const label = document.createElement("label");
label.style.cssText = "display:flex;gap:10px;align-items:center;margin-top:10px;font:13px system-ui";
label.textContent = "D's share";
const slider = document.createElement("input");
slider.type = "range"; slider.min = 0; slider.max = 100; slider.step = 1;
slider.oninput = () => ds.set("share", slider.value, { index: 0 });
label.append(slider);
mount(label);
// A drag in either chart moves the slider too.
const sync = () => { slider.value = ds.getData()[0].share; };
ds.on("change", sync);
sync();
```
## One history, one selection
The undo history belongs to the dataset. A gesture in any chart is one step, and `ds.undo()` steps back the last gesture, whichever chart it happened in. `setData` clears the history.
Here you click the map to add a place you expect to flood, and its bar appears below. Drag the bar to set the depth, and the place's circle grows on the map. Undo steps back the depth, then the place, in both charts. `count({ max: 8 })` caps the number of places.
### Example: Where it floods, and how deep
The map writes lon and lat. The bars write depth. ds.undo() steps back either.
Try: **Click** the map to add a place, **drag** its bar, then press **Undo** twice.
```javascript
// Up to eight places you expect to flood, and how deep.
const ds = Elicit.dataset({
schema: {
id: { type: "categorical", key: true },
lon: { type: "quantitative", domain: [-123.27, -123.02] },
lat: { type: "quantitative", domain: [49.20, 49.32] },
depth: { type: "quantitative", domain: [0, 3], default: 0.5 },
},
data: [
{ id: "Item 1", lon: -123.115, lat: 49.272, depth: 1.2 },
{ id: "Item 2", lon: -123.130, lat: 49.206, depth: 0.8 },
],
constraints: [count({ max: 8 })],
});
// Click the map to add a place. Drag a pin to move it.
// Its circle grows with the depth you set below.
const map = ds.chart({
width: 440, height: 300,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
marks: [
geoBasemap({ geojson: vancouver, fill: "#EDF7F8", stroke: "#6F8294", strokeWidth: 0.7 }),
geoPoint({
fill: "#2B5D87", fillOpacity: 0.7, stroke: "#fff", strokeWidth: 1.5,
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
size: { field: "depth", scale: { range: [3, 18] } },
},
edits: [edit.geo.move(), edit.geo.create()],
}),
geoText({
dy: -14, fontSize: 11, fill: "#20555A",
channels: { lon: { field: "lon" }, lat: { field: "lat" }, text: { field: "id" } },
}),
],
});
// Each place gets a bar as soon as it exists. Drag it to set the depth.
const depths = ds.chart({
width: 440, height: 200,
margins: { top: 10, right: 16, bottom: 30, left: 56 },
axes: { x: { title: "Flood depth (m)" } },
marks: [
barX({
fill: "#2B5D87",
channels: { y: { field: "id" }, x: { field: "depth", edit: move() } },
}),
],
});
mount(map.dom());
mount(depths.dom());
// One history for both charts.
const controls = document.createElement("div");
controls.style.cssText = "display:flex;gap:8px;margin-top:10px;font:12px system-ui";
const undo = document.createElement("button");
const redo = document.createElement("button");
undo.textContent = "↶ Undo";
redo.textContent = "↷ Redo";
undo.onclick = () => ds.undo();
redo.onclick = () => ds.redo();
const sync = () => {
undo.disabled = !ds.canUndo();
redo.disabled = !ds.canRedo();
};
ds.on("change", sync);
sync();
controls.append(undo, redo);
mount(controls);
```
The selection belongs to the dataset too. Select a row in one chart and every chart outlines it. `ds.on("select")` fires once per change. See [Selection](https://elicitjs.github.io/editing/selection.md).
## Linked hover
Charts on one dataset link their hover. Point at a row in one chart and every chart outlines that row and fades the others. A chart with no edits takes part: every mark that draws rows answers the pointer. Hover writes no data and adds no undo step.
### Example: Rent and income, by district
Two charts, no effects in either spec. The bars are draggable and the dots are view-only.
Try: **Hover** a bar or a dot. The same district lights up in the other chart.
```javascript
// Six districts: what people pay, and what they earn.
const ds = Elicit.dataset({
schema: {
district: { type: "categorical", domain: ["Ash", "Birch", "Cedar", "Dale", "Elm", "Fern"] },
rent: { type: "quantitative", domain: [0, 3000] },
income: { type: "quantitative", domain: [0, 100] },
},
data: [
{ district: "Ash", rent: 2400, income: 82 },
{ district: "Birch", rent: 1500, income: 48 },
{ district: "Cedar", rent: 1900, income: 71 },
{ district: "Dale", rent: 900, income: 35 },
{ district: "Elm", rent: 2100, income: 55 },
{ district: "Fern", rent: 1200, income: 62 },
],
});
// Neither chart sets `effects`. Two charts on one dataset link their hover.
const bars = ds.chart({
width: 440, height: 200,
margins: { top: 10, right: 16, bottom: 30, left: 44 },
axes: { y: { title: "Rent" } },
marks: [
bar({
fill: "#50AEB7",
channels: { x: { field: "district" }, y: { field: "rent", edit: move() } },
}),
],
});
// A view-only chart takes part too.
const scatter = ds.chart({
width: 440, height: 220,
margins: { top: 10, right: 16, bottom: 36, left: 44 },
axes: { x: { title: "Income" }, y: { title: "Rent" } },
marks: [
point({
fill: "#F4A259", size: 7,
channels: { x: { field: "income" }, y: { field: "rent" } },
}),
],
});
mount(bars.dom());
mount(scatter.dom());
```
`effects.hovered.link` sets a chart's part in it. `true` sends the chart's hover and shows the others'. `"receive"` shows the others' hover and sends none. `false` keeps hover inside the chart. The default is `true` when two or more charts draw the dataset.
```js
ds.chart({ marks, effects: { hovered: { link: "receive" } } });
```
`effects.hovered.others` styles the faded rows, and `others: false` keeps the outline alone. See [Highlight and mute](https://elicitjs.github.io/effects.md#mute).
`ds.getHover()` returns the hovered row, and `ds.on("hover", cb)` fires when it changes. A row of the primary table is its index; a row of another table is `{ table, index }`, as in the selection. `ds.hover(row)` sets it from outside a chart, such as a table row beside the charts, in either form, and `ds.hover(null)` clears it.
For a highlight that stays, use the selection: `edit.select()` on the mark and `effects: { selected: { others: { opacity: 0.25 } } }`.
## What each chart keeps
Every chart on a dataset shares:
- the rows, the schema and its domains, so a zoom in one chart zooms every chart;
- `constraints`, `lock` and `context`;
- the undo history, the selection and the [linked hover](#hover);
- `onChange` and `on("change")`, which fire once per commit, whichever chart made it.
Each chart keeps its own marks, size, `theme`, `guides`, `effects` and stages. `chart.on("stage")` and the stage methods are the chart's own. `chart.control` and `chart.emit` replay a gesture on that chart, through its edits and its scales.
A chart also carries the dataset's methods, so `chart.getData()` and `chart.undo()` work on a chart from `Elicit(spec)`. `chart.dataset` is the dataset itself. A dataset key passed to `ds.chart()`, such as `constraints`, is ignored with a warning that points to `Elicit.dataset`.
`chart.destroy()` detaches one chart. The other charts keep working, and the dataset keeps its rows and history.
A chart draws the dataset's rows as they are. A [view](#view) shows the same rows another way. To show a summary of them, such as a histogram of another chart's points, compute it in a `change` listener and give it a dataset of its own.
A [hierarchy](https://elicitjs.github.io/marks/hierarchy.md) fits its node boxes in one chart's pixels: the chart where the last gesture happened, or, for seed data, `setData` and `set`, the first chart that draws the boxes. Other charts draw the stored boxes as they are.
---
# Bar
> Source: https://elicitjs.github.io/marks/bar/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`bar` draws one rectangle per row: a categorical **band** on one axis, and a **value** on the other, drawn as length from a baseline or as a span (`x1`/`x2`, `y1`/`y2`). `bar` takes its orientation from the band axis; `barY` forces vertical, `barX` horizontal. For rectangles that span both axes, use [`rect`](https://elicitjs.github.io/marks/rect.md) with `brushRect()`.
## API reference
### `bar(options) · barY(options) · barX(options)`
Import `plot` from `elicitjs`. `bar` infers orientation from which axis is a band; `barY` forces vertical, `barX` horizontal. All three share these options.
JSON keyword: `plot.bar`, `plot.barY`, `plot.barX`
```ts
bar({ channels, orientation, edits, id }) → Mark
barY(options) → Mark // orientation: "vertical"
barX(options) → Mark // orientation: "horizontal"
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | Channel map — one band axis (category) and one linear axis (value or a span). See **Channels**. |
| `image` | `string \| (d) => string \| ChannelSpec` | | The shape's background image: a URL painted inside each shape in place of the fill. Takes `fit`, `position` and `repeat` as channel params, as in CSS. See [Image](https://elicitjs.github.io/marks/image.md#settings). |
| `orientation` | `'vertical' \| 'horizontal'` | `auto` | Override the inferred direction (bar only; barY/barX pin it). |
| `handles / handleSize / handleColor` | `boolean \| 'hit' / number / string` | `true with a stack edit / 5 / theme` | Boundary dots on a stacked bar. Unset, they draw once a `edit.stack.*` edit is wired. `true` always draws them, as ink on a bar with no edit. `'hit'` keeps them grabbable but invisible. `false` is neither drawn nor grabbable. |
| `gradient` | `{ stops, direction }` | | A linear-gradient fill over each bar’s own box, in place of a flat `fill`. `stops` is a list of `[offset, colour]` with offsets 0–1; `direction` is `'vertical'` (default, bottom to top) or `'horizontal'` (left to right). |
| `cornerRadius` | `number` | `theme (0)` | Corner radius in px. Defaults to the theme’s `marks.bar.cornerRadius`. |
| `edits` | `Edit[]` | | Mark-level edits; per-channel edits live in `channels[ch].edit`. A stacked bar also takes `edit.stack.cut()`, `edit.stack.edge()` and `edit.stack.merge()`. |
| `fill, stroke, …` | `style` | `fill: 'steelblue'` | Style shorthands / channels (see the style surface on any mark). |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x` | `band \| linear` | Category (band) or value (linear), depending on orientation. |
| `y` | `band \| linear` | The other axis. The value axis carries `edit: move()` to make bars draggable. |
| `y1 / y2` | `linear` | Explicit vertical span (barY) — draw between two values instead of from the baseline. With one end given, the other is the baseline. |
| `x1 / x2` | `linear` | Explicit horizontal span (barX) — a Gantt-style range per category. |
| `xOffset / yOffset` | `band` | A second category nested inside each `x` (or `y`) category: one sub-band per value, for grouped bars. |
| `stack` | `categorical \| ordinal field` | Stack the bars that share a band. The field names each segment and sets their order (its schema domain, else first appearance). `edit.stack.cut()` writes a new segment’s category into it. Declare a schema domain covering the stacked total. |
| `fill, stroke, strokeWidth, opacity` | `const \| field` | Standard style surface; a field tints through the ordinal palette. |
Returns / emits: A **mark** emitting one `rect` per datum, styled through the standard surface.
## Band × value
The band axis places the bars. The linear axis sets their length from a baseline.
### Example: A vertical bar chart
x band of categories, y linear value.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ cat: "A", n: 30 }, { cat: "B", n: 55 },
{ cat: "C", n: 22 }, { cat: "D", n: 44 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
marks: [
bar({
fill: "#50AEB7",
channels: {
x: { field: "cat" },
y: { field: "n" },
},
}),
],
});
mount(chart.dom());
```
### Example: Colour by a field
fill: { field: "kind" } tints each bar through the ordinal palette.
```javascript
const chart = Elicit({
width: 340, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ cat: "A", n: 34, kind: "low" }, { cat: "B", n: 58, kind: "high" },
{ cat: "C", n: 22, kind: "low" }, { cat: "D", n: 47, kind: "high" },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
kind: { type: "categorical", domain: ["low", "high"] },
},
marks: [
bar({
channels: {
x: { field: "cat" },
y: { field: "n" },
fill: { field: "kind" },
},
}),
],
});
mount(chart.dom());
```
`gradient: { stops, direction }` fills each bar with a linear gradient over its own box. Each stop is `[offset, colour]`, from 0 to 1. `direction: 'vertical'` (the default) runs from the bottom of the bar to its top; `'horizontal'` runs left to right. `area` and `rect` take the same option.
### Example: A gradient fill
gradient: { stops: [[0, pale], [1, teal]] } — every bar shades from bottom to top.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ cat: "A", n: 30 }, { cat: "B", n: 55 },
{ cat: "C", n: 22 }, { cat: "D", n: 44 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
marks: [
bar({
// Offset 0 is the bottom of each bar, 1 the top.
gradient: { stops: [[0, "#EDF7F8"], [1, "#50AEB7"]] },
channels: {
x: { field: "cat" },
y: { field: "n", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Horizontal bars (barX)
Put the band on `y` and the value on `x`, and the bars run horizontally. `barX` forces this orientation; `bar` infers it from the band axis.
### Example: barX — value on x
y is the category band, x the linear value drawn rightward from the baseline.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 14, right: 16, bottom: 26, left: 60 },
data: [
{ region: "North", sales: 42 }, { region: "South", sales: 68 },
{ region: "East", sales: 30 }, { region: "West", sales: 54 },
],
schema: {
region: { type: "categorical", domain: ["North", "South", "East", "West"] },
sales: { type: "quantitative", domain: [0, 80] },
},
marks: [
barX({
fill: "#1B3F60",
channels: {
y: { field: "region" },
x: { field: "sales" },
},
}),
],
});
mount(chart.dom());
```
## Stacked bars
The `stack` channel stacks the bars that share a band. Each segment sits on the cumulative total of the ones before it. Rows with the same `x` (or `y`, for `barX`) stack together. Declare a schema domain that covers the stacked **total**.
The `stack` field names each segment, and must be categorical or ordinal. Segments follow the order of its schema domain, so the same category sits at the same height in every band. With no domain declared, they follow the order the values first appear in the data. Colour is separate: bind `fill` to the same field to colour each segment by its category.
`stack` is the counterpart of `xOffset`: `xOffset` places the rows of a band side by side, and `stack` places them end to end. Without either, rows that share a band draw over each other. Elicit.js logs a warning, unless the bars are translucent (a constant `opacity` or `fillOpacity` below 1), which layers them on purpose. A span (`x1`/`x2` or `y1`/`y2`) places each bar itself, so `stack` has no effect on it.
### Example: A stacked bar chart
stack and fill both on { field: "asset" }. The pct domain covers the total, [0, 100].
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
data: [
{ year: "2023", asset: "stocks", pct: 50 },
{ year: "2023", asset: "bonds", pct: 30 },
{ year: "2023", asset: "cash", pct: 20 },
{ year: "2024", asset: "stocks", pct: 65 },
{ year: "2024", asset: "bonds", pct: 20 },
{ year: "2024", asset: "cash", pct: 15 },
],
schema: {
year: { type: "categorical", domain: ["2023", "2024"] },
asset: { type: "categorical", domain: ["stocks", "bonds", "cash"] },
pct: { type: "quantitative", domain: [0, 100] },
},
legends: true,
marks: [
bar({
channels: {
x: { field: "year" },
y: { field: "pct" },
stack: { field: "asset" },
fill: { field: "asset" },
},
}),
],
});
mount(chart.dom());
```
## Grouped bars (xOffset, yOffset)
`xOffset` splits each `x` category into one sub-band per value of a second field, so the bars of one category sit side by side. `yOffset` does the same inside each `y` category, for grouped `barX`. The offset needs a categorical `x` (or `y`) to divide. It has no axis, so colour the groups with `fill` on the same field and turn on its legend.
Sub-bands touch by default, and the gap between categories is the `x` band's padding. `scale: { padding }` on the offset channel opens a gap inside each group. `yOffset` puts its first value at the bottom of the slot, as a band `y` axis does.
### Example: Grouped bars
xOffset: { field: "year" } splits each region into three sub-bands. y carries edit: move().
Try: **Drag** any bar up or down.
```javascript
const chart = Elicit({
width: 400, height: 250,
margins: { top: 16, right: 16, bottom: 28, left: 36 },
data: [
{ region: "North", year: "2022", sales: 40 }, { region: "North", year: "2023", sales: 55 },
{ region: "North", year: "2024", sales: 62 }, { region: "South", year: "2022", sales: 30 },
{ region: "South", year: "2023", sales: 34 }, { region: "South", year: "2024", sales: 48 },
{ region: "West", year: "2022", sales: 52 }, { region: "West", year: "2023", sales: 47 },
{ region: "West", year: "2024", sales: 58 },
],
schema: {
region: { type: "categorical", domain: ["North", "South", "West"] },
year: { type: "categorical", domain: ["2022", "2023", "2024"] },
sales: { type: "quantitative", domain: [0, 80] },
},
marks: [
barY({
channels: {
x: { field: "region" },
xOffset: { field: "year" },
y: { field: "sales", edit: move() },
fill: { field: "year", legend: { anchor: "top", title: false } },
},
}),
],
});
mount(chart.dom());
```
A bar draws only for a row that names both a category and a group. Combine `xOffset` with `stack` and each sub-band stacks on its own. `create()` and `toggle()` read the group from where you click, and `move({ channels: ["x", "xOffset"] })` drags a bar into another category and group.
### Example: Fill in one group
context marks 2023 as given; you drag the 2024 bar beside it in each region.
Try: **Drag** a teal bar to your estimate. The grey bars are fixed.
```javascript
// 2023 is given; you estimate 2024 beside it in every region.
const regions = ["North", "South", "West", "East"];
const given = { North: 55, South: 34, West: 47, East: 40 };
const chart = Elicit({
width: 400, height: 250,
margins: { top: 16, right: 16, bottom: 28, left: 36 },
data: regions.flatMap((region) => [
{ region, year: "2023", sales: given[region] },
{ region, year: "2024", sales: given[region] },
]),
context: (d) => d.year === "2023",
schema: {
region: { type: "categorical", domain: regions },
year: { type: "categorical", domain: ["2023", "2024"] },
sales: { type: "quantitative", domain: [0, 80] },
},
constraints: [clamp({ min: 0 })],
marks: [
barY({
channels: {
x: { field: "region" },
xOffset: { field: "year", scale: { padding: 0.1 } },
y: { field: "sales", edit: move() },
fill: { field: "year", scale: { range: ["#BCC9D4", "#50AEB7"] },
legend: { anchor: "top", title: false } },
},
}),
],
});
mount(chart.dom());
```
## Slicing a stack
A stacked bar divides one total among its rows. Three gestures reshape it, the same three that work on a [pie or donut](https://elicitjs.github.io/marks/arc.md#slice):
- `edit.stack.cut()` — **click** inside a segment to divide it in two at that point.
- `edit.stack.edge()` — **drag** a boundary to move value across it. Only the two segments it separates change.
- `edit.stack.merge()` — **double-click** a boundary to fuse those two back into one.
All three preserve the band's total. Cutting divides a magnitude, dragging moves value from one row to its neighbour, and merging adds two into one. Boundary handles appear once one of these edits is set, and take the shared `handles` / `handleSize` / `handleColor` options. With `pick: "nearest"`, a press near a boundary grabs it, which helps with thin segments. A focused boundary also takes the arrow keys.
A cut mints a row and writes its category into the `stack` field, taking a value from that field's schema domain, so building a stack takes no typing. The new segment takes a category that sorts next to the one you cut, so the other segments keep their places. A **closed** domain (the default) hands out the values that band doesn't yet use, and refuses the cut once they run out. Each band draws from its own copy of the domain, so `bonds` in 2023 and `bonds` in 2024 are both available.
### Example: Cut a stack into parts
Each year starts as one 100% block. The asset domain declares four categories, so each band takes four cuts.
Try: **Click** inside a segment to cut it, **drag** a boundary to shift value, **double-click** one to merge.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
data: [
{ year: "2023", asset: "stocks", pct: 100 },
{ year: "2024", asset: "stocks", pct: 100 },
],
schema: {
year: { type: "categorical", domain: ["2023", "2024"] },
asset: { type: "categorical", domain: ["stocks", "bonds", "cash", "gold"] },
pct: { type: "quantitative", domain: [0, 100] },
},
legends: true,
marks: [
bar({
channels: {
x: { field: "year" },
y: { field: "pct" },
stack: { field: "asset" },
fill: { field: "asset" },
},
edits: [
edit.stack.cut(),
edit.stack.edge(),
edit.stack.merge(),
],
}),
],
});
mount(chart.dom());
```
Set `open: true` on the field's schema entry and the domain becomes a starting set instead: a cut appends a new category to it, named from `label` (`"Category"` by default) for you to rename later with `edit.scale.categories()`. An open field also skips the out-of-domain check on seed data.
### Example: An open domain
holding is declared open, so each cut adds a category rather than running out. label: "Holding" names them.
Try: **Click** inside a segment to add a holding.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
data: [{ year: "2024", holding: "VTI", pct: 100 }],
schema: {
year: { type: "categorical", domain: ["2024"] },
holding: { type: "categorical", domain: ["VTI"], open: true },
pct: { type: "quantitative", domain: [0, 100] },
},
legends: true,
marks: [
bar({
channels: {
x: { field: "year" },
y: { field: "pct" },
stack: { field: "holding" },
fill: { field: "holding" },
},
edits: [
edit.stack.cut({ label: "Holding" }),
edit.stack.edge(),
edit.stack.merge(),
],
}),
],
});
mount(chart.dom());
```
## Explicit spans (x1/x2, y1/y2)
Give the value axis two endpoints, `x1`/`x2` for `barX` or `y1`/`y2` for `barY`, and each bar spans from one to the other instead of starting at the baseline. Use it for a range per category, as in a Gantt chart. `x1`/`x2` share the scale of `x` (likewise `y1`/`y2` with `y`), so only one needs an explicit type and domain.
### Example: Years active per person
barX with x1/x2 spans; y is the category band.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 14, right: 16, bottom: 26, left: 60 },
data: [
{ person: "Ada", start: 1830, end: 1852 },
{ person: "Grace", start: 1930, end: 1992 },
{ person: "Alan", start: 1931, end: 1954 },
],
schema: {
person: { type: "categorical", domain: ["Ada", "Grace", "Alan"] },
start: { type: "quantitative", domain: [1820, 2000] },
end: { type: "quantitative", domain: [1840, 2000] },
},
marks: [
barX({
fill: "#8A78C0",
channels: {
y: { field: "person" },
x1: { field: "start" },
x2: { field: "end" },
},
}),
],
});
mount(chart.dom());
```
### Example: Brush: edges + body together
brushSpan() combines both: grab near an edge to resize just that end, grab the body to move the whole span. Drag an edge past the other and release — the fields re-sort (start stays ≤ end) with no visual jump.
Try: **Drag** an edge to resize it, the body to move the whole bar, or drag one edge past the other to see it flip.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 14, right: 16, bottom: 26, left: 60 },
data: [
{ person: "Ada", start: 1830, end: 1852 },
{ person: "Grace", start: 1930, end: 1992 },
{ person: "Alan", start: 1931, end: 1954 },
],
schema: {
person: { type: "categorical", domain: ["Ada", "Grace", "Alan"] },
start: { type: "quantitative", domain: [1820, 2000] },
end: { type: "quantitative", domain: [1840, 2000] },
},
marks: [
barX({
fill: "#50AEB7",
channels: {
y: { field: "person" },
x1: { field: "start" },
x2: { field: "end" },
},
edits: [
brushSpan({ channels: ["x1", "x2"], threshold: 40,
edgeInset: 10, guide: true }),
],
}),
],
});
mount(chart.dom());
```
## Editing bars
Put `edit: move()` on the value channel and drag a bar to rewrite its value. With `pick: "nearest"`, you grab a bar from anywhere in its column, which helps with thin bars. A bar dragged to the baseline collapses to zero length but keeps a minimum grab target, with either pick mode, so you can drag it back up.
### Example: Drag a value
y carries edit: move(). Dragging writes y back through the same scale.
Try: **Drag** a bar up or down.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
bar({
fill: "#50AEB7",
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
},
}),
],
});
mount(chart.dom());
```
### Example: Nearest pick + self-drawn guide
pick: "nearest" grabs a bar from anywhere in its column; guide: true draws the snap ring.
Try: **Drag** from anywhere in a column to grab that bar.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
bar({
fill: "#50AEB7",
channels: {
x: { field: "x" },
y: { field: "y",
edit: move({ pick: "nearest", threshold: 40, guide: true }) },
},
}),
],
});
mount(chart.dom());
```
---
# Rect
> Source: https://elicitjs.github.io/marks/rect/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`rect` draws a rectangle whose extent on each axis resolves separately: a **span** (`x1`/`x2`, `y1`/`y2`), a fixed pixel **size** (`width`/`height`) centred on an anchor, a categorical **band**, or a baseline→value length. Use it for heatmap cells, 2-D regions, binned histograms and annotation boxes, and edit it with `brushRect()`. `rectX` / `rectY` force one axis to a baseline→value length. When one axis is a band and the other a value, use [`bar`](https://elicitjs.github.io/marks/bar.md).
## API reference
### `rect(options) · rectX(options) · rectY(options)`
Import `plot` from `elicitjs`. `rect` spans both axes; `rectX` forces value on x (y a span/band), `rectY` forces value on y. All three share these options.
JSON keyword: `plot.rect`, `plot.rectX`, `plot.rectY`
```ts
rect({ channels, orientation, width, height, cornerRadius, edits, id }) → Mark
rectX(options) → Mark // value on x
rectY(options) → Mark // value on y
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | Channel map — spans (x1/x2, y1/y2), bands, or single x/y values per axis. See **Channels**. |
| `image` | `string \| (d) => string \| ChannelSpec` | | The shape's background image: a URL painted inside each shape in place of the fill. Takes `fit`, `position` and `repeat` as channel params, as in CSS. See [Image](https://elicitjs.github.io/marks/image.md#settings). |
| `orientation` | `'vertical' \| 'horizontal'` | | Draws one axis from the baseline to the value (`'vertical'` = y). `rectY / rectX` set it. Bare `rect` reads each axis from its own channels: a span, a band or a value. |
| `width / height` | `number` | | Fixed pixel extent for every rect, centred on its `x`/`y` anchor. Overrides the band cell and the baseline→value span. Also available per datum as channels. |
| `cornerRadius` | `number` | `theme (0)` | Corner radius in px. Also available per datum as a `cornerRadius` channel. Defaults to the theme’s `marks.rect.cornerRadius`. |
| `gradient` | `{ stops, direction }` | | A linear-gradient fill over each rect’s own box, in place of a flat `fill`. `stops` is a list of `[offset, colour]` with offsets 0–1; `direction` is `'vertical'` (default, bottom to top) or `'horizontal'` (left to right). Same option as on `bar` and `area`. |
| `edits` | `Edit[]` | | Mark-level edits; per-channel edits live in `channels[ch].edit`. Use `brushRect` for 2-D edge/corner/body editing. |
| `fill, stroke, …` | `style` | `fill: 'steelblue'` | Style shorthands / channels (the shared style surface). |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x1 / x2` | `linear` | Horizontal span endpoints. Share x’s resolved scale. With one end given, the other is the baseline. |
| `y1 / y2` | `linear` | Vertical span endpoints. Share y’s resolved scale. With one end given, the other is the baseline. |
| `x / y` | `band \| linear` | A single value (baseline→value), or a band cell when that axis is categorical. For a heatmap, add `scale: { padding: 0 }` so cells touch. |
| `width / height` | `px` | Explicit pixel extent — the rect becomes a fixed-size box centred on its `x`/`y` anchor. Overrides band and baseline→value. |
| `fill, stroke, strokeWidth, opacity` | `const \| field` | Standard style surface; a field tints through the ordinal palette. |
Returns / emits: A **mark** emitting one `rect` per datum.
## A 2-D rectangle (both axes are spans)
Give both axes explicit endpoints and each row draws a rectangle from `x1` to `x2` and `y1` to `y2`.
### Example: Region boxes
x1/x2 and y1/y2 place each rect; fill by a field.
```javascript
const chart = Elicit({
width: 360, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ x1: 1, x2: 4, y1: 1, y2: 3, kind: "a" },
{ x1: 5, x2: 8, y1: 4, y2: 7, kind: "b" },
{ x1: 3, x2: 6, y1: 6, y2: 9, kind: "a" },
],
schema: {
x1: { type: "quantitative", domain: [0, 10] },
x2: { type: "quantitative", domain: [0, 10] },
y1: { type: "quantitative", domain: [0, 10] },
y2: { type: "quantitative", domain: [0, 10] },
kind: { type: "categorical", domain: ["a", "b"] },
},
marks: [
rect({
fillOpacity: 0.6,
channels: {
x1: { field: "x1" }, x2: { field: "x2" },
y1: { field: "y1" }, y2: { field: "y2" },
fill: { field: "kind" },
},
}),
],
});
mount(chart.dom());
```
## Heatmap (both axes categorical)
Put a category on both axes and each row draws one cell at that (`x`, `y`) intersection, giving a heatmap. A quantitative `fill` resolves to a sequential colour ramp, a categorical `fill` to a palette. Band scales pad by default; set `scale: { padding: 0 }` on each axis so the cells touch. A drag can't invert a colour, so edit a cell's value through the legend: `select()` on the cells makes the one you click the target row, and `legendColor({ edit: edit.legend.value() })` drags that row's value along the ramp.
### Example: Coloured cells
A category on x and y; fill by a quantitative field; padding 0 so cells touch.
Try: **Click** a cell to select it, then **drag** the legend handle to set its value.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 16, right: 84, bottom: 30, left: 56 },
data: [
{ day: "Mon", slot: "AM", load: 4 }, { day: "Mon", slot: "PM", load: 9 }, { day: "Mon", slot: "Eve", load: 6 },
{ day: "Tue", slot: "AM", load: 7 }, { day: "Tue", slot: "PM", load: 14 }, { day: "Tue", slot: "Eve", load: 8 },
{ day: "Wed", slot: "AM", load: 12 }, { day: "Wed", slot: "PM", load: 20 }, { day: "Wed", slot: "Eve", load: 11 },
{ day: "Thu", slot: "AM", load: 6 }, { day: "Thu", slot: "PM", load: 16 }, { day: "Thu", slot: "Eve", load: 10 },
],
schema: {
day: { type: "categorical", domain: ["Mon", "Tue", "Wed", "Thu"] },
slot: { type: "categorical", domain: ["AM", "PM", "Eve"] },
load: { type: "quantitative", domain: [0, 20] },
},
marks: [
// A category on BOTH axes draws one cell per (day, slot). `scale: { padding: 0 }`
// removes the band gap so the cells touch, as a heatmap wants. A quantitative
// `fill` resolves to a sequential colour ramp.
// `select()` makes a cell the target row, so the legend edits the one you click.
rect({
edits: [ edit.select() ],
channels: {
x: { field: "day", scale: { padding: 0 } },
y: { field: "slot", scale: { padding: 0 } },
fill: { field: "load" },
},
}),
// Colour isn't gesture-invertible, so the ramp handle sets the value by hand.
// It tracks the selected cell — click a cell, then drag the handle to set it.
legendColor({ anchor: "right", title: "load", edit: edit.legend.value() }),
],
});
mount(chart.dom());
```
## Fixed-size boxes (width/height)
Give an axis a pixel extent with `width` (x) or `height` (y) and the rect becomes a fixed-size box centred on its `x`/`y` anchor. An explicit size overrides the band interval and the baseline→value length. The anchor is a positional channel, so a `move()` on `x` and `y` moves the whole box.
### Example: Boxes at data points
x/y anchor each box; width/height set a constant 28×28 px size.
Try: **Drag** a box to move it (its size stays fixed).
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 16, right: 16, bottom: 30, left: 40 },
data: [
{ x: 1, y: 8, tag: "a" },
{ x: 3, y: 3, tag: "b" },
{ x: 5, y: 6, tag: "c" },
{ x: 7, y: 2, tag: "d" },
],
schema: {
x: { type: "quantitative", domain: [0, 8] },
y: { type: "quantitative", domain: [0, 10] },
tag: { type: "categorical", domain: ["a", "b", "c", "d"] },
},
marks: [
// `width` / `height` are pixel extents, so each rect is a fixed 28x28 box
// centred on its (x, y) anchor — the SVG-native form, alongside x1/x2 spans
// and band cells. The anchor stays a positional channel: a drag on x and y
// inverts the pointer through both scales, so the whole box moves.
rect({
fill: "#50AEB7", fillOpacity: 0.8,
channels: {
x: { field: "x", edit: edit.move() },
y: { field: "y", edit: edit.move() },
width: { value: 28 },
height: { value: 28 },
},
}),
],
});
mount(chart.dom());
```
## Binned histogram (rectY)
`rectY` draws a histogram: `x` is a quantitative bin span (`x1`/`x2`) and `y` is a count from the baseline. Pass data already binned, one row per bin. Use `barY` when bins are categorical labels instead of numeric edges.
### Example: Pre-binned counts
x1/x2 place each bin on a shared quantitative x; y is the count.
```javascript
const chart = Elicit({
width: 400, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ x1: 0, x2: 2, n: 4 },
{ x1: 2, x2: 4, n: 12 },
{ x1: 4, x2: 6, n: 18 },
{ x1: 6, x2: 8, n: 9 },
{ x1: 8, x2: 10, n: 3 },
],
schema: {
x1: { type: "quantitative", domain: [0, 10] },
x2: { type: "quantitative", domain: [0, 10] },
n: { type: "quantitative", domain: [0, 24] },
},
marks: [
rectY({
fill: "#50AEB7", fillOpacity: 0.75,
channels: {
x1: { field: "x1" },
x2: { field: "x2" },
y: { field: "n" },
},
}),
],
});
mount(chart.dom());
```
### Example: Editable bin heights
Drag on y to reshape the distribution; clamp keeps counts ≥ 0.
Try: **Drag** a bin’s top edge to change its count.
```javascript
const chart = Elicit({
width: 400, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ x1: 0, x2: 2, n: 4 },
{ x1: 2, x2: 4, n: 12 },
{ x1: 4, x2: 6, n: 18 },
{ x1: 6, x2: 8, n: 9 },
{ x1: 8, x2: 10, n: 3 },
],
schema: {
x1: { type: "quantitative", domain: [0, 10] },
x2: { type: "quantitative", domain: [0, 10] },
n: { type: "quantitative", domain: [0, 24] },
},
constraints: [clamp({ min: 0, max: 24, field: "n" })],
marks: [
rectY({
fill: "#1B3F60", fillOpacity: 0.75,
channels: {
x1: { field: "x1" },
x2: { field: "x2" },
y: { field: "n", edit: move({ guide: true }) },
},
}),
],
});
mount(chart.dom());
```
## Composable 2-D editing (brushRect)
`brushRect()` edits all four extents. Grab an edge to resize one side, a corner to resize two extents, or the body to move the whole rect. `resize` (`'both' | 'x' | 'y' | 'none'`) sets which axes resize. `move` (boolean) turns the body drag on or off. Together they give resize-one-axis, move-only and resize-only variants.
### Example: Full 2-D: edges, corners, body
Default brushRect(): every direction live.
Try: **Drag** an edge to resize a side, a corner to resize two extents, or the body to move.
```javascript
const chart = Elicit({
width: 360, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [ { x1: 2, x2: 6, y1: 2, y2: 6 } ],
schema: {
x1: { type: "quantitative", domain: [0, 10] },
x2: { type: "quantitative", domain: [0, 10] },
y1: { type: "quantitative", domain: [0, 10] },
y2: { type: "quantitative", domain: [0, 10] },
},
marks: [
rect({
fill: "#50AEB7", fillOpacity: 0.5,
channels: {
x1: { field: "x1" }, x2: { field: "x2" },
y1: { field: "y1" }, y2: { field: "y2" },
},
edits: [ brushRect({ edgeInset: 12 }) ],
}),
],
});
mount(chart.dom());
```
### Example: Resize x only
brushRect({ resize: "x" }) — only the vertical edges resize; body still moves.
Try: **Drag** a left/right edge to resize width; the body to move.
```javascript
const chart = Elicit({
width: 360, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [ { x1: 2, x2: 6, y1: 2, y2: 6 } ],
schema: {
x1: { type: "quantitative", domain: [0, 10] },
x2: { type: "quantitative", domain: [0, 10] },
y1: { type: "quantitative", domain: [0, 10] },
y2: { type: "quantitative", domain: [0, 10] },
},
marks: [
rect({
fill: "#1B3F60", fillOpacity: 0.5,
channels: {
x1: { field: "x1" }, x2: { field: "x2" },
y1: { field: "y1" }, y2: { field: "y2" },
},
edits: [ brushRect({ resize: "x", edgeInset: 12 }) ],
}),
],
});
mount(chart.dom());
```
### Example: Move only
brushRect({ resize: "none" }) — no edges grab; the whole rect translates.
Try: **Drag** anywhere in the rect to move it (edges do nothing).
```javascript
const chart = Elicit({
width: 360, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [ { x1: 3, x2: 7, y1: 3, y2: 7 } ],
schema: {
x1: { type: "quantitative", domain: [0, 10] },
x2: { type: "quantitative", domain: [0, 10] },
y1: { type: "quantitative", domain: [0, 10] },
y2: { type: "quantitative", domain: [0, 10] },
},
marks: [
rect({
fill: "#8A78C0", fillOpacity: 0.5,
channels: {
x1: { field: "x1" }, x2: { field: "x2" },
y1: { field: "y1" }, y2: { field: "y2" },
},
edits: [ brushRect({ resize: "none" }) ],
}),
],
});
mount(chart.dom());
```
## Creating rects
`create()` works on a rect as on any data mark (see [Create · Remove · Anchors](https://elicitjs.github.io/editing/existence.md)). A click gives one point and a rect needs a size, so the creator must seed the extent. A `rectY`-style rect (band or baseline→value length) takes its size from the axis and creates like a `bar`. A 2-D span rect (`x1`/`x2`, `y1`/`y2`) needs the opposite corner from `create({ defaults: { x2, y2 } })`; `brushRect()` then shapes it. Without an extent, the new row mints at zero size, invisible, and logs a warning. On a map, `edit.geo.createRect()` mints a box sized from default spans around the click.
---
# Tick
> Source: https://elicitjs.github.io/marks/tick/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`tick` draws a line at a value on one axis, spanning the other axis. Over a category band it marks a value per category; with no band it spans the full extent, as a rug or strip plot. `tickY` and `tickX` force the value axis; `tick` infers it. `inset` shrinks each end, and `length` sets a fixed, centred length.
## API reference
### `tick(options) · tickY(options) · tickX(options)`
Import `plot` from `elicitjs`. `tick` infers the value axis from which axis is a band; `tickY` marks a value on y (spans the x band), `tickX` on x.
JSON keyword: `plot.tick`, `plot.tickY`, `plot.tickX`
```ts
tick({ channels, orientation, inset, length, edits, id }) → Mark
tickY(options) → Mark // value on y
tickX(options) → Mark // value on x
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | One band axis (span) + one linear axis (the marked value). See **Channels**. |
| `orientation` | `'vertical' \| 'horizontal'` | `auto` | Which axis the value runs along (`'vertical'` = y). Inferred from which axis is a band; `tickY / tickX` pin it. |
| `inset` | `number` | `0` | Pixels to shrink each end of the span. |
| `length` | `number` | | Explicit centred span length in pixels. On a band axis it centres in the band; when the span axis also has a channel (e.g. scatter `x`+`y`), it centres on that channel’s encoded position so a short tick sits on the datum. |
| `edits` | `Edit[]` | | Mark-level edits; per-channel edits live in the channels map. |
| `stroke, strokeWidth, …` | `style` | `stroke:'steelblue'` | Style shorthands / channels. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x` | `band \| linear` | Category (band) or value (linear), per orientation. |
| `y` | `band \| linear` | The other axis; the value axis carries `edit: move()` to drag the tick. |
| `stroke, strokeWidth, opacity` | `const \| field` | Standard style surface. |
Returns / emits: A **mark** emitting one `line` per datum (a bar with zero thickness).
## A value marker across bands
`tickY` marks a `y` value across each category's band. It takes the same channels and edits as a `bar`, and drags the same way.
### Example: Ticks over a band axis
One tick per category, spanning the band at its y value.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
tickY({
stroke: "#50AEB7", strokeWidth: 3,
channels: {
x: { field: "x" },
y: { field: "y" },
},
}),
],
});
mount(chart.dom());
```
### Example: Drag a value (ticks)
Same y edit as a bar; pick: "nearest" grabs the tick from anywhere in its column.
Try: **Drag** a tick up or down — from anywhere in its column.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
tickY({
stroke: "#50AEB7", strokeWidth: 3,
channels: {
x: { field: "x" },
y: { field: "y",
edit: move({ pick: "nearest" }) },
},
}),
],
});
mount(chart.dom());
```
## A rug / strip plot
With no band on the other axis, a tick spans the full extent, giving a strip of marks at each row's position. `inset` trims the ends so the strip sits clear of the frame.
### Example: tickX — a distribution strip
Values along x, each drawn as a vertical mark spanning y. inset shortens them.
```javascript
const chart = Elicit({
width: 400, height: 200,
margins: { top: 16, right: 16, bottom: 28, left: 16 },
data: [
{ v: 12 }, { v: 18 }, { v: 21 }, { v: 34 }, { v: 39 },
{ v: 41 }, { v: 55 }, { v: 58 }, { v: 63 }, { v: 71 }, { v: 84 },
],
schema: {
v: { type: "quantitative", domain: [0, 100] },
},
marks: [
tickX({
stroke: "#1B3F60", strokeWidth: 2, inset: 10,
channels: {
x: { field: "v" },
},
}),
],
});
mount(chart.dom());
```
---
# Point
> Source: https://elicitjs.github.io/marks/point/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`point` draws one dot per row at `x`/`y`, for scatter plots and creatable points. `size`, `fill`, `stroke` and `angle` are channels like any other. The default shape is a circle; `shape: 'square'` draws a centred square of side `2 × size` that rotates about its centre.
## API reference
### `point(options)`
Import `plot` from `elicitjs`. A circle or square per datum; every channel — positional or not — resolves through the global scales.
JSON keyword: `plot.point`
```ts
point({ channels, shape, edits, id }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | Channel map — see **Channels**. |
| `image` | `string \| (d) => string \| ChannelSpec` | | The shape's background image: a URL painted inside each shape in place of the fill. Takes `fit`, `position` and `repeat` as channel params, as in CSS. See [Image](https://elicitjs.github.io/marks/image.md#settings). |
| `shape` | `'circle' \| 'square'` | `'circle'` | Glyph shape. A square is a centred rect with side `2 × size`, so an `angle` channel can spin it. |
| `edits` | `Edit[]` | | Mark-level edits; per-channel edits live in the channels map. |
| `tip` | `true \| string[] \| (d) => string` | | A tooltip of the row under the pointer, as on every mark: all columns, the listed ones, or your own text. See [Tooltips](https://elicitjs.github.io/guides.md#tips). |
| `motion` | `boolean` | `false` | Eased drawing, as on every mark. When the rows change, the mark's shapes travel to their new places. A grabbed row is drawn at the pointer along a channel whose scale is a band or a point scale, and eases into its slot on release. The data is never eased. See [Ranking](https://elicitjs.github.io/widgets.md#ranking). |
| `fill, stroke, size, angle, …` | `style` | `fill: 'steelblue'` | Shorthands / channels. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x` | `linear \| band` | Horizontal position; omitted parks the dot at the centre of x. |
| `y` | `linear \| band` | Vertical position; omitted parks the dot at the centre of y. |
| `size` | `linear` | The circle radius / half square side (default 5). Pair with `edit: resize()` to drag the radius. |
| `angle` | `linear` | Orientation in math degrees (0° = +x, CCW). Pair with `edit: rotate({ pivot: 'mark', fold: false, pick: 'direct' })`. Circles are rotation-invariant; squares and symbols rotate. |
| `fill` | `const \| field` | Fill; a field tints through the ordinal palette. |
| `stroke, strokeWidth, opacity` | `const \| field` | Standard style surface. |
| `symbol` | `const \| field` | Draws the point as a glyph (emoji or unicode shape), drawn as text and sized by `size`. An SVG path warns; use [`plot.shape()`](https://elicitjs.github.io/marks/shape.md) for path shapes. |
Returns / emits: A **mark** emitting one `circle` or `rect` per datum.
## Channels: size, fill, colour
A numeric field can drive the radius (`size`) and a continuous colour ramp at once. A categorical field drives the ordinal palette. Constants and fields mix on the same mark.
### Example: Sequential fill + size from a number
A numeric field drives both the continuous colour ramp and the radius.
```javascript
const chart = Elicit({
width: 340, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 34 },
data: [
{ h: 150, weight: 48 }, { h: 160, weight: 57 }, { h: 170, weight: 66 },
{ h: 180, weight: 78 }, { h: 190, weight: 92 }, { h: 165, weight: 61 },
],
schema: {
h: { type: "quantitative", domain: [140, 200] },
weight: { type: "quantitative", domain: [40, 100] },
},
marks: [
point({
channels: {
x: { field: "h" },
y: { field: "weight" },
fill: { field: "weight" }, // number -> sequential ramp
size: { field: "weight" }, // number -> radius
},
}),
],
});
mount(chart.dom());
```
### Example: Constant style shorthands
Outlined, semi-transparent dots via top-level stroke / strokeWidth / opacity.
```javascript
const chart = Elicit({
width: 340, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 12, y: 40 }, { x: 30, y: 22 }, { x: 48, y: 55 },
{ x: 66, y: 33 }, { x: 80, y: 68 }, { x: 22, y: 60 },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 80] },
},
marks: [
point({
fill: "#F2B94B", opacity: 0.85,
size: 9,
channels: {
x: { field: "x" },
y: { field: "y" },
},
}),
],
});
mount(chart.dom());
```
A `symbol` channel draws each point as a glyph, an emoji or a unicode shape, sized by `size`; see [Symbol](https://elicitjs.github.io/marks/symbol.md). `point` draws a symbol as text, so an SVG path string as a symbol logs a warning. For path shapes, use [`plot.shape()`](https://elicitjs.github.io/marks/shape.md).
`tip: true` shows a tooltip of the row under the pointer, on `point` and every other mark. Drags work through it. See [Tooltips](https://elicitjs.github.io/guides.md#tips).
## Heatmap of circles / squares
Put a category on both `x` and `y` and each dot centres at that intersection, giving a grid heatmap. `fill` encodes the value as colour and `size` as radius, so magnitude reads twice. `shape: 'square'` swaps circles for centred squares. Use `rect` for filled cells that tile the plane. The `size` scale is invertible, so `resize()` on it drags a dot's radius back to a value, and its colour re-derives from the same field.
### Example: Sized, coloured grid
Category on x and y; size and fill both ramp off the value field.
Try: **Drag** a dot to resize it and set its value.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 16, right: 84, bottom: 30, left: 56 },
data: [
{ day: "Mon", slot: "AM", load: 4 }, { day: "Mon", slot: "PM", load: 9 }, { day: "Mon", slot: "Eve", load: 6 },
{ day: "Tue", slot: "AM", load: 7 }, { day: "Tue", slot: "PM", load: 14 }, { day: "Tue", slot: "Eve", load: 8 },
{ day: "Wed", slot: "AM", load: 12 }, { day: "Wed", slot: "PM", load: 20 }, { day: "Wed", slot: "Eve", load: 11 },
{ day: "Thu", slot: "AM", load: 6 }, { day: "Thu", slot: "PM", load: 16 }, { day: "Thu", slot: "Eve", load: 10 },
],
schema: {
day: { type: "categorical", domain: ["Mon", "Tue", "Wed", "Thu"] },
slot: { type: "categorical", domain: ["AM", "PM", "Eve"] },
load: { type: "quantitative", domain: [0, 20] },
},
marks: [
// A category on both axes centres one dot per (day, slot). `size` ramps the
// radius and `fill` the colour off the same field, so magnitude reads twice.
// `size` is invertible, so resize() drags a dot's radius back to a value —
// its colour re-derives from the same field on the next render.
point({
channels: {
x: { field: "day" },
y: { field: "slot" },
size: { field: "load", edit: edit.resize() },
fill: { field: "load" },
},
}),
legendColor({ anchor: "right", title: "load" }),
],
});
mount(chart.dom());
```
## Moving points in 2D
When both `x` and `y` carry a drag, the pointer inverts through both positional scales.
### Example: 2D move (scatter)
Both x and y carry edit: move(), so a dot moves anywhere.
Try: **Drag** a dot anywhere.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: 20, y: 30 }, { x: 50, y: 62 }, { x: 78, y: 40 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#50AEB7", opacity: 0.85,
size: 9,
channels: {
x: { field: "x" },
y: { field: "y" },
},
edits: [ move({ channels: ["x", "y"] }) ],
}),
],
});
mount(chart.dom());
```
## Adding points
`create()` on a `point` inverts the pointer through the `x` and `y` scales to mint a datum. A move-drag is on the same mark here, so the creator uses `gesture: "dblclick"` to keep the two gestures apart. See [Create · Remove · Anchors](https://elicitjs.github.io/editing/existence.md) for the full model and which marks can create.
### Example: Double-click to add a point
create({ gesture: "dblclick" }) mints a datum at the pointer; group comes from the schema default; count({ max }) caps the dataset.
Try: **Double-click** empty space to add a point · **drag** to move it.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 25, y: 40, group: "a" },
{ x: 60, y: 70, group: "a" },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
group: { type: "categorical", default: "a" },
},
constraints: [ count({ max: 10 }) ],
marks: [
point({
fill: "#1B3F60",
size: 8,
channels: {
x: { field: "x", edit: move() },
y: { field: "y", edit: move() },
},
// dblclick, not click: a plain click would race the move-drag on the same
// mark. The pointer inverts through x and y to mint the datum; group comes
// from the schema default. count caps the dataset.
edits: [ create({ gesture: "dblclick" }) ],
}),
],
});
mount(chart.dom());
```
## Rotating squares and ticks
An `angle` channel orients a mark about its centre. Degrees follow the math convention (0° = +x, counter-clockwise). `rotate()` inverts the pointer through the same scale. Squares use `point({ shape: 'square' })`. Short `tickX` / `tickY` segments (with `length`) rotate the same way, as directional markers on a scatter.
Picking follows the rotation: a proximity pick measures a tick where it is drawn, and hover and selection outlines turn with the mark.
### Example: Scatter of rotatable squares
shape: 'square' plus angle with rotate({ pivot: 'mark', fold: false, pick: 'direct' }).
Try: **Drag** a square to spin it.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 20, y: 30, theta: -20 },
{ x: 50, y: 62, theta: 35 },
{ x: 78, y: 40, theta: 70 },
{ x: 35, y: 75, theta: -55 },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
theta: { type: "quantitative", domain: [-180, 180] },
},
marks: [
point({
shape: "square",
fill: "#50AEB7", size: 10,
channels: {
x: { field: "x" },
y: { field: "y" },
angle: {
field: "theta",
scale: { range: [-180, 180] },
edit: rotate({ pivot: "mark", fold: false, pick: "direct" }),
},
},
}),
],
});
mount(chart.dom());
```
### Example: Scatter of rotatable ticks
tickX with length centres a short vertical segment on (x, y); angle rotates it about that midpoint — a lean / direction marker.
Try: **Drag** a tick to spin it.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 20, y: 30, theta: -20 },
{ x: 50, y: 62, theta: 35 },
{ x: 78, y: 40, theta: 70 },
{ x: 35, y: 75, theta: -55 },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
theta: { type: "quantitative", domain: [-180, 180] },
},
marks: [
tickX({
length: 36,
stroke: "#50AEB7",
strokeWidth: 4,
channels: {
x: { field: "x" },
y: { field: "y" },
angle: {
field: "theta",
scale: { range: [-180, 180] },
edit: rotate({ pivot: "mark", fold: false, pick: "direct" }),
},
},
}),
],
});
mount(chart.dom());
```
### Example: Grabbing a spun tick from nearby
pick: 'nearest' with a 12px threshold. The catchment tracks each tick's drawn arm, so the flat one is grabbable along the horizontal.
Try: **Drag** from just off either tick — including off the END of the flat one, well away from the vertical it would sit on at 0°.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 22, y: 32, theta: 90 },
{ x: 74, y: 68, theta: 20 },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
theta: { type: "quantitative", domain: [-180, 180] },
},
marks: [
tickX({
length: 36,
stroke: "#50AEB7",
strokeWidth: 4,
channels: {
x: { field: "x" },
// A 4px tick is a small target, so pick the nearest one within 12px
// instead of demanding a hit. The catchment is measured against the tick
// as DRAWN — along the arm it currently points down, not the vertical it
// would occupy at 0° — so the left tick (spun flat) is grabbable off
// either END, nowhere near the upright segment it started as.
y: {
field: "y",
edit: move({
channels: ["y"],
pick: "nearest",
threshold: 12,
guide: { catchment: true },
}),
},
angle: { field: "theta", scale: { range: [-180, 180] } },
},
}),
],
});
mount(chart.dom());
```
---
# Line
> Source: https://elicitjs.github.io/marks/line/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`line` draws a connected path through ordered points, with a draggable handle on each point once the line carries an edit. One mark covers a you-draw-it curve, a multi-series chart and a connected scatter: `series` groups rows into lines, `order` or `connect` orders them, and `edit.line.anchor` / `newSeries` / `draw` create them. `lineY`/`lineX` fix the value axis; `path` defaults to `connect: "sequence"`.
## API reference
### `line(options) · lineY(options) · lineX(options) · path(options) · polygon(options)`
Import `plot` from `elicitjs`. One non-interactive connector path per series, drawn under one draggable `circle` handle per datum. `lineY`/`lineX` pin the value axis; `path` defaults to `connect: "sequence"`.
JSON keyword: `plot.line`, `plot.lineY`, `plot.lineX`, `plot.path`, `plot.polygon`
```ts
line({ channels, orientation, curve, connect, handles, handleSize, handleColor, edits, id }) → Mark
lineY(options) → Mark // value on y (time series)
path(options) → Mark // connect: "sequence"
polygon(options) → Mark // path with closed: true
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | Channel map — see **Channels**. |
| `orientation` | `'vertical' \| 'horizontal'` | `auto` | Which axis the value runs along (`'vertical'` = y). Inferred from a band scale or the lone bound channel; `lineY / lineX` pin it. |
| `channels.series` | `channel` | `auto` | The column grouping points into lines. A **channel**, because it names a column. Defaults to `fill`’s field (then `stroke`’s), so a coloured chart auto-groups. |
| `channels.order` | `channel` | | The column each series is sorted by. Also a channel — a route’s `stop` number orders the line and encodes nothing, so there is no other channel to point at. |
| `connect` | `'domain' \| 'sequence'` | `'domain'` | How points connect when no order channel is given: sorted by the domain axis, or as drawn. The mode only — it names no column. |
| `closed` | `boolean` | `false (true on polygon)` | Join each line’s last point to its first and fill the inside: the `fill` you give, or a tint of the stroke. `edit.line.moveSeries()` drags the region by its inside. |
| `curve` | `string` | `'linear'` | Interpolation between handles (e.g. `"catmullRom"`, `"step"`). |
| `handles` | `boolean \| 'hit'` | `true with an edit` | `true` draws a grabbable circle per datum. `'hit'` keeps the grab target but draws nothing. `false` is neither drawn nor grabbable, so a sweep or nearest pick has nothing to target. The default is `true` when the mark carries an edit and `false` otherwise. |
| `handleSize` | `number` | `5` | Pixel radius of each handle. |
| `handleColor` | `string` | `theme` | Handle fill. Defaults to the series’ stroke, so each handle matches its line; the ring is the theme’s `handleStroke`. |
| `edits, id` | | | As on every mark. Line authoring edits live under `edit.line.*`. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x` | `linear \| band \| time` | Domain or value axis (per variant / inference). |
| `y` | `linear \| band \| time` | The other axis; the value axis carries the handle edit. |
| `stroke` | `const \| field` | Line colour; a field here also becomes the default `series` grouping. |
| `strokeWidth, opacity` | `const \| field` | Standard style surface for the connector + handles. |
| `strokeDash` | `const \| field` | Dash pattern. A constant is an SVG dash array (`'4 2'`); a field maps each category onto a dash vocabulary through an ordinal scale. Takes `legend: true`. |
Returns / emits: A **mark** with `supportsSeries: true`. Emits one `path` per series (`pointerEvents:"none"`) plus one indexed `circle` handle per datum, each tagged with its `series`.
## A line & its curve
`lineY` draws a value on `y` over a domain on `x` (the usual time series). `curve` sets the interpolation between handles.
### Example: curve: "catmullRom"
A smooth line through the points. Try "linear" or "step" for other shapes.
```javascript
const chart = Elicit({
width: 400, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 0, y: 40 }, { x: 1, y: 62 }, { x: 2, y: 48 },
{ x: 3, y: 78 }, { x: 4, y: 60 }, { x: 5, y: 84 },
],
schema: {
s: { type: "categorical" }, // the series key; declared so create() mints it
x: { type: "quantitative", domain: [0, 5] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
lineY({
stroke: "#50AEB7", strokeWidth: 3, curve: "catmullRom",
channels: {
x: { field: "x" },
y: { field: "y" },
},
}),
],
});
mount(chart.dom());
```
## Missing values
A row whose value is `null`, `undefined` or `NaN` breaks the line there. The segments on either side draw on their own, and the missing row gets no handle.
### Example: A gap where a value is missing
The row at x = 3 has y: null, so the line stops and starts again.
Try: **Drag** a handle on either side of the gap.
```javascript
const chart = Elicit({
width: 400, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 0, y: 40 }, { x: 1, y: 52 }, { x: 2, y: 48 },
{ x: 3, y: null }, // no value: the line breaks here
{ x: 4, y: 66 }, { x: 5, y: 60 }, { x: 6, y: 74 },
],
schema: {
x: { type: "quantitative", domain: [0, 6] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
lineY({
stroke: "#50AEB7", strokeWidth: 3,
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Dashed lines
`strokeDash` sets the dash pattern. A constant is an SVG dash array (`strokeDash: '4 2'`). A field maps each category onto a dash pattern (solid, dashed, dotted, dash-dot, long dash), as `stroke` maps one onto a colour. Add `legend: true` to the channel for a key of dashed segments.
### Example: Observed and forecast
strokeDash: { field: "kind" } draws the forecast dashed; series: { field: "kind" } splits the two lines.
Try: **Drag** a forecast point.
```javascript
const chart = Elicit({
width: 420, height: 250,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
axes: { x: { tickFormat: "d" } },
data: [
{ year: 2020, v: 42, kind: "observed" }, { year: 2021, v: 48, kind: "observed" },
{ year: 2022, v: 45, kind: "observed" }, { year: 2023, v: 55, kind: "observed" },
{ year: 2023, v: 55, kind: "forecast" }, { year: 2024, v: 60, kind: "forecast" },
{ year: 2025, v: 64, kind: "forecast" }, { year: 2026, v: 70, kind: "forecast" },
],
schema: {
year: { type: "quantitative", domain: [2020, 2026] },
v: { type: "quantitative", domain: [0, 100] },
kind: { type: "categorical", domain: ["observed", "forecast"] },
},
marks: [
lineY({
stroke: "#1B3F60", strokeWidth: 2.5,
channels: {
x: { field: "year" },
y: { field: "v", edit: move() },
series: { field: "kind" },
// A field picks a dash pattern per category: solid, then dashed.
strokeDash: { field: "kind" },
},
}),
],
});
mount(chart.dom());
```
Rows group into lines by `series`. Without it, they group by the field on `fill`, `stroke` or `strokeDash`, so a `strokeDash` field alone also splits the lines.
## You-draw-it (sweep)
Put `edit: move({ pick: "sweep" })` on the value channel for a you-draw-it line. Press and sweep horizontally to paint each point's `y` as the pointer crosses its column. The `x` positions stay fixed.
### Example: Sweep to draw the curve
The value channel carries a sweep; guide: true shows the paint guide.
Try: **Sweep** left-to-right across the chart — or drag a single handle.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 0, y: 50 }, { x: 1, y: 50 }, { x: 2, y: 50 }, { x: 3, y: 50 },
{ x: 4, y: 50 }, { x: 5, y: 50 }, { x: 6, y: 50 }, { x: 7, y: 50 },
],
schema: {
s: { type: "categorical" }, // the series key; declared so create() mints it
x: { type: "quantitative", domain: [0, 7] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
lineY({
stroke: "#50AEB7", strokeWidth: 3, curve: "catmullRom",
channels: {
x: { field: "x" },
y: { field: "y",
edit: move({ pick: "sweep", guide: true }) },
},
}),
],
});
mount(chart.dom());
```
## Hiding the handles
By default, handles draw only where an edit can move the row. A line with no edit has none, and neither does a `lock`ed or `context` row, or a line whose edits wait for a later `stage`. `handles: true` draws them on every row, with or without an edit. `handles: 'hit'` keeps them grabbable but invisible, so a sweep or nearest pick still finds the line. `handles: false` removes them entirely; a proximity edit then has nothing to target and logs a warning. `handleSize` sizes them when shown.
### Example: A clean line, still sweepable
handles: 'hit' hides the dots; the sweep edit still works.
Try: **Sweep** across — no handles, but the line still responds.
```javascript
const chart = Elicit({
width: 400, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 0, y: 50 }, { x: 1, y: 50 }, { x: 2, y: 50 }, { x: 3, y: 50 },
{ x: 4, y: 50 }, { x: 5, y: 50 }, { x: 6, y: 50 }, { x: 7, y: 50 },
],
schema: {
s: { type: "categorical" }, // the series key; declared so create() mints it
x: { type: "quantitative", domain: [0, 7] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
lineY({
stroke: "#8A78C0", strokeWidth: 3, curve: "catmullRom",
handles: 'hit', // hide the anchor dots (still editable)
channels: {
x: { field: "x" },
y: { field: "y",
edit: move({ pick: "sweep", guide: true }) },
},
}),
],
});
mount(chart.dom());
```
## Multiple lines (series)
The `series` channel groups points into separate lines, so one mark holds many series. Without `series`, the field on `fill`, `stroke` or `strokeDash` groups them. A `stroke` field both groups and colours the lines from the ordinal palette. A sweep locks onto the nearest line when the drag starts and paints only that one.
### Example: Two series, swept independently
stroke: { field: "g" } both groups and colours the lines.
Try: **Sweep** over one line to reshape it; the other stays put.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ g: "plan", x: 0, y: 30 }, { g: "plan", x: 1, y: 45 }, { g: "plan", x: 2, y: 40 }, { g: "plan", x: 3, y: 60 },
{ g: "actual", x: 0, y: 70 }, { g: "actual", x: 1, y: 62 }, { g: "actual", x: 2, y: 75 }, { g: "actual", x: 3, y: 68 },
],
schema: {
s: { type: "categorical" }, // the series key; declared so create() mints it
x: { type: "quantitative", domain: [0, 3] },
y: { type: "quantitative", domain: [0, 100] },
g: { type: "categorical" }, // a group identifier, not an ordered scale
},
marks: [
lineY({
strokeWidth: 3, curve: "catmullRom",
channels: {
x: { field: "x" },
y: { field: "y",
edit: move({ pick: "sweep", guide: true }) },
stroke: { field: "g" }, // groups AND colours the lines
},
}),
],
});
mount(chart.dom());
```
## Connected scatter (connect: sequence)
With `connect: "sequence"`, points connect in row order instead of domain order, giving a connected scatter or a free 2D path. Both axes carry a drag here, so each point moves in 2D and the links follow. `edit.line.anchor()` appends a point wherever you click, extending the one path in click order.
### Example: A 2D path you can reshape
path defaults to connect: "sequence"; a 2D drag moves points, anchor extends the one path in click order.
Try: **Drag** a point anywhere, or **click** empty space to add the next anchor.
```javascript
const chart = Elicit({
width: 420, height: 300,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ s: 0, x: 20, y: 30 }, { s: 0, x: 45, y: 70 },
{ s: 0, x: 70, y: 40 }, { s: 0, x: 85, y: 80 },
],
schema: {
s: { type: "categorical" }, // the series key; declared so create() mints it
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
path({
stroke: "#1B3F60", strokeWidth: 3,
channels: {
series: { field: "s" },
x: { field: "x" },
y: { field: "y" },
},
edits: [
move({ channels: ["x", "y"], pick: "nearest", threshold: 40 }),
edit.line.anchor({ into: "nearest", channels: ["x", "y"], series: "s", threshold: 80 }),
],
}),
],
});
mount(chart.dom());
```
## Closed regions (polygon)
`closed: true` joins a path's last point to its first and fills the inside. `polygon` is `path` with `closed: true`. Each vertex is a row, so `move` drags one by its handle and `remove` deletes one. `edit.line.moveSeries()` drags the whole region by its inside, and moves an open line when you press on it. The fill is the `fill` you give, or a tint of the stroke. The `linear`, `catmullRom`, `basis` and `cardinal` curves close; any other is drawn with straight sides.
### Example: A region you can reshape
Five rows, one per vertex. The region stays inside the schema's x and y domains.
Try: **Drag** a vertex to reshape · **drag** the inside to move the region.
```javascript
const chart = Elicit({
width: 420, height: 300,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
// One row per vertex, joined in row order.
data: [
{ x: 25, y: 30 }, { x: 70, y: 22 }, { x: 82, y: 62 },
{ x: 48, y: 80 }, { x: 18, y: 60 },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
polygon({
stroke: "#50AEB7", strokeWidth: 2,
channels: {
x: { field: "x" },
y: { field: "y" },
},
edits: [
move({ channels: ["x", "y"] }), // a vertex, by its handle
edit.line.moveSeries(), // the whole region, by its inside
],
}),
],
});
mount(chart.dom());
```
## Draw from scratch (samples)
`newSeries` seeds a whole line at once, flat at the clicked value. It places one anchor per sampled domain position: the scale's ticks by default, or a count, an explicit list, or a time interval. Double-click empty space to drop a fresh line, then sweep it.
### Example: Double-click to seed, then sweep
edit.line.newSeries({ samples: 6 }) drops six evenly-spaced anchors at the click’s value.
Try: **Double-click** to drop a line, then **sweep** to shape it.
```javascript
const chart = Elicit({
width: 420, height: 300,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [],
schema: {
s: { type: "categorical" }, // the series key; declared so create() mints it
x: { type: "quantitative", domain: [0, 10] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
lineY({
stroke: "#50AEB7", strokeWidth: 3, curve: "catmullRom",
channels: {
series: { field: "s" },
x: { field: "x" },
y: { field: "y",
edit: move({ pick: "sweep", guide: true }) },
},
edits: [ edit.line.newSeries({ along: "x", value: "y", series: "s", samples: 6 }) ],
}),
],
});
mount(chart.dom());
```
## Draw it in one drag (draw)
`draw` creates lines by dragging. On a domain-ordered line, a drag in empty space draws from scratch: as the pointer crosses each sample column, it lays that point down at the pointer value, so one stroke draws the curve. A later drag within `threshold` of the drawn line reshapes it with a sweep. A drag farther away draws another line. Pass `into: "new"` to always draw a fresh line.
### Example: Draw, then reshape
edit.line.draw({ samples: 8 }) on an empty line. First drag draws all eight points; a drag over the line reshapes it, a drag in empty space starts a new one.
Try: **Press and drag** to draw · **drag over the line** to reshape · **drag elsewhere** for a new line.
```javascript
const chart = Elicit({
width: 420, height: 300,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [],
schema: {
s: { type: "categorical" }, // the series key; declared so create() mints it
x: { type: "quantitative", domain: [0, 10] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
lineY({
stroke: "#50AEB7", strokeWidth: 3, curve: "catmullRom",
channels: {
series: { field: "s" },
x: { field: "x" },
y: { field: "y" },
},
edits: [ edit.line.draw({ along: "x", value: "y", series: "s", samples: 8 }) ],
}),
],
});
mount(chart.dom());
```
---
# Area
> Source: https://elicitjs.github.io/marks/area/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`area` fills the region under a series. It groups and orders rows as [`line`](https://elicitjs.github.io/marks/line.md) does, and takes the same handles, drags and sweeps. `areaY` fills to the `y` baseline, `areaX` to the `x` baseline. Give the value axis an endpoint pair (`y1` + `y2`) and it fills between them instead, as an **uncertainty band** you edit by both edges.
## API reference
### `area(options) · areaY(options) · areaX(options)`
Import `plot` from `elicitjs`. One filled path per series, with an optional draggable handle per datum. `areaY` fills to the y baseline, `areaX` to the x baseline; bare `area` infers the value axis.
JSON keyword: `plot.area`, `plot.areaY`, `plot.areaX`
```ts
area({ channels, orientation, curve, connect, handles, handleSize, handleColor, edits, id }) → Mark
areaY(options) → Mark // value on y
areaX(options) → Mark // value on x
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | Channel map — see **Channels**. |
| `image` | `string \| (d) => string \| ChannelSpec` | | The shape's background image: a URL painted inside each shape in place of the fill. Takes `fit`, `position` and `repeat` as channel params, as in CSS. See [Image](https://elicitjs.github.io/marks/image.md#settings). |
| `orientation` | `'vertical' \| 'horizontal'` | `auto` | Which axis the value runs along (`'vertical'` = y). Inferred from a band scale, an endpoint pair, or the lone bound channel; `areaY / areaX` pin it. |
| `channels.series` | `channel` | `auto` | The column grouping points into separate areas. Defaults to `fill`’s field, then `stroke`’s. |
| `channels.order` | `channel` | | The column each series is sorted by, when array order and the domain axis are both wrong. |
| `connect` | `'domain' \| 'sequence'` | `'domain'` | How points join when no order channel is given: sorted by the domain axis, or as drawn. |
| `curve` | `string` | `'linear'` | Interpolation between handles (e.g. `"catmullRom"`, `"step"`). |
| `handles` | `boolean \| 'hit'` | `true with an edit` | `true` draws a grabbable circle per datum. `'hit'` keeps the grab target but draws nothing. `false` is neither drawn nor grabbable, so a sweep or nearest pick has nothing to target. The default is `true` when the mark carries an edit and `false` otherwise. |
| `handleSize` | `number` | `5` | Pixel radius of each handle. |
| `handleColor` | `string` | `theme` | Handle fill. Defaults to the area’s own colour (its stroke, else its fill); the ring is the theme’s `handleStroke`. |
| `gradient` | `{ stops, direction }` | | A linear-gradient fill over the area’s own box, in place of a flat `fill`. `stops` is a list of `[offset, colour]` with offsets 0–1; `direction` is `'vertical'` (default, bottom to top) or `'horizontal'` (left to right). |
| `edits, id` | | | As on every mark. Area authoring edits live under `edit.line.*`, which it shares with `line`. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x / y` | `linear \| point \| time` | Domain and value axes (same as line). |
| `y1 / y2 · x1 / x2` | `linear` | An endpoint **pair** on the value axis: fill between the two fields instead of down to the baseline (a confidence band, a fan chart). They share the value axis’s scale, so they resolve exactly like `y`, and declaring a pair picks the value axis on its own. With one end given, the other is the baseline. Handles appear on each declared edge. Same span/baseline split `bar` and `rect` make, spelled the same way. |
| `fill / stroke` | `const \| field` | Area fill (default fillOpacity 0.35) and outline. A field here also becomes the default series grouping. |
| `strokeDash` | `const \| field` | Outline dash pattern: an SVG dash array (`'4 2'`), or a field mapped onto a dash vocabulary. Takes `legend: true`. |
Returns / emits: A mark emitting one filled path per series plus optional handle circles.
## Filled series
Drag a handle to reshape the curve. Each handle takes the area's colour. By default, handles draw only when the area carries an edit; `handles: true` draws them without one.
### Example: Editable area
areaY with drag on y handles.
Try: **Drag** a handle to reshape the area.
```javascript
const chart = Elicit({
width: 400, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ t: 1, n: 20 }, { t: 2, n: 45 }, { t: 3, n: 35 },
{ t: 4, n: 60 }, { t: 5, n: 50 },
],
schema: {
t: { type: "quantitative", domain: [1, 5] },
n: { type: "quantitative", domain: [0, 100] },
},
marks: [
areaY({
fill: "#50AEB7",
channels: {
x: { field: "t" },
y: { field: "n", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Invisible handles
`handles: 'hit'` keeps the handles grabbable but invisible, as on `line` and `arc`. `handles: false` removes them entirely; a sweep or nearest pick then has nothing to target and logs a warning.
### Example: handles: 'hit'
Same area as above; the handles are invisible but still draggable.
Try: **Drag** along the upper edge where a handle would sit.
```javascript
// handles: 'hit' — invisible but grabbable (shared contract with line/arc).
const chart = Elicit({
width: 400, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ t: 1, n: 20 }, { t: 2, n: 45 }, { t: 3, n: 35 },
{ t: 4, n: 60 }, { t: 5, n: 50 },
],
schema: {
t: { type: "quantitative", domain: [1, 5] },
n: { type: "quantitative", domain: [0, 100] },
},
marks: [
areaY({
handles: 'hit',
fill: "#50AEB7",
channels: {
x: { field: "t" },
y: { field: "n", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Gradient fill
`gradient: { stops, direction }` fills the area with a linear gradient instead of a flat `fill`. Each stop is `[offset, colour]`, with `offset` from 0 to 1 across the area's own box. `direction: 'vertical'` (the default) runs from bottom (0) to top (1); `'horizontal'` runs left to right. `bar` and `rect` take the same option.
### Example: A gradient fill
gradient: { stops: [[0, pale], [1, blue]] } fades the area toward its baseline.
Try: **Drag** a handle — the gradient stretches over the new shape.
```javascript
const chart = Elicit({
width: 400, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ t: 1, n: 20 }, { t: 2, n: 45 }, { t: 3, n: 35 },
{ t: 4, n: 60 }, { t: 5, n: 50 },
],
schema: {
t: { type: "quantitative", domain: [1, 5] },
n: { type: "quantitative", domain: [0, 100] },
},
marks: [
areaY({
fillOpacity: 0.9,
// Offset 0 is the bottom of the area's box, 1 the top.
gradient: { stops: [[0, "#EDF7F8"], [1, "#50AEB7"]], direction: "vertical" },
channels: {
x: { field: "t" },
y: { field: "n", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Uncertainty band
Give the value axis an endpoint pair and the area fills between them, as in a confidence interval or a fan chart. Both edges get handles, so you set the interval by dragging its ends. Add the [ordering](https://elicitjs.github.io/constraints.md#ordering) constraint to keep the band the right way up: drag the low edge above the high one and the high edge moves with it, since the edge you grabbed is the one you meant.
### Example: An editable confidence band
areaY with a y1/y2 pair; ordering keeps lo ≤ hi.
Try: **Drag** either edge — push the low edge past the high one and the band moves rather than turning inside-out.
```javascript
const chart = Elicit({
width: 400, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ year: 2025, lo: 20, hi: 45 }, { year: 2026, lo: 25, hi: 60 },
{ year: 2027, lo: 22, hi: 72 }, { year: 2028, lo: 18, hi: 85 },
],
schema: {
year: { type: "quantitative", domain: [2025, 2028] },
lo: { type: "quantitative", domain: [0, 100] },
hi: { type: "quantitative", domain: [0, 100] },
},
// A dataset invariant: it holds whichever edge you grab.
constraints: [ ordering({ field: ["lo", "hi"] }) ],
marks: [
areaY({
fill: "#50AEB7",
channels: {
x: { field: "year" },
// An endpoint PAIR instead of a single value: fill BETWEEN the two
// fields rather than down to the baseline. Declaring the pair is what
// picks the value axis, and both edges get handles.
y1: { field: "lo", edit: move({ channels: ["y1"] }) },
y2: { field: "hi", edit: move({ channels: ["y2"] }) },
},
}),
],
});
mount(chart.dom());
```
A row whose value is `null`, `undefined` or `NaN` breaks the area or band there, as on a [line](https://elicitjs.github.io/marks/line.md#gaps), and has no handle. To repaint one edge in a single drag, put `edit.line.sweep()` on `y1` and `y2`; see [Sweeping a band](https://elicitjs.github.io/editing/sweep.md#band).
---
# Text
> Source: https://elicitjs.github.io/marks/text/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`text` draws one **label** per row at (`x`, `y`). `format` sets how a number displays, as a d3-format string or a function, without changing the data. It takes the universal edits (`move()`, `cycle()`, `rotate()`), and `editText()` lets you retype a label.
## API reference
### `text(options) · textX(options) · textY(options)`
Import `plot` from `elicitjs`. `text` positions from x AND y; `textX` / `textY` are 1-D labels along one axis (the other parks at centre).
JSON keyword: `plot.text`, `plot.textX`, `plot.textY`
```ts
text({ channels, orientation, format, wrap, lineHeight, edits, id }) → Mark
textX(options) → Mark // value on x
textY(options) → Mark // value on y
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | Channel map. See **Channels**. |
| `orientation` | `'vertical' \| 'horizontal'` | | Places the label along one axis and parks it at the plot centre on the other (`'vertical'` = y). `textY / textX` set it. Bare `text` places each axis through its own channel, and at the centre where a channel is unbound. |
| `text, fontSize, textAnchor, lineAnchor, dx, dy` | `shorthand` | | Constant shorthands, e.g. `text({ dy: -8, lineAnchor: "bottom" })`. |
| `format` | `string \| fn` | `String` | Display formatter: a d3-format string (e.g. `".1f"`) or `(v) => string`. Display-only — the field stays raw. Helpers live on `format` (`format.number`, `format.percent`, …). |
| `wrap` | `number \| true \| fn` | | Wrap the label at this pixel width. `true` wraps at the plot width. A function `(d, i, data) => number` gives a per-datum width, for a label that has to fit the box it sits in. |
| `lineHeight` | `number` | `1.35 × fontSize` | Pixel step between wrapped lines. |
| `edits` | `Edit[]` | | Mark-level edits; per-channel edits live in `channels[ch].edit`. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x / y` | `linear \| band` | Position. A missing axis parks the label at that dimension’s centre. |
| `text` | `field \| const` | The value to draw (raw — no scale; passed through `format`). |
| `fontSize` | `field \| const` | Size in px, raw. |
| `textAnchor` | `field \| const` | Horizontal anchor: `start`·`middle`·`end`. |
| `lineAnchor` | `field \| const` | Vertical anchor: `top`·`middle`·`bottom` (maps to SVG `dominant-baseline`). |
| `dx / dy` | `field \| const` | Pixel offsets from the encoded (x, y). Visual-only — drag still inverts the pointer through the scale. |
| `angle` | `field \| const` | Rotation in degrees (scaled when a scale is declared, so `rotate()` is an exact inverse). |
| `fill, opacity` | `const \| field` | Standard style surface. |
Returns / emits: A **mark** emitting one `text` per datum.
## Labels from data
`x`/`y` position the label, and `text` is its string. `text`, `fontSize`, `textAnchor`, `lineAnchor`, `dx` and `dy` take a field or a constant and are used as-is. `angle` is in degrees. Offset and anchor keep a label clear of the mark it labels.
### Example: A labelled scatter
point for the dots, text for the labels above them — dy + lineAnchor park the string above the point.
```javascript
const chart = Elicit({
width: 360, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ gdp: 3, life: 6, name: "Ada" },
{ gdp: 6, life: 8, name: "Grace" },
{ gdp: 8, life: 4, name: "Alan" },
],
schema: {
gdp: { type: "quantitative", domain: [0, 10] },
life: { type: "quantitative", domain: [0, 10] },
name: { type: "categorical", domain: ["Ada", "Grace", "Alan"] },
},
marks: [
point({ fill: "#50AEB7",
channels: { x: { field: "gdp" }, y: { field: "life" } } }),
text({ fontSize: 12, dy: -10, lineAnchor: "bottom",
channels: {
x: { field: "gdp" }, y: { field: "life" },
text: { field: "name" },
} }),
],
});
mount(chart.dom());
```
### Example: Formatted numeric labels
format is display-only (a d3-format string or a helper from format.*). The field stays the raw number, so a later drag still inverts correctly.
```javascript
const chart = Elicit({
width: 360, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ cat: "A", n: 0.42 },
{ cat: "B", n: 0.75 },
{ cat: "C", n: 0.18 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C"] },
n: { type: "quantitative", domain: [0, 1] },
},
marks: [
barY({ fill: "#1B3F60",
channels: { x: { field: "cat" }, y: { field: "n" } } }),
text({ fontSize: 12, dy: -6, lineAnchor: "bottom",
format: format.percent(".0%"),
channels: {
x: { field: "cat" }, y: { field: "n" },
text: { field: "n" },
} }),
],
});
mount(chart.dom());
```
### Example: Line chart with value labels
lineY draws the series; text sits on the same (x, y) with dy above each point.
```javascript
const chart = Elicit({
width: 400, height: 260,
margins: { top: 20, right: 16, bottom: 28, left: 34 },
data: [
{ t: 0, n: 40 }, { t: 1, n: 62 }, { t: 2, n: 48 },
{ t: 3, n: 78 }, { t: 4, n: 60 }, { t: 5, n: 84 },
],
schema: {
t: { type: "quantitative", domain: [0, 5] },
n: { type: "quantitative", domain: [0, 100] },
},
marks: [
lineY({
stroke: "#50AEB7", strokeWidth: 2.5, curve: "catmullRom",
channels: { x: { field: "t" }, y: { field: "n" } },
}),
text({
fontSize: 11, dy: -10, lineAnchor: "bottom",
fill: "#2A7880", format: ".0f",
channels: {
x: { field: "t" }, y: { field: "n" },
text: { field: "n" },
},
}),
],
});
mount(chart.dom());
```
## Editing labels
A direct-pick edit makes a label interactive. Use the universal edits to drag, rotate or cycle a label, or `editText()` to retype its content.
### Example: Drag to reposition
A mark-level move({ channels: ["x", "y"] }) moves the label and writes x and y back through the scales. Attach an edit on a channel or in edits.
Try: **Drag** a label to move it.
```javascript
const chart = Elicit({
width: 360, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ x: 3, y: 4, label: "drag me" },
{ x: 6, y: 7, label: "and me" },
],
schema: {
x: { type: "quantitative", domain: [0, 10] },
y: { type: "quantitative", domain: [0, 10] },
label: { type: "categorical", domain: ["drag me", "and me"] },
},
marks: [
text({ fontSize: 13, fill: "#2A7880",
channels: {
x: { field: "x" }, y: { field: "y" },
text: { field: "label" },
},
edits: [ move({ channels: ["x", "y"] }) ],
}),
],
});
mount(chart.dom());
```
### Example: Draggable numeric readout
text and y read the same field, and move() on y rewrites it, so the number updates as you drag. format sets how it displays.
Try: **Drag** the number up or down.
```javascript
const chart = Elicit({
width: 360, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
data: [ { cat: "A", n: 40 }, { cat: "B", n: 70 } ],
schema: {
cat: { type: "categorical", domain: ["A", "B"] },
n: { type: "quantitative", domain: [0, 100] },
},
marks: [
text({ fontSize: 16, fill: "#1B3F60", format: ".1f",
channels: {
x: { field: "cat" },
y: { field: "n", edit: move() },
text: { field: "n" },
} }),
],
});
mount(chart.dom());
```
### Example: Type to edit content
editText() wires double-click-to-retype: an inline input opens, Enter commits, Esc cancels.
Try: **Double-click** a label, type, and press Enter.
```javascript
const chart = Elicit({
width: 360, height: 220,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ x: 3, y: 5, label: "double-click" },
{ x: 7, y: 3, label: "me too" },
],
schema: {
x: { type: "quantitative", domain: [0, 10] },
y: { type: "quantitative", domain: [0, 10] },
label: { type: "categorical" },
},
marks: [
text({ fontSize: 14, fill: "#5B4A96",
channels: {
x: { field: "x" }, y: { field: "y" },
text: { field: "label", edit: editText() },
} }),
],
});
mount(chart.dom());
```
### Example: Drag and retype together
Mark-level drag plus editText on the text channel: drag repositions, double-click retypes.
Try: **Drag** to move; **double-click** to rename.
```javascript
const chart = Elicit({
width: 360, height: 220,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ x: 3, y: 5, label: "move me" },
{ x: 7, y: 3, label: "rename me" },
],
schema: {
x: { type: "quantitative", domain: [0, 10] },
y: { type: "quantitative", domain: [0, 10] },
label: { type: "categorical" },
},
marks: [
text({ fontSize: 14, fill: "#8F6511",
channels: {
x: { field: "x" }, y: { field: "y" },
text: { field: "label", edit: editText() },
},
edits: [ move({ channels: ["x", "y"] }) ],
}),
],
});
mount(chart.dom());
```
---
# Symbol & Emoji
> Source: https://elicitjs.github.io/marks/symbol/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
The `symbol` channel maps a category to a **glyph**, an emoji or a unicode shape, as `fill` maps a category to a colour. It is a channel, not a mark: `point`, `dotStack` and `waffle` draw the glyph in place of their circle or rect, and [`shape`](https://elicitjs.github.io/marks/shape.md) reads it as a named shape or SVG path. The elicited value is the category. Edit it with `cycle()` or `edit.legend.category()`.
## API reference
### `channels.symbol`
A category → glyph map through an ordinal scale. Add it to any shape mark. Give it glyphs with `scale: { range: [...] }` or a named `scale: { scheme: 'faces' }`. Non-positional and non-invertible — a drag can't set a glyph, so it's edited via cycle/legend/create.
```ts
symbol: { field, scale: { range | scheme }, edit? }
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `scale.range` | `string[]` | `unicode shapes` | The glyph palette. Defaults to ●■▲◆★… when omitted. |
| `scale.scheme` | `string` | | Named glyph set: 'faces', 'faces5', 'hearts', 'weather', 'arrows', 'shapes'. |
| `size` | `number` | `mark default` | The mark's radius still sets the glyph's px extent, so a glyph point and a circle point match. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `symbol` | `ordinal` | Field → glyph. Range is a glyph array (`scale: { range: ["😢","😐","😊"] }`) or a scheme. |
Returns / emits: Nothing on its own — it changes how a host mark draws each datum.
## Emoji points — click to cycle
Here the `y` position and the glyph both encode `mood`. A `cycle()` on the `symbol` channel advances the category on click. The face changes and the point moves to its new row, since both channels read the same field.
### Example: Mood over the week
symbol maps the ordinal mood to a face; cycle() advances it on click.
Try: **Click** a face to cycle its mood.
```javascript
const chart = Elicit({
width: 380, height: 250,
margins: { top: 16, right: 16, bottom: 30, left: 64 },
data: [
{ day: "Mon", mood: "ok" }, { day: "Tue", mood: "good" },
{ day: "Wed", mood: "bad" }, { day: "Thu", mood: "good" },
{ day: "Fri", mood: "great" },
],
schema: {
day: { type: "categorical", domain: ["Mon","Tue","Wed","Thu","Fri"] },
mood: { type: "ordinal", domain: ["bad","ok","good","great"] },
},
marks: [
point({
size: 15,
channels: {
x: { field: "day" },
y: { field: "mood" },
symbol: {
field: "mood",
scale: { range: ["😢","😐","🙂","😄"] },
edit: cycle(),
},
},
}),
],
});
mount(chart.dom());
```
## One fixed glyph — no mapping
The `symbol: '⚽'` shorthand draws one glyph on every point. It desugars to a constant channel and skips the scale, as `fill: 'red'` does. Here the elicited value is `goals`: drag a ball up or down to set that stage's total.
### Example: World Cup goals
A constant symbol: '⚽' — one glyph for every point, no scale. The elicited value is goals; drag a ball up or down to set it.
Try: **Drag** a ⚽ up or down to change that stage's goals.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 16, right: 16, bottom: 30, left: 40 },
data: [
{ stage: "Group", goals: 3 },
{ stage: "R16", goals: 2 },
{ stage: "QF", goals: 2 },
{ stage: "SF", goals: 1 },
{ stage: "Final", goals: 2 },
],
schema: {
stage: { type: "categorical", domain: ["Group","R16","QF","SF","Final"] },
goals: { type: "quantitative", domain: [0, 6] },
},
marks: [
point({
size: 15,
symbol: "⚽", // one glyph, no mapping — pure identity
channels: {
x: { field: "stage" },
y: { field: "goals", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Emoji tokens — drop and remove
A constant `symbol` shorthand makes every token the same glyph. `create` and `remove` work as on plain dots, here as a ⭐ star-rating counter.
### Example: Star tokens
dotStack of ⭐ tokens; click a slot to add, click a star to remove.
Try: **Click** a column to add a ⭐, **click** a ⭐ to remove it.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 30, left: 30 },
data: [ { rating: 3 }, { rating: 3 }, { rating: 5 }, { rating: 4 } ],
schema: { rating: { type: "ordinal", domain: [1, 2, 3, 4, 5] } },
constraints: [ count({ max: 24 }) ],
marks: [
dotStack({
symbol: "⭐", size: 12,
channels: { x: { field: "rating" } },
edits: [ create({ gesture: "click", channels: ["x"] }), remove() ],
}),
],
});
mount(chart.dom());
```
## Emoji waffle — count in glyphs
A `symbol` channel draws every waffle cell as its category's glyph, so you count a quantity in 🍎. Drag to fill. Empty cells draw faint and stay grabbable.
### Example: Fruit basket
Each category's cells render its emoji; edit.waffle.fill drags the count.
Try: **Drag** up a column to change its count.
```javascript
const chart = Elicit({
width: 380, height: 280,
margins: { top: 16, right: 16, bottom: 30, left: 30 },
data: [
{ fruit: "apples", n: 6 },
{ fruit: "bananas", n: 4 },
{ fruit: "cherries", n: 9 },
],
schema: {
fruit: { type: "categorical", domain: ["apples","bananas","cherries"] },
n: { type: "quantitative", domain: [0, 12] },
},
constraints: [ snap({ step: 1 }) ],
marks: [
waffleY({
channels: {
x: { field: "fruit" },
count: { field: "n", edit: edit.waffle.fill() },
symbol: { field: "fruit", scale: { range: ["🍎","🍌","🍒"] } },
},
}),
],
});
mount(chart.dom());
```
## A glyph legend / picker
`legendSymbol({ edit: edit.legend.category() })` draws a row of glyphs you click to set the category. It is the same [legend](https://elicitjs.github.io/marks/legend.md) as a colour legend, drawn with glyphs instead of swatches.
### Example: Pick a weather
A single-row answer whose glyph is set from the legend row.
Try: **Click** a glyph in the legend to set today's weather.
```javascript
const chart = Elicit({
width: 360, height: 240,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
data: [ { sky: "cloudy" } ],
schema: { sky: { type: "ordinal", domain: ["sunny","partly","cloudy","rain","storm"] } },
axes: false,
marks: [
point({
size: 40,
channels: {
x: { value: 60 }, y: { value: 100 },
symbol: { field: "sky", scale: { scheme: "weather" } },
},
}),
// A glyph legend that doubles as a picker: legendSymbol draws the row of
// glyphs, edit.legend.category() makes each one click-to-set the category.
legendSymbol({ anchor: "bottom", swatchSize: 22, edit: edit.legend.category() }),
],
});
mount(chart.dom());
```
---
# Shape
> Source: https://elicitjs.github.io/marks/shape/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`shape()` draws one SVG path per row, centred at its `x`/`y` — a named shape, a pictogram, any path you write. The shape comes from the `symbol` channel. `size` is the radius of the box it fits, and `angle` turns it in place. It takes every universal edit, as `point` does.
## API reference
### `shape(options)`
One SVG path per row, centred at `x`/`y`. The shape comes from the `symbol` channel. It takes every universal edit, is picked inside its body, and declares a node box for a [network](https://elicitjs.github.io/marks/network.md).
JSON keyword: `plot.shape`
```ts
shape({ channels, symbol, edits, id, table, tip }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `symbol` | `string \| (d, i, data) => string` | `'circle'` | Shorthand for a constant `symbol` channel: a shape name, an SVG path, or a function of the row returning either. A string that is neither draws a circle and logs a warning. |
| `image` | `string \| (d) => string \| ChannelSpec` | | The shape's background image: a URL painted inside each shape in place of the fill. Takes `fit`, `position` and `repeat` as channel params, as in CSS. See [Image](https://elicitjs.github.io/marks/image.md#settings). |
| `channels` | `object` | `{}` | Channel map — see **Channels**. |
| `edits` | `Edit[]` | | Mark-level edits. `move`, `resize`, `rotate` and the rest work as on `point`. |
| `fill, stroke, size, angle, …` | `style` | `fill: theme ink` | Shorthands for constant channels. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x / y` | `linear \| point` | The shape's centre. Omitted, it sits at the middle of the plot on that axis. |
| `symbol` | `ordinal` | The shape per row. A field maps onto the named shapes `circle`, `square`, `triangle`, `diamond`, `star`, `cross`, `wye` by default, or onto `scale: { range: [...] }` — names or SVG path strings. Default `circle`. |
| `size` | `linear` | The radius of the box the shape fits, in px (default 6). Pair with `resize()` to drag it. |
| `angle` | `linear` | Rotation in degrees, counter-clockwise from east, about the shape’s centre. Pair with `rotate({ pick: 'direct', pivot: 'mark', fold: false })`. |
| `fill / stroke / strokeWidth / strokeDash / opacity` | `const \| field` | Paint, as on any mark. |
| `ports` | `true \| sides \| { out, in }` | Where links may meet the shape’s box in a network. Pair with `edit.network.connect()`. |
## Named shapes by category
Put a categorical field on `symbol` and each category takes a named shape: `circle`, `square`, `triangle`, `diamond`, `star`, `cross`, `wye`, in that order. `legends: true` keys each category with its shape.
You can grab a shape anywhere inside its outline.
### Example: Trees by species
symbol on a categorical field maps each species to a named shape; the legend keys them.
Try: **Drag** a shape to move it · **click** one to cycle its species.
```javascript
const chart = Elicit({
width: 440, height: 280,
margins: { top: 16, right: 16, bottom: 32, left: 36 },
legends: true,
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
kind: { type: "categorical", domain: ["oak", "pine", "birch", "maple"] },
},
data: [
{ x: 18, y: 30, kind: "oak" }, { x: 30, y: 72, kind: "pine" },
{ x: 46, y: 48, kind: "birch" }, { x: 62, y: 80, kind: "maple" },
{ x: 74, y: 26, kind: "oak" }, { x: 86, y: 58, kind: "pine" },
],
marks: [
shape({
size: 9, fill: "#1B3F60",
channels: {
x: { field: "x" },
y: { field: "y" },
// Each category takes a named shape: circle, square, triangle, diamond, …
symbol: { field: "kind", edit: cycle() },
},
edits: [move({ channels: ["x", "y"] })],
}),
],
});
mount(chart.dom());
```
## Pictograms from SVG paths
Give `symbol` a `scale: { range: [...] }` of SVG path strings, and each category draws its own pictogram. A path can use any coordinates. It is fitted to the box of radius `size` around its row's position.
The elicited value is the category. The path encodes it, as a colour does on `fill`.
### Example: Rank three needs
A path per category on the symbol scale; move() on y sets each priority.
Try: **Drag** a pictogram up or down to set its priority.
```javascript
// Hand-written SVG paths, one per category. Any coordinates work:
// each path is fitted to a box of radius `size` around its row's x/y.
const house = "M0 10 L10 0 L20 10 L17 10 L17 20 L3 20 L3 10 Z";
const car = "M1 12 L4 6 L16 6 L19 12 L19 16 L1 16 Z M4 16 A2 2 0 0 0 8 16 Z M12 16 A2 2 0 0 0 16 16 Z";
const heart = "M10 18 L2.5 10 A5 5 0 0 1 10 4.5 A5 5 0 0 1 17.5 10 Z";
const chart = Elicit({
width: 380, height: 260,
margins: { top: 20, right: 16, bottom: 32, left: 36 },
schema: {
need: { type: "categorical", domain: ["housing", "transport", "health"] },
priority: { type: "quantitative", domain: [0, 10] },
},
data: [
{ need: "housing", priority: 7 },
{ need: "transport", priority: 4 },
{ need: "health", priority: 8 },
],
marks: [
shape({
size: 16,
channels: {
x: { field: "need" },
y: { field: "priority", edit: move() },
symbol: { field: "need", scale: { range: [house, car, heart] } },
fill: { field: "need", scale: { range: ["#4e79a7", "#f28e2b", "#e15759"] } },
},
}),
],
});
mount(chart.dom());
```
## One path for every row
The `symbol` shorthand sets one shape for every row: a name, an SVG path, or `(d, i, data) => string` for a shape chosen per row. It defaults to `"circle"`. A string that is neither a name nor a readable path draws a circle and logs a warning.
`angle` rotates the shape in degrees, counter-clockwise from east. `rotate()` on `angle` turns it about its centre, and `resize()` on `size` grows it. Both read the same drag, so `when` separates them: with `when.noShift` and `when.shift`, a plain drag turns an arrow and Shift-drag sets its speed.
### Example: Wind arrows
symbol sets one arrow for every row; rotate() writes dir and resize() writes speed.
Try: **Drag** around an arrow to turn it · **Shift-drag** outward to make it longer.
```javascript
// Wind at three stations: drag an arrow to turn it, Shift-drag to set its speed.
const arrow = "M0 7 L12 7 L12 2 L20 10 L12 18 L12 13 L0 13 Z"; // points right (0°)
const chart = Elicit({
width: 400, height: 260,
margins: { top: 16, right: 16, bottom: 32, left: 36 },
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
dir: { type: "quantitative", domain: [0, 360] },
speed: { type: "quantitative", domain: [0, 30] },
},
data: [
{ x: 22, y: 62, dir: 30, speed: 12 },
{ x: 52, y: 34, dir: 120, speed: 20 },
{ x: 80, y: 70, dir: 300, speed: 6 },
],
constraints: [clamp({ field: "speed", min: 2, max: 30 })],
marks: [
shape({
symbol: arrow,
fill: "#50AEB7",
channels: {
x: { field: "x" },
y: { field: "y" },
// Degrees, counter-clockwise from east.
angle: {
field: "dir",
scale: { range: [0, 360] },
edit: rotate({ pick: "direct", pivot: "mark", fold: false, when: when.noShift }),
},
size: { field: "speed", scale: { range: [4, 28] } },
},
edits: [resize({ channel: "size", when: when.shift })],
}),
],
});
mount(chart.dom());
```
## Shapes as network nodes
A shape declares its box, so it can be the node mark of a [network](https://elicitjs.github.io/marks/network.md). Links meet the box's edges, and a `ports` channel puts connection points on them. On a shape turned by `angle`, the edges and ports turn with it.
### Example: A supply network
Each station is a shape by kind. ports with edit.network.connect() draws new links.
Try: **Drag** a station to move it · **drag** from a port to another station to link them · **drag** a link's end to rewire it.
```javascript
const chart = Elicit({
width: 460, height: 280,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
stations: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
kind: { type: "categorical", domain: ["source", "relay", "sink"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
feeds: {
role: "links",
directed: true,
fields: { source: { type: "ref" }, target: { type: "ref" } },
},
},
},
data: {
stations: [
{ id: "a", kind: "source", x: 10, y: 50 },
{ id: "b", kind: "relay", x: 40, y: 20 },
{ id: "c", kind: "relay", x: 40, y: 80 },
{ id: "d", kind: "relay", x: 68, y: 50 },
{ id: "e", kind: "sink", x: 92, y: 50 },
],
feeds: [
{ source: "a", target: "b" },
{ source: "a", target: "c" },
{ source: "b", target: "d" },
],
},
marks: [
link({ stroke: "#94A5B3", strokeWidth: 1.5, edits: [edit.network.rewire()] }),
shape({
size: 14,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
symbol: { field: "kind", scale: { range: ["triangle", "circle", "square"] } },
fill: { field: "kind", scale: { range: ["#7DB86B", "#50AEB7", "#EE7B5E"] } },
// Drag from a port to another station to link them.
ports: { value: true, edit: edit.network.connect() },
},
}),
],
});
mount(chart.dom());
```
---
# Track
> Source: https://elicitjs.github.io/marks/track/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`track()` draws a value as a length along a route: a bar that wraps, coils or curls round a circle. The route is the `path` option, an SVG path. The `length` channel is how much of it is drawn, and `move()` on `length` drags the end of the bar along the route.
## API reference
### `track(options)`
A value drawn as a length along a route. The route is the `path` option, and the `length` channel is the fraction of it drawn. Each row draws its route as an invisible grab area, then its bar.
JSON keyword: `plot.track`
```ts
track({ path, join, channels, edits, id, table, tip }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `path` | `string \| (d, i, data) => string` | | The route: an SVG path, or a function of the row returning one. Each `M` starts a lane, and only lanes hold value. In plot pixels, or in unit form when `x`, `y` or `size` is bound. A path that can’t be read draws nothing and logs a warning. |
| `join` | `'round' \| 'straight' \| 'none'` | `'none'` | What connects one lane to the next. It holds no value. `'round'` leaves along one lane and arrives along the next. |
| `channels` | `object` | `{}` | Channel map — see **Channels**. |
| `edits` | `Edit[]` | | Mark-level edits. `move()` on `length` drags the end of the bar along the route; `slide()` adds to it along one axis. |
| `stroke, strokeWidth, opacity, …` | `style` | `stroke: theme ink, strokeWidth: 2` | Shorthands for constant channels. The bar is a stroke and is never filled. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `length` | `linear` | How much of the route is drawn. Its range is `[0, 1]`, so the schema’s domain spans the whole route. Omitted, the whole route is drawn. Pair with `move()`. |
| `x / y` | `linear \| point` | Where a unit-form path is centred. Binding either one places the path. |
| `size` | `linear` | The radius of the box a unit-form path fits, in px (default 6). |
| `angle` | `linear` | Rotation of a unit-form path in degrees, counter-clockwise from east. |
| `stroke / strokeWidth / strokeDash / opacity` | `const \| field` | The bar's paint. |
## A route for every row
The schema's domain spans the whole route: the domain's maximum draws all of it, and half of it draws half. Rows read on one scale when every row's route is the same length.
`path` is in plot pixels. A function of the row, `(d, i, data) => string`, gives each row its own route. When `x`, `y` or `size` is bound, the path is in unit form and placed the way [`shape`](https://elicitjs.github.io/marks/shape.md) places one: centred at `x`/`y`, fitted to a box of radius `size`, turned by `angle`. One path then draws a route for every row.
`move()` puts the end of the bar at the point of the route nearest the pointer. You can press anywhere on the route, even where no bar is drawn, so a bar at zero can still be grabbed. During a drag the end follows the route from where it was, so it doesn't jump to a part of the route that only passes close by. `slide()` on `length` also works: it adds to the value as you drag along one axis.
### Example: Project progress
One circular path, placed per row by x and size. move() on length writes done.
Try: **Drag the end of a ring** round its circle · **press** anywhere on a grey circle to jump the ring there.
```javascript
// How far along is each project? Drag the end of a ring round its circle.
// One route for every row: a circle from the top, clockwise, in unit form.
// x, y and size place it, so each row draws its own ring.
const ring = "M0,-1 A1,1 0 1 1 -0.001,-1";
const chart = Elicit({
width: 460, height: 200,
margins: { top: 10, right: 10, bottom: 40, left: 10 },
axes: false,
schema: {
project: { type: "categorical" },
done: { type: "quantitative", domain: [0, 100] },
},
data: [
{ project: "Survey", done: 80 },
{ project: "Interviews", done: 35 },
{ project: "Report", done: 10 },
],
constraints: [snap({ step: 1 })],
marks: [
// The full circle, faint, under each ring.
track({
path: ring,
channels: {
x: { field: "project" }, size: { value: 50 }, y: { value: 75 },
stroke: { value: "#dddddd" }, strokeWidth: { value: 12 },
},
}),
track({
path: ring,
channels: {
x: { field: "project" }, size: { value: 50 }, y: { value: 75 },
length: { field: "done", edit: move() },
stroke: { value: "#50AEB7" }, strokeWidth: { value: 12 },
},
}),
text({ channels: {
x: { field: "project" }, y: { value: 75 },
text: { fn: (d) => `${d.done}%` }, fontSize: { value: 16 },
} }),
text({ channels: {
x: { field: "project" }, y: { value: 160 },
text: { field: "project" }, fontSize: { value: 12 }, fill: { value: "#555555" },
} }),
],
});
mount(chart.dom());
```
## Lanes and joins
Each `M` in the path starts a **lane**. Only lanes hold value, so the gap from one lane to the next adds nothing to the length. `join` draws what connects them: `"round"` turns through a curve that leaves along one lane and arrives along the next, so two lanes running opposite ways get a half circle. `"straight"` draws a line across the gap. `"none"` (the default) leaves it empty. A join is drawn once the bar reaches the next lane.
A route with one lane, such as a coil with square corners, needs no `join`: every pixel of it holds value.
### Example: Three joins
Three charts over one dataset. Each draws the same value along the same three lanes, with a different join.
Try: **Drag the end of any bar** round a turn · the other two charts follow.
```javascript
// One value, drawn three ways. Each chart takes the same route, three lanes
// with one `M` each, and a different `join` for what connects them.
const route = "M110,20L410,20 M410,42L110,42 M110,64L410,64";
const ds = Elicit.dataset({
schema: { value: { type: "quantitative", domain: [0, 90] } },
data: [{ value: 50 }],
constraints: [snap({ step: 1 })],
});
for (const join of ["round", "straight", "none"]) {
const chart = ds.chart({
width: 460, height: 90,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
axes: false,
marks: [
track({
path: route,
join,
channels: {
length: { field: "value", edit: move() },
stroke: { value: "#50AEB7" }, strokeWidth: { value: 8 },
},
}),
text({ channels: {
x: { value: 20 }, y: { value: 42 },
text: { value: `join: "${join}"` }, textAnchor: { value: "start" }, fontSize: { value: 12 },
} }),
],
});
mount(chart.dom());
}
```
[Du Bois's wrapped bars](https://elicitjs.github.io/case-studies/du-bois-wrapped.md) builds wrapped bars with `track`, and [his coil and spiral](https://elicitjs.github.io/case-studies/du-bois-spiral.md) draw a coil and a spiral with it.
---
# Image
> Source: https://elicitjs.github.io/marks/image/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
Pictures work as they do in CSS. `image()` draws one picture per row at `x`, `y`, from its `src` channel, like an ` `. On `bar`, `rect`, `area`, `point`, `ellipse`, `shape`, `waffle` and `dotStack`, the `image` channel is the shape's background image: it paints inside the shape in place of the fill. Both channels take their settings as params: `fit`, `position`, and on `image`, `repeat`. For a picture behind the whole chart, use [`guides.image`](https://elicitjs.github.io/guides.md#image).
## API reference
### `image(options)`
Import `plot` from `elicitjs`. One picture per row, like an ` `, centred at `x`, `y` in a square of side `2 * size`.
JSON keyword: `plot.image`
```ts
image({ src, channels, edits, id }) → Mark
image({ channels: { x, y, src: { field: "photo", fit: "cover", position: "top" } } })
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `Channels` | `{}` | x, y, src, size, angle plus the standard style channels. |
| `src` | `string \| (d) => string` | | The picture's URL for every row. Shorthand for channels.src = { value }. |
| `size` | `number \| ChannelSpec` | `16` | Half the square's side, in px. |
| `stroke, opacity, …` | `style` | | A stroke outlines the square; opacity fades the picture. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x, y` | `linear \| band \| point` | The centre. A missing channel parks it at the centre of that dimension. |
| `src` | `raw` | The picture's URL: a column of URLs ({ field }), one URL ({ value }) or a function of the row ({ fn }). Read as-is, never scaled. Takes fit (default 'contain') and position as params. |
| `angle` | `linear` | Rotation in math degrees about the centre. |
Returns / emits: A **mark** emitting one picture per row that has a URL.
### `image channel (on marks)`
A shape's background image. `bar`, `rect`, `area`, `point`, `ellipse`, `shape`, `waffle` and `dotStack` paint it inside each shape in place of the fill. Its settings are params of the channel.
JSON keyword: `mark`
```ts
barY({ image: "photo.jpg", channels })
barY({ channels: { x, y, image: { value: "icon.svg", fit: "contain", position: "bottom", repeat: "repeat-y" } } })
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `image` | `string \| (d) => string` | | The picture's URL. Shorthand for channels.image = { value }. |
| `fit` | `'cover' \| 'contain' \| 'fill' \| 'none' \| 'scale-down'` | `'cover' on image · 'contain' on src` | How the picture is sized in its box, as CSS object-fit. |
| `position` | `string` | `'center'` | Where the picture sits in its box, as CSS object-position: keywords ('top', 'bottom left') and percentages ('25% 75%'). |
| `repeat` | `'no-repeat' \| 'repeat' \| 'repeat-x' \| 'repeat-y'` | `'no-repeat'` | Whether the picture repeats from where position puts it, as CSS background-repeat. |
## One picture per row
`image()` centres each picture on its row's `x` and `y`, in a square of side `2 * size` (default `size: 16`, a 32px square). Give one URL with the `src` shorthand, or a column of URLs with `channels: { src: { field } }`. A row with no URL draws nothing.
The picture moves, picks and outlines like any other mark, so `move()` places it.
### Example: Place each forecast
Each row names its icon in src; move() writes both coordinates.
Try: **Drag** each icon to how likely and how disruptive you think that day's weather is.
```javascript
const chart = Elicit({
width: 420, height: 300,
margins: { top: 16, right: 20, bottom: 40, left: 48 },
axes: { x: { title: "how likely (%)" }, y: { title: "how disruptive" } },
data: [
{ day: "Mon", icon: "/images/sun.svg", chance: 70, impact: 1 },
{ day: "Tue", icon: "/images/cloud.svg", chance: 45, impact: 3 },
{ day: "Wed", icon: "/images/storm.svg", chance: 25, impact: 8 },
],
schema: {
day: { type: "categorical" },
icon: { type: "categorical" },
chance: { type: "quantitative", domain: [0, 100] },
impact: { type: "quantitative", domain: [0, 10] },
},
marks: [
image({
size: 18,
channels: {
x: { field: "chance" },
y: { field: "impact" },
// One URL per row. `fit` and `position` work as on an .
src: { field: "icon", fit: "contain" },
},
edits: [ move({ channels: ["x", "y"] }) ],
}),
],
});
mount(chart.dom());
```
## Pictures inside marks
Set the `image` channel on a mark with a shape and the picture replaces its fill. The mark keeps its stroke, its edits and its geometry. `fillOpacity` and `opacity` fade the picture. A hover or selection effect that sets `fill` shows its colour in place of the picture.
`repeat` repeats the picture from where `position` puts it, as `background-repeat` does. With `fit: 'contain'`, `position: 'bottom'` and `repeat: 'repeat-y'`, each picture is as wide as the bar and they stack up from its base, so a taller bar shows more copies.
### Example: People in a bar
image: { value, fit: "contain", position: "bottom", repeat: "repeat-y" }
Try: **Drag** a bar up or down.
```javascript
const chart = Elicit({
width: 380, height: 300,
margins: { top: 14, right: 14, bottom: 26, left: 34 },
data: [
{ group: "18–34", people: 40 }, { group: "35–54", people: 65 },
{ group: "55+", people: 25 },
],
schema: {
group: { type: "categorical", domain: ["18–34", "35–54", "55+"] },
people: { type: "quantitative", domain: [0, 100] },
},
scales: { x: { type: "band", padding: 0.55 } },
marks: [
barY({
channels: {
x: { field: "group" },
y: { field: "people", edit: move() },
// As CSS: each picture as wide as the bar, stacked up from its base.
image: {
value: "/images/person.svg",
fit: "contain", position: "bottom", repeat: "repeat-y",
},
},
}),
],
});
mount(chart.dom());
```
On a `waffle`, each filled cell shows the picture and empty cells stay the track. With one cell per person, the chart is a pictogram.
### Example: A pictogram you fill
100 cells, one per person; edit.waffle.fill() sets how many are filled.
Try: **Drag** up or down the grid to set how many people out of 100.
```javascript
const chart = Elicit({
width: 260, height: 300,
margins: { top: 16, right: 12, bottom: 24, left: 12 },
data: [{ cat: "of 100 people", value: 30 }],
schema: {
cat: { type: "categorical", domain: ["of 100 people"] },
value: { type: "quantitative", domain: [0, 100] },
},
scales: { x: { type: "band" } },
marks: [
waffleY({
multiple: 10,
channels: {
x: { field: "cat" },
count: { field: "value", edit: edit.waffle.fill() },
// Each filled cell shows the picture; empty cells stay the track.
image: { value: "/images/person.svg", fit: "contain" },
},
}),
],
});
mount(chart.dom());
```
## Fit, position and repeat
The settings are params of the channel, next to its `field` or `value`: `image: { field: 'photo', fit: 'contain', position: 'top' }`. A mark's box is its shape's bounding box. An `image()`'s box is its square.
- `fit` sizes the picture, as `object-fit`. `'cover'` fills the box and crops what spills over; `'contain'` shows all of it; `'fill'` stretches it to the box; `'none'` keeps the picture's own size; `'scale-down'` is the smaller of `'none'` and `'contain'`. The default is `'cover'` on `image` and `'contain'` on `src`.
- `position` places the picture in what room is left, as `object-position` and `background-position`. It takes keywords (`'center'`, `'top'`, `'bottom left'`) and percentages (`'25% 75%'`). The default is `'center'`.
- `repeat` repeats the picture across the box, as `background-repeat`: `'no-repeat'` (the default), `'repeat'`, `'repeat-x'` or `'repeat-y'`. It applies to `image` only, since an ` ` does not repeat.
`fit: 'none'` and `'scale-down'` read the picture's own width and height. Give an SVG explicit `width` and `height` attributes, or these use its default size.
`arc`, `line`, `text` and the other marks draw no `image` channel and log a warning when given one.
---
# Ellipse
> Source: https://elicitjs.github.io/marks/ellipse/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`ellipse` draws a dot with two radii, `rx` and `ry`. Each is its own channel, with its own field and its own edit, so one mark elicits two numbers. `size` sets any radius you leave unset.
## API reference
### `ellipse(options)`
Import `plot` from `elicitjs`. A dot with **two independent radii**. `point` has one `size` channel because a circle has one radius; splitting it into `rx` and `ry` means each can carry its own field and its own edit — two elicited numbers in one shape.
JSON keyword: `plot.ellipse`
```ts
ellipse({ channels, edits, id }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `Channels` | `{}` | x, y, rx, ry, angle plus the standard style channels. |
| `image` | `string \| (d) => string \| ChannelSpec` | | The shape's background image: a URL painted inside each shape in place of the fill. Takes `fit`, `position` and `repeat` as channel params, as in CSS. See [Image](https://elicitjs.github.io/marks/image.md#settings). |
| `size` | `number \| ChannelSpec` | `5` | The fallback for whichever radius is not otherwise named, so ellipse({ size: 6 }) is a circle. |
| `fill, stroke, …` | `style` | `theme ink` | The standard style surface, same as every mark. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x, y` | `linear \| band \| point` | The centre. A missing channel parks it at the centre of that dimension. |
| `rx` | `size` | Horizontal radius in px (default range `[3, 18]`). Natural edit: `slide({ axis: 'x' })`. |
| `ry` | `size` | Vertical radius in px. Natural edit: `slide({ axis: 'y' })`. Both fall back to `size`. |
| `angle` | `linear` | Tilt in math degrees about the centre. A rotated ellipse is hit-tested in its own frame, so it stays grabbable where it is drawn. |
Returns / emits: A **mark** emitting one `ellipse` node per datum.
## Two uncertainties, one blob
Use an ellipse for an estimate with per-axis uncertainty. The centre is the estimate, and each radius is the uncertainty along its axis.
Both radius edits are on the same mark, so one diagonal drag reshapes the blob. `slide({ axis: 'x' })` and `slide({ axis: 'y' })` read different components of the drag, so they work together.
### Example: Cost × benefit, with per-axis spread
rx and ry are separate fields; drag a blob sideways to widen it, up or down to flatten it.
Try: **Drag** a blob sideways (cost spread) or vertically (benefit spread).
```javascript
const chart = Elicit({
width: 480, height: 320,
margins: { top: 20, right: 24, bottom: 40, left: 44 },
axes: { x: {}, y: {} },
data: [
{ region: "North", cost: 30, benefit: 62, costSd: 8, benefitSd: 16 },
{ region: "South", cost: 66, benefit: 34, costSd: 17, benefitSd: 6 },
],
schema: {
cost: { type: "quantitative", domain: [0, 100] },
benefit: { type: "quantitative", domain: [0, 100] },
costSd: { type: "quantitative", domain: [2, 30] },
benefitSd: { type: "quantitative", domain: [2, 30] },
region: { type: "categorical", domain: ["North", "South"] },
},
marks: [
// One blob per region: the CENTRE is the estimate, the two RADII are two
// separate uncertainties. A circle could only say "how unsure overall"; two
// radii let a reader say they are confident about cost and vague about benefit.
// Both edits sit on one mark, so a single diagonal drag reshapes the blob —
// that is the point of rx and ry being independent channels.
ellipse({
channels: {
x: { field: "cost" },
y: { field: "benefit" },
rx: { field: "costSd", scale: { range: [6, 64] },
edit: slide({ axis: "x", increase: "right" }) },
ry: { field: "benefitSd", scale: { range: [6, 64] },
edit: slide({ axis: "y", increase: "down" }) },
fill: { field: "region" },
fillOpacity: { value: 0.35 },
stroke: { field: "region" },
},
}),
],
});
mount(chart.dom());
```
## Moving it as well
Two edits that read the same component of a drag conflict on one mark: a `move()` on the centre and a radius `slide` would both fire. Gate one with `when` (for example `when.shift`, as on [Shape](https://elicitjs.github.io/marks/shape.md#path)), or give each its own mark in a [composite](https://elicitjs.github.io/marks/composite.md): an `ellipse` that resizes, and a `point` at its centre that moves. Direct pick sends each drag to the mark you touched.
### Example: A blob you can move and resize
The ellipse carries the radius edit; a small centre dot carries the move. Two marks, two gestures, one row.
Try: **Drag the dot** to move the blob · **drag the blob** to resize it.
```javascript
const chart = Elicit({
width: 420, height: 320,
margins: { top: 20, right: 24, bottom: 40, left: 44 },
axes: { x: {}, y: {} },
data: [ { cost: 40, benefit: 55, sd: 14 } ],
schema: {
cost: { type: "quantitative", domain: [0, 100] },
benefit: { type: "quantitative", domain: [0, 100] },
sd: { type: "quantitative", domain: [2, 30] },
},
marks: [
// Two edits that both read a raw drag can't share one mark — one gesture would
// fire both. Give them one mark each: the blob resizes, the dot at its centre
// moves. Direct-pick routes a gesture to the mark you touched, so there is
// nothing to arbitrate.
composite({
id: "blob",
parts: [
ellipse({ channels: {
x: { field: "cost" },
y: { field: "benefit" },
rx: { field: "sd", scale: { range: [6, 64] },
edit: slide({ axis: "x", increase: "right" }) },
ry: { field: "sd", scale: { range: [6, 64] } },
fill: { value: "#50AEB7" }, fillOpacity: { value: 0.28 },
stroke: { value: "#37919B" },
} }),
point({ channels: {
x: { field: "cost", edit: move({ channels: ["x", "y"] }) },
y: { field: "benefit" },
size: { value: 5 },
fill: { value: "#20555A" },
} }),
],
}),
],
});
mount(chart.dom());
```
## Inside a glyph
A [face](https://elicitjs.github.io/marks/face.md) draws its eyes with `ellipse`: an `rx` that opens and an `ry` that squints, both set as fractions of the glyph's frame so they scale with the head. See [composite](https://elicitjs.github.io/marks/composite.md#box) for how a mark places itself in a glyph's local coordinates.
---
# Curve
> Source: https://elicitjs.github.io/marks/curve/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`curve` draws a segment bowed off its chord. The bend is the `curvature` channel, so how much it bends, and which way, is an elicited number. `curveY` spans `x` and sits on `y`, `curveX` spans `y` and sits on `x`, and `curve` reads the channels you declare.
## API reference
### `curve(options) · curveX · curveY`
Import `plot` from `elicitjs`. A segment that **bends**. A `tick` draws a straight line between two points; a curve draws the same span bowed off its chord by an amount that is itself a channel — so “how much does this bend, and which way” becomes an elicited number. `curveY` spans x and sits on y; `curveX` spans y and sits on x; bare `curve` reads the declared channels.
JSON keyword: `plot.curve`, `plot.curveX`, `plot.curveY`
```ts
curve({ channels, orientation, length, edits, id }) → Mark
curveY(options) → Mark // value on y (chord along x)
curveX(options) → Mark // value on x (chord along y)
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `Channels` | `{}` | The chord endpoints (x1/x2 or y1/y2; with one end given, the other is the baseline), the position on the other axis, curvature, angle, plus the standard style channels. |
| `orientation` | `'vertical' \| 'horizontal'` | `auto` | Which axis the value runs along (`'vertical'` = y). Inferred from the declared chord pair, a band scale or the lone bound channel; `curveY / curveX` pin it. |
| `length` | `number` | `min(w,h)·0.25` | Chord length in px, centred on the span axis' own channel. Used only when no endpoint pair is declared. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `curvature` | `linear` | How far the apex sits off the chord, as a fraction of the HALF-chord: 0 is a straight segment, ±1 bows out by half the span’s length. Positive bows to the **left of travel** (a rightward chord bows up). It scales with the chord, so a glyph’s curve stays proportional when the glyph resizes. Natural edit: `slide({ axis: 'y' })`. |
| `x1, x2 (curveY)` | `linear \| band \| point` | The chord's two ends. Without them the chord is `length` px centred on the `x` channel. |
| `y (curveY)` | `linear` | Where the chord sits. curveX swaps the two families: y1/y2 span, x positions. |
| `angle` | `linear` | Tilt about the chord midpoint, in math degrees. Baked into the geometry (neither renderer rotates a path node), so it works everywhere. Natural edit: `rotate({ pivot: 'mark', pick: 'direct' })`. |
Returns / emits: A **mark** emitting two path nodes per datum: the visible curve, and a fat transparent **hit path** over it so a few-pixel stroke is actually grabbable. The hit path leaves `pointerEvents` unset, so an inert curve is silenced by the engine and can’t swallow a neighbour’s drag.
## One number: how much it bends
`curvature` is the apex's offset from the chord as a fraction of the **half-chord**. 0 is a straight segment, and ±1 bows out by half the span's length. The shape stays proportional when the span changes, so a face's mouth keeps its expression when the head is resized.
Positive curvature bows to the left of travel, from the first endpoint to the second, so a rightward chord bows up. Set the direction on the scale: a descending `range` turns a rising field into a deepening cup.
### Example: How does value grow between the ends?
The chord is fixed and only the shape between its ends is elicited: one number.
Try: **Drag** a curve up to arch it, down to cup it.
```javascript
const chart = Elicit({
width: 480, height: 300,
margins: { top: 20, right: 24, bottom: 40, left: 44 },
axes: { x: {}, y: false },
data: [
{ option: "A", convexity: 0.6 },
{ option: "B", convexity: -0.3 },
{ option: "C", convexity: 0.0 },
],
schema: {
option: { type: "categorical", domain: ["A", "B", "C"] },
convexity: { type: "quantitative", domain: [-1, 1] },
},
marks: [
// "How does value grow between the two ends?" — a straight line means steadily,
// a bow means front- or back-loaded. The chord is fixed (both ends are agreed);
// only the SHAPE between them is elicited, which is exactly one number.
curveY({
length: 110,
channels: {
x: { field: "option" },
// No y scale here, so the height is a visual constant: `{ value }` is in
// pixels, and skips the scale by definition.
y: { value: 150 },
// Positive curvature bows to the LEFT of travel — up, for a chord that runs
// left to right. So an ascending range plus increase:"up" makes dragging up
// arch it and dragging down cup it.
curvature: { field: "convexity", scale: { range: [-0.8, 0.8] },
edit: slide({ axis: "y", increase: "up" }) },
stroke: { value: "#50AEB7" },
strokeWidth: { value: 3 },
},
}),
],
});
mount(chart.dom());
```
## Bend and tilt
`angle` tilts the whole curve about its chord midpoint.
Both edits work on the same mark because they read different components of one drag: `slide({ axis: "y" })` on `curvature` and `slide({ axis: "x" })` on `angle`. Two edits that read the same component conflict, unless `when` gates one of them (see [Shape](https://elicitjs.github.io/marks/shape.md#path)). Use `slide`, not `rotate`, on `angle`: you grab the curve at its own pivot, so a few pixels of travel swing `rotate` through most of a half-turn and pin the value to an extreme.
### Example: An explicit chord, bent and leaning
x1 → x2 states the chord outright; curvature bends it and angle leans it.
Try: **Drag** the curve up and down to bend it · around to tilt it.
```javascript
const chart = Elicit({
width: 420, height: 300,
margins: { top: 20, right: 30, bottom: 40, left: 44 },
axes: { x: {}, y: {} },
data: [ { from: 15, to: 85, at: 55, bow: 0.5, lean: 12 } ],
schema: {
from: { type: "quantitative", domain: [0, 100] },
to: { type: "quantitative", domain: [0, 100] },
at: { type: "quantitative", domain: [0, 100] },
bow: { type: "quantitative", domain: [-1, 1] },
lean: { type: "quantitative", domain: [-45, 45] },
},
marks: [
// An explicit endpoint PAIR states the chord: x1 → x2 at height y. Both edits
// sit on one mark, so ONE drag drives both: its vertical component bends the
// curve, its horizontal one tilts it. Reading two components of a gesture is
// what lets two params share a mark without fighting — an angular edit here
// would fire off both, since you are standing on the pivot.
curveY({
channels: {
x1: { field: "from" },
x2: { field: "to" },
y: { field: "at" },
curvature: { field: "bow", scale: { range: [-0.8, 0.8] },
edit: slide({ axis: "y", increase: "up" }) },
angle: { field: "lean", scale: { range: [-45, 45] },
edit: slide({ axis: "x", increase: "right" }) },
stroke: { value: "#EE7B5E" },
strokeWidth: { value: 3 },
},
}),
],
});
mount(chart.dom());
```
## Grabbing a curve
A curve carries a wide transparent hit area along its stroke, so a drag near the line catches it, on both SVG and canvas. Edits measure from the chord midpoint. A curve with no edit lets drags pass through to the marks beneath it.
---
# Arc · Pie · Donut
> Source: https://elicitjs.github.io/marks/arc/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`arc` and `donut` draw **pie** and **donut** slices. Each row's magnitude, on the `theta` channel, is stacked and normalised to a full circle or a partial arc. `edit.stack.edge()`, `cut()` and `merge()` reshape the slices while keeping the total fixed. `x`/`y` scatter one donut per value, and a `radius` channel gives each slice its own rim for a rose plot.
## API reference
### `arc(options) · donut(options)`
Import `plot` from `elicitjs`. `donut` is `arc` with a default inner radius. A full pie is just `arc()`.
JSON keyword: `plot.arc`, `plot.donut`
```ts
arc({ channels, outerRadius, innerRadius, padAngle, arc, start, end, handles, handleSize, handleColor, edits, id }) → Mark
donut(options) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `outerRadius` | `number` | `fits the slot` | Outer radius in px, for every donut. Omit to fit the slot (a band cell, or a shrunk scatter default); or bind a size field for a per-donut radius. |
| `innerRadius` | `number` | `0` | Inner radius; >0 makes a donut. A value in `(0,1]` is a **ratio** of the outer radius (so a fitted / size-driven donut stays proportional); >1 is absolute px. `donut()` defaults this. |
| `padAngle` | `number` | `0` | Gap between slices in degrees. |
| `arc` | `'semi' \| 'full'` | `'full'` | Angular span of the whole pie. `'semi'` is the top half. |
| `start / end` | `number` | `-180 / 180` | Explicit span in degrees, measured counter-clockwise from 3 o’clock (0° is the right, 90° the top). The span is signed: `start: 90, end: -270` walks clockwise from 12 o’clock. Both given, they override `arc`. |
| `edits` | `Edit \| Edit[]` | | Slice editing — `edit.stack.cut()`, `edit.stack.edge()`, `edit.stack.merge()`. Draws a grab handle on each interior boundary (*n* slices → *n* − 1 handles; the seam is the layout's fixed anchor). |
| `handles` | `boolean \| 'hit'` | `true with a stack edit` | Unset, the boundary dots draw once an `edit.stack.*` edit is wired. `true` always draws them, as ink on a pie with no edit. `'hit'` keeps each boundary grabbable but draws no dot. `false` is neither drawn nor grabbable. |
| `handleSize` | `number` | `5` | Pixel radius of each boundary handle. |
| `handleColor` | `string` | `theme` | Handle fill. Defaults to the theme’s `handle` colour. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `theta` | `magnitude field` | Slice size in data units; layout normalizes by the sum of rows. The polar positional channel (Vega-Lite's name for it) — not `angle`, which is a mark's rotation in place, and not `value`, which already means a visual-space constant on any channel. Read raw here: an arc normalizes its own magnitudes, so it neither implies a radial axis nor draws a fan key. |
| `stack` | `categorical \| ordinal field` | Optional. Names each slice and orders the slices by the field's schema domain (else first appearance); without it, slices follow data order. `edit.stack.cut()` writes a new slice's category into it, so a cut needs it. |
| `fill` | `ordinal \| const` | Slice colour. |
| `x / y` | `field \| const` | Donut centre. Bind a field to place one donut per distinct value (a band category, or a scatter coordinate) — a grid of donuts, grouped by the encoding. Unbound → the plot centre (one donut). |
| `size` | `field \| const` | Optional per-donut outer radius (e.g. turnout), through the size scale. Overridden by an explicit outerRadius. |
| `radius` | `linear \| sqrt` | Per-slice outer radius (a rose plot), through a radius scale whose range runs from `innerRadius` to `outerRadius`. `scale: 'sqrt'` makes area proportional to the value. Takes an edit: `move()` drags a slice’s rim. Wins over `size`. Key it with `axisRadial({ channel: 'radius' })`. |
Returns / emits: A **mark** emitting one filled `path` per row.
## Pie
Full circle, zero inner radius.
### Example: Party shares
Three slices from a shared total.
```javascript
const chart = Elicit({
width: 300, height: 280,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
data: [
{ party: "D", share: 48 },
{ party: "R", share: 45 },
{ party: "O", share: 7 },
],
schema: {
party: { type: "categorical" },
share: { type: "quantitative", domain: [0, 100] },
},
marks: [
arc({
outerRadius: 100,
channels: {
theta: { field: "share" },
fill: { field: "party" },
},
}),
],
});
mount(chart.dom());
```
## Donut
The same layout with an inner hole, which leaves room for a centre label.
### Example: Donut with centre text
Static proportions; text is a sibling mark.
```javascript
const chart = Elicit({
width: 300, height: 280,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
data: [
{ party: "D", share: 48, label: "48%" },
{ party: "R", share: 45, label: "" },
{ party: "O", share: 7, label: "" },
],
schema: {
party: { type: "categorical" },
share: { type: "quantitative", domain: [0, 100] },
label: { type: "categorical" },
},
marks: [
donut({
outerRadius: 100, innerRadius: 55,
channels: {
theta: { field: "share" },
fill: { field: "party" },
},
}),
text({
fontSize: 22,
channels: {
text: { value: "100%" },
textAnchor: { value: "middle" },
lineAnchor: { value: "middle" },
},
}),
],
});
mount(chart.dom());
```
## Editable slice boundaries
Add `edit.stack.edge()` and every interior boundary gets a draggable handle, so *n* slices give *n* − 1 handles. The seam where the last slice meets the first stays fixed, since the orientation and the total are both fixed.
Dragging a boundary moves value between the two slices it separates. One grows by what the other loses, so the total is preserved.
### Example: Drag any boundary
Each handle pair-shifts the two slices it sits between; the rest of the pie holds still.
Try: **Drag** a dot on any slice edge.
```javascript
const chart = Elicit({
width: 300, height: 280,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
data: [
{ party: "D", share: 40 },
{ party: "R", share: 35 },
{ party: "O", share: 25 },
],
schema: {
party: { type: "categorical" },
share: { type: "quantitative", domain: [0, 100] },
},
marks: [
arc({
outerRadius: 100,
edits: [edit.stack.edge()],
channels: {
theta: { field: "share" },
fill: { field: "party" },
},
}),
],
});
mount(chart.dom());
```
### Example: Donut, four slices
Four slices → three handles.
Try: **Drag** any edge — the two adjacent slices rebalance.
```javascript
const chart = Elicit({
width: 300, height: 280,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
data: [
{ cat: "A", v: 20 },
{ cat: "B", v: 20 },
{ cat: "C", v: 20 },
{ cat: "D", v: 40 },
],
schema: {
cat: { type: "categorical" },
v: { type: "quantitative", domain: [0, 100] },
},
marks: [
donut({
outerRadius: 100, innerRadius: 50,
edits: [edit.stack.edge()],
handleSize: 6,
channels: {
theta: { field: "v" },
fill: { field: "cat", scale: { scheme: "dd" } },
},
}),
],
});
mount(chart.dom());
```
## Cutting and merging slices
A pie divides one total among its rows, as a stacked `bar` does along an axis. The same three gestures work on both:
- `edit.stack.cut()` — **click** inside a slice to divide it in two at the pointer angle.
- `edit.stack.edge()` — **drag** a boundary to move value across it.
- `edit.stack.merge()` — **double-click** a boundary to fuse those two slices back into one.
Each preserves the pie's total, and each takes `pick: "nearest"` to grab a slice or boundary from close by. A cut needs a `stack` channel: it writes the new slice's category into that field, taking a value from its schema domain, so it needs no typing. A pie always stacks, so on `arc` the `stack` channel only names the slices and orders them by its domain. Without it, slices follow data order. A closed domain hands out the values this pie doesn't yet use, and refuses the cut once they run out. `open: true` lets each cut append a new one. See [Slicing a stack](https://elicitjs.github.io/marks/bar.md#slice) for the bar form.
### Example: Cut a slice
One full circle to start. The category domain declares five values, so the pie takes four cuts.
Try: **Click** inside a slice to cut it, **drag** a boundary to shift share, **double-click** one to merge.
```javascript
const chart = Elicit({
width: 300, height: 300,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
data: [{ category: "housing", share: 100 }],
schema: {
category: {
type: "categorical",
domain: ["housing", "food", "transport", "savings", "other"],
},
share: { type: "quantitative", domain: [0, 100] },
},
legends: true,
marks: [
arc({
outerRadius: 100,
channels: {
theta: { field: "share" },
stack: { field: "category" },
fill: { field: "category" },
},
edits: [
edit.stack.cut(),
edit.stack.edge(),
edit.stack.merge(),
],
}),
],
});
mount(chart.dom());
```
## A grid of donuts
Bind `x` (and optionally `y`) to a field and each distinct value becomes a **slot** with its own donut. The rows at that slot are its slices, so the encoding does the grouping. A `size` field scales each donut separately, and `outerRadius` sets one radius for all. Otherwise the radius fits the slot.
Here `x: { field: 'state' }` gives a band axis, so `IL`, `NY` and `NC` each get a donut of their own party split. A boundary drag moves share within that state only, and the other states keep their totals.
### Example: Party split per state
One donut per band-axis category; each state's boundaries redistribute within that state alone.
Try: **Drag** a boundary in one state — only that state’s shares rebalance.
```javascript
const chart = Elicit({
width: 520, height: 260,
margins: { top: 20, right: 20, bottom: 30, left: 20 },
data: [
{ state: "IL", party: "D", share: 55 },
{ state: "IL", party: "R", share: 38 },
{ state: "IL", party: "O", share: 7 },
{ state: "NY", party: "D", share: 60 },
{ state: "NY", party: "R", share: 33 },
{ state: "NY", party: "O", share: 7 },
{ state: "NC", party: "D", share: 47 },
{ state: "NC", party: "R", share: 48 },
{ state: "NC", party: "O", share: 5 },
],
schema: {
party: { type: "categorical" },
share: { type: "quantitative", domain: [0, 100] },
state: { type: "categorical", domain: ["IL", "NY", "NC"] },
},
marks: [
donut({
edits: [edit.stack.edge()],
handleSize: 6,
channels: {
x: { field: "state" }, // band axis → one donut per state
theta: { field: "share" }, // party's share within its state
fill: { field: "party" },
},
}),
],
});
mount(chart.dom());
```
## Rose plots (radius)
The `radius` channel gives each slice its own outer radius, between `innerRadius` and `outerRadius`, for a rose or radial plot. `theta` still sets each slice's angle. `theta: { value: 1 }` makes every slice the same width, so the value reads from the rim alone. With no `outerRadius`, the ring's extent is 40% of the smaller plot dimension.
`scale: 'sqrt'` makes a slice's area grow with its value; the default linear scale makes its radius grow with it. Put `edit: move()` on the channel to drag a slice's rim in or out. `axisRadial({ channel: 'radius' })` draws concentric rings as its key.
### Example: A rose you can reshape
radius: { field: "speed", scale: "sqrt", edit: move() } — eight equal slices, each rim a value.
Try: **Drag** a slice's rim outward or inward to change its speed.
```javascript
const chart = Elicit({
width: 320, height: 300,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
data: [
{ dir: "N", speed: 12 }, { dir: "NE", speed: 8 },
{ dir: "E", speed: 5 }, { dir: "SE", speed: 9 },
{ dir: "S", speed: 18 }, { dir: "SW", speed: 24 },
{ dir: "W", speed: 15 }, { dir: "NW", speed: 10 },
],
schema: {
dir: { type: "categorical" },
speed: { type: "quantitative", domain: [0, 30] },
},
elements: [ axisRadial({ channel: "radius", ticks: 3 }) ],
marks: [
arc({
innerRadius: 12, outerRadius: 120, padAngle: 2,
start: 112.5, end: -247.5, // clockwise, N centred at the top
fill: "#1B3F60", fillOpacity: 0.85,
channels: {
theta: { value: 1 }, // equal slices: the value lives on the radius
// sqrt: a slice's AREA grows with the value, not its radius.
radius: { field: "speed", scale: "sqrt", edit: move() },
},
}),
],
});
mount(chart.dom());
```
A `radius` channel replaces a per-donut `size` and sets one ring's extent. On a grid of donuts, every slot uses that extent.
---
# Waffle
> Source: https://elicitjs.github.io/marks/waffle/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A waffle shows a quantity per category as a block of countable **cells**. One cell is worth `unit` of the field, so `value / unit` cells fill, laid out `multiple` across the band. The `count` channel holds the value. Edit it with `edit.waffle.fill()`, which fills up to the cell under the pointer, so the value is always a whole number of cells.
## API reference
### `waffle(options) · waffleY(options) · waffleX(options)`
Import `plot` from `elicitjs`. `waffleY` grows blocks upward (category on x), `waffleX` rightward (category on y). Bare `waffle` reads the direction from the channel map: the category's axis is the band, and `count` runs along the other one.
JSON keyword: `plot.waffle`, `plot.waffleY`, `plot.waffleX`
```ts
waffleY({ channels, orientation, unit, multiple, shape, showEmpty, emptyFill, gap, edits, id }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | One band (category) axis — `x` or `y` — plus `count`, the magnitude. Put `edit: edit.waffle.fill()` on `count`; it fills up to the exact cell under the pointer, for both drag and click. |
| `image` | `string \| (d) => string \| ChannelSpec` | | The shape's background image: a URL painted inside each shape in place of the fill. Takes `fit`, `position` and `repeat` as channel params, as in CSS. See [Image](https://elicitjs.github.io/marks/image.md#settings). |
| `orientation` | `'vertical' \| 'horizontal'` | `from the channel map` | Which way the blocks grow. `waffleY` / `waffleX` set it; otherwise it follows the positional channel you bound. Same option `bar` takes. |
| `unit` | `number` | `1` | The quantity **one cell** represents. `value / unit` cells fill; raise it for large counts, lower it (>0) for fine fractions. |
| `multiple` | `number` | `auto` | Cells across the band. Defaults to whatever makes cells square given the band width and scale; each row then spans `multiple · unit`. |
| `shape` | `'square' \| 'circle'` | `'square'` | Cell shape: square cells or dots, as on `point`. A `symbol` channel draws a glyph in each cell instead. |
| `showEmpty` | `boolean` | `true` | Draw the unfilled cells (the value track). Set `false` to hide them; they stay as invisible drag targets, so dragging up to raise the count still works. |
| `emptyFill` | `string` | `'#eee'` | Colour of the unfilled cells when shown (filled cells use the standard style surface). |
| `gap` | `number` | `1` | Pixel gap between cells. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x / y` | `band` | The category axis. Bind one of them; the count runs along the other. |
| `count` | `linear` | The magnitude, in data units, on its own count axis — not on x or y. One cell is worth one unit of the field. |
| `xOffset / yOffset` | `band` | A second category nested inside the category axis: one block per value, side by side. |
Returns / emits: A **mark** emitting one cell node (`rect` or `circle`) per cell; every cell carries the datum, so the whole block is one drag/click target.
## Counting quantities
A waffle over four categories. Each cell is 10 fruit, so count the cells and multiply by the unit to read an amount.
### Example: Fruit counts
Static waffle; count domain 0–320, one cell = 10 fruit (32 cells), multiple picked automatically.
```javascript
const cats = ["apples","bananas","oranges","pears"];
const chart = Elicit({
width: 460, height: 300,
margins: { top: 16, right: 12, bottom: 28, left: 34 },
data: [
{ cat: "apples", value: 210 }, { cat: "bananas", value: 200 },
{ cat: "oranges", value: 310 }, { cat: "pears", value: 40 },
],
schema: {
cat: { type: "categorical", domain: cats },
value: { type: "quantitative", domain: [0, 320] },
},
scales: { x: { type: "band" } },
marks: [
waffleY({
fill: "#50AEB7",
channels: {
x: { field: "cat" },
count: { field: "value" },
},
unit: 10,
}),
],
});
mount(chart.dom());
```
## Picking a proportion
One category over a 0–1 domain. Each cell is 1/50, so 50 cells fill the block. Click or drag, and `edit.waffle.fill()` fills up to the cell under the pointer.
### Example: Proportion picker
click or drag; unit = 1/50 makes 50 countable cells, edit.waffle.fill lands exactly on the cell you point at.
Try: click a cell, or drag up/down.
```javascript
const chart = Elicit({
width: 220, height: 300,
margins: { top: 16, right: 12, bottom: 24, left: 34 },
data: [{ cat: "belief", value: 0.4 }],
onChange: (d) => console.log("proportion:", d[0].value.toFixed(2)),
schema: {
cat: { type: "categorical", domain: ["belief"] },
value: { type: "quantitative", domain: [0, 1] },
},
scales: { x: { type: "band" } },
marks: [
waffleY({
fill: "#2B5D87",
unit: 1/50,
channels: {
x: { field: "cat" },
count: { field: "value", edit: edit.waffle.fill() },
},
// click sets the count to the clicked cell too
edits: [ edit.waffle.fill({ channels: ["count"], gesture: "click" }) ],
}),
],
});
mount(chart.dom());
```
## Dots, click-to-set & hidden track
`shape: "circle"` draws a dot in each square cell. A `click` gesture sets the count to the clicked cell in one tap. `showEmpty: false` hides the empty cells, and they stay grabbable.
### Example: Click a dot to set the count
circle cells, one = 5; uniform dots pack tightly (gap: 0). Click any dot to fill up to and including it, or drag.
Try: click a dot, or drag up/down.
```javascript
const chart = Elicit({
width: 240, height: 300,
margins: { top: 16, right: 12, bottom: 24, left: 34 },
data: [{ cat: "count", value: 45 }],
onChange: (d) => console.log("count:", d[0].value),
schema: {
cat: { type: "categorical", domain: ["count"] },
value: { type: "quantitative", domain: [0, 100] },
},
scales: { x: { type: "band" } },
marks: [
waffleY({
fill: "#7DB86B",
shape: "circle",
unit: 5,
gap: 0,
channels: {
x: { field: "cat" },
count: { field: "value", edit: edit.waffle.fill() }, // drag to fill
},
edits: [ edit.waffle.fill({ channels: ["count"], gesture: "click" }) ], // click to set
}),
],
});
mount(chart.dom());
```
## Small counts (unit = 1)
With `unit: 1` each cell is one item, so small counts read directly. The grid is centred in the band and only as wide as it needs to be.
### Example: Tallies of 1–6
one cell = one item; counts of 1, 3, 6, 2 — count the cells directly.
```javascript
const cats = ["A","B","C","D"];
const chart = Elicit({
width: 460, height: 260,
margins: { top: 16, right: 12, bottom: 28, left: 28 },
data: [
{ cat: "A", value: 1 }, { cat: "B", value: 3 },
{ cat: "C", value: 6 }, { cat: "D", value: 2 },
],
schema: {
cat: { type: "categorical", domain: cats },
value: { type: "quantitative", domain: [0, 6] },
},
scales: { x: { type: "band" } },
marks: [
waffleY({
fill: "#F2B94B",
shape: "circle",
unit: 1,
gap: 0,
channels: { x: { field: "cat" }, count: { field: "value" } },
}),
],
});
mount(chart.dom());
```
## The count axis
A waffle's magnitude is the `count` channel, and it has its own **count axis**, separate from `y`. A waffle and a bar in one chart keep separate domains.
Ask for the axis with `axes: { count: true }`. The cells already make the count readable, so it is off by default. It reports data units, matching the column it reads.
One cell is worth `unit` of the field. With the default `unit: 1`, the column value is the number of cells. Pick a `unit` that divides the declared domain. Otherwise the top cell is a fraction and the mark logs a warning.
### Example: A count axis
axes: { count: true } — one cell is 10, so the 320 domain spans 32 cells.
```javascript
const cats = ["apples","bananas","oranges","pears"];
const chart = Elicit({
width: 460, height: 300,
margins: { top: 16, right: 12, bottom: 28, left: 44 },
// The count axis is opt-in: it reserves layout space for a scale these marks
// already make countable by eye, so it sits with `legends`, not with x/y.
axes: { count: true },
data: [
{ cat: "apples", value: 210 }, { cat: "bananas", value: 200 },
{ cat: "oranges", value: 310 }, { cat: "pears", value: 40 },
],
schema: {
cat: { type: "categorical", domain: cats },
value: { type: "quantitative", domain: [0, 320] },
},
scales: { x: { type: "band" } },
marks: [
waffleY({
fill: "#50AEB7",
channels: {
x: { field: "cat" },
// The magnitude is `count`, on a count axis of its own — not `y`.
count: { field: "value" },
},
unit: 10, // one cell is worth 10, so 320 spans 32 cells
}),
],
});
mount(chart.dom());
```
## Grouped waffles (xOffset, yOffset)
`xOffset` splits each category into one block per value of a second field, side by side. Each block keeps its own cells, so `edit.waffle.fill()` fills the block you point at. `yOffset` does the same for `waffleX`. The cells shrink to fit the narrower block.
### Example: A waffle per group
xOffset: { field: "sex" } gives each sport a block for women and one for men. One cell is 10 athletes.
Try: **Click** or **drag** in a block to set its count.
```javascript
const sports = ["rowing", "cycling", "judo"];
const chart = Elicit({
width: 420, height: 260,
margins: { top: 16, right: 12, bottom: 28, left: 28 },
data: sports.flatMap((sport) => [
{ sport, sex: "women", athletes: 40 },
{ sport, sex: "men", athletes: 40 },
]),
schema: {
sport: { type: "categorical", domain: sports },
sex: { type: "categorical", domain: ["women", "men"] },
athletes: { type: "quantitative", domain: [0, 200] },
},
marks: [
waffleY({
unit: 10,
channels: {
x: { field: "sport" },
xOffset: { field: "sex", scale: { padding: 0.15 } },
count: { field: "athletes", edit: edit.waffle.fill() },
fill: { field: "sex", legend: { anchor: "top", title: false } },
},
}),
],
});
mount(chart.dom());
```
## Orientation
Put the category on `y` and the blocks grow rightward. `waffleY` and `waffleX` set the direction. A bare `waffle` takes it from the channel map: the category's axis is the band, and `count` runs along the other. `orientation: "horizontal" | "vertical"` is the explicit form, the same option `bar` takes.
### Example: Blocks that grow rightward
waffleX with the category on y; the count axis sits at the bottom.
```javascript
const cats = ["apples","bananas","oranges","pears"];
const chart = Elicit({
width: 460, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 72 },
axes: { count: true },
data: [
{ cat: "apples", value: 210 }, { cat: "bananas", value: 200 },
{ cat: "oranges", value: 310 }, { cat: "pears", value: 40 },
],
schema: {
cat: { type: "categorical", domain: cats },
value: { type: "quantitative", domain: [0, 320] },
},
scales: { y: { type: "band" } },
marks: [
waffleX({
fill: "#50AEB7",
channels: {
// The category is on y, so the count runs along x.
y: { field: "cat" },
count: { field: "value" },
},
unit: 10,
}),
],
});
mount(chart.dom());
```
---
# Stacked dots
> Source: https://elicitjs.github.io/marks/dotstack/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`dotStack` draws a **dot histogram**: each row is one token, and tokens in the same slot stack into a countable column. Click an empty slot to add a token (`create`), and click a token to remove it (`remove`). The answer is the number of tokens in each slot: `data.filter(d => d.bin === b).length`.
## API reference
### `dotStack(options) · dotStackY(options) · dotStackX(options)`
Import `plot` from `elicitjs`. The category axis is a band/point scale over the discrete slots. `dotStackY` stacks upward (slots on x), `dotStackX` rightward (slots on y). Bare `dotStack` reads the direction from the channel map: the slot channel's axis is the category, and tokens stack along the other one.
JSON keyword: `plot.dotStack`, `plot.dotStackY`, `plot.dotStackX`
```ts
dotStack({ channels, orientation, size, gap, ghost, label, edits, id }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | A band/point category axis whose `domain` is the slot list. |
| `image` | `string \| (d) => string \| ChannelSpec` | | The shape's background image: a URL painted inside each shape in place of the fill. Takes `fit`, `position` and `repeat` as channel params, as in CSS. See [Image](https://elicitjs.github.io/marks/image.md#settings). |
| `orientation` | `'vertical' \| 'horizontal'` | `from the channel map` | Which way tokens stack. `dotStackY` / `dotStackX` set it; otherwise it follows the positional channel you bound. Same option `bar` and `waffle` take. |
| `size` | `number` | `7` | Token radius (fixed geometry — the stack offset is 2·size + gap per token). |
| `gap` | `number` | `2` | Gap between stacked tokens, along the stack direction. |
| `ghost` | `boolean` | `true` | Draw a faint open ring at each slot's next position (a droppable affordance). |
| `label` | `boolean` | `false` | Draw the per-slot count above each column. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x / y` | `band \| point` | The category (slot) axis; the other axis is a pure count of stacked tokens. |
Returns / emits: A **mark** emitting one `circle` per token, plus optional ghost rings and count labels.
## Dropping tokens
Click to drop a token into the nearest slot. Click a token to take it back. `count()` caps the budget.
### Example: Probability tokens over bins
A discrete point scale of bins 0–1; 25-token budget.
Try: **Click** the plane to add a token · **click** a dot to remove it.
```javascript
const bins = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1];
const chart = Elicit({
width: 560, height: 260,
margins: { top: 20, right: 16, bottom: 28, left: 16 },
axes: { x: {}, y: false },
data: [
{ bin: 0.3 }, { bin: 0.3 }, { bin: 0.3 },
{ bin: 0.4 }, { bin: 0.4 }, { bin: 0.5 },
],
onChange: (d) => console.log("tokens:", d.length),
schema: {
bin: { type: "categorical", domain: bins },
},
scales: { x: { type: "point" } },
constraints: [ count({ max: 25 }) ],
marks: [
dotStack({
channels: { x: { field: "bin" } },
edits: [ create({ gesture: "click", channels: ["x"] }), remove() ],
label: true,
}),
],
});
mount(chart.dom());
```
### Example: Tentative dot on hover (probe)
create({ pick: "probe" }) shows the token before it is real; the click commits it.
Try: **Hover** a bin to preview a dot · **click** to commit it · **Alt-click** a dot to remove it.
```javascript
const bins = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1];
const chart = Elicit({
width: 560, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 16 },
axes: { x: {}, y: false },
data: [],
schema: {
bin: { type: "categorical", domain: bins },
},
scales: { x: { type: "point" } },
constraints: [ count({ max: 20, strategy: "reject" }) ],
marks: [
dotStack({
id: "tokens",
channels: { x: { field: "bin" } },
edits: [
// Hover previews the drop; the click commits it. advance:false keeps the
// edit live so you can keep dropping tokens.
create({ pick: "probe", channels: ["x"], advance: false, when: when.noAlt }),
// The plane owns the pointer in probe mode, so removal picks the nearest.
remove({ pick: "nearest", when: when.alt }),
],
}),
],
});
mount(chart.dom());
const out = document.createElement("div");
out.style.cssText = "font:12px ui-monospace,monospace;color:#6F8294";
const show = () => { out.textContent = "committed tokens: " + chart.getData().length + " / 20"; };
chart.on("change", show); show();
mount(out);
```
### Example: Per-slot cap with unique
unique({ field, max }) limits the height of any one column.
```javascript
const cats = ["A","B","C","D"];
const chart = Elicit({
width: 420, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 16 },
axes: { x: {}, y: false },
data: [{ bin: "A" }, { bin: "B" }, { bin: "B" }],
schema: {
bin: { type: "categorical", domain: cats },
},
scales: { x: { type: "band" } },
constraints: [ unique({ field: "bin", max: 5, strategy: "reject" }) ],
marks: [
dotStack({
channels: { x: { field: "bin" } },
edits: [ create({ gesture: "click", channels: ["x"] }), remove() ],
label: true,
}),
],
});
mount(chart.dom());
```
## Orientation
Put the slots on `y` and tokens stack rightward instead of up. `dotStackY` and `dotStackX` force a direction. Bare `dotStack` takes it from the channels: the slot channel's axis holds the categories, and tokens stack along the other. `orientation: "horizontal" | "vertical"` sets it explicitly, as on `bar` and `waffle`.
### Example: Tokens that stack rightward
dotStackX with the slots on y; columns grow from the left edge.
Try: **Click** a row to add a token · **click** a token to remove it.
```javascript
const bins = ["never","rarely","sometimes","often","always"];
const chart = Elicit({
width: 460, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 84 },
data: [
{ bin: "rarely" }, { bin: "rarely" }, { bin: "sometimes" },
{ bin: "sometimes" }, { bin: "sometimes" }, { bin: "often" },
],
onChange: (d) => console.log("tokens:", d.length),
schema: { bin: { type: "ordinal", domain: bins } },
scales: { y: { type: "point" } },
marks: [
dotStackX({
size: 8,
fill: "#2B5D87",
// The category is on y, so tokens stack along x.
channels: { y: { field: "bin" } },
edits: [ create({ gesture: "click", channels: ["y"] }), remove() ],
}),
],
});
mount(chart.dom());
```
---
# Trend + Band
> Source: https://elicitjs.github.io/marks/trend/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`trend` elicits a **parametric line** from one row `{ intercept, slope }`, drawn as `y = intercept + slope·x` across the plot. An intercept handle at `anchor` (`x = 0` by default) moves the line up and down. A slope grip at each end rotates it about the anchor. `trendBand` draws the uncertainty around it: a range on the intercept, a range on the slope, and every line between them.
## API reference
### `trend(options)`
Import `plot` from `elicitjs`. A single-datum parametric line; the line itself is non-interactive and each handle is a draggable circle claimed by its own parameter.
JSON keyword: `plot.trend`
```ts
trend({ channels, anchor, grip, probe, handles, handleSize, handleColor, id }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `anchor` | `number` | `0 (if in x domain), else the first domain end` | x position of the intercept handle and the slope-rotation pivot. 0 is the classic y-intercept. |
| `grip` | `"end" \| "probe"` | `"end"` | Where the slope grips sit. end mounts a pair on the line's own ends, and a drag passes the line through the pointer — so it swings all the way round. probe pins one at x = probe, sliding vertically at that column, which caps the reachable slope at ySpan / (probe − anchor). |
| `probe` | `number` | `the other x-domain end` | The column a pinned slope grip sits at, under grip: "probe" only. Setting it under the default grip warns. |
| `handles` | `boolean \| "hit"` | `true with an edit` | Unset, the grips draw where an edit reaches the row. true always draws them, as ink on a trend with no edit. Turn them off with false when the line is driven from the plane. "hit" keeps them grabbable but invisible. |
| `handleSize` | `number` | `5` | Handle circle radius. |
| `handleColor` | `string` | `the mark's fill` | Handle circle paint. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x, y` | `field` | The plot's AXES, not columns of the datum. Declare their domains in the schema. |
| `intercept` | `field \| datum` | The line's value at x = 0. Unscaled — a parameter in its own units, projected through y. |
| `slope` | `field \| datum` | The line's slope, in y units per x unit. Unscaled. Pin either parameter with { datum: 0 } to make it a constant no edit can write. |
Returns / emits: A **mark** emitting the `line` (edge-to-edge through the plot) plus handle `circle`s tagged `intercept` / `slope` — one at the anchor, and one at each end of the line under the default grip. If the chart's `axes` is left unspecified, chart axes cross at the origin; state it explicitly with `axes: { origin: true | false }` either way.
### `trendBand(options)`
Import `plot` from `elicitjs`. The uncertainty around a parametric line: every line the belief’s ranges allow, drawn as one envelope, a stack of nested envelopes, or a fan of samples. Declares no edits of its own — put them on the mark the reader grabs.
JSON keyword: `plot.trendBand`
```ts
trendBand({ channels, render, levels, samples, seed, sigma, distribution, anchor, grip, probe, handles, handleSize, handleColor, id }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `"region" \| "gradient" \| "samples"` | `"region"` | One exact envelope polygon; nested envelopes stacked so the ink darkens toward the line; or individual sampled lines. |
| `levels` | `number` | `5` | gradient only — how many nested envelopes. Their opacities compound to fillOpacity at the centre. |
| `samples` | `number` | `60` | samples only — how many lines to draw from the family. |
| `seed` | `number` | `7` | samples only — PRNG seed, so the fan is stable across re-renders. |
| `distribution` | `"normal" \| "uniform"` | `"normal"` | samples only — normal treats the bounds as a sigma-wide envelope; uniform spreads flat across them. |
| `sigma` | `number` | `1.96` | The envelope half-width in standard deviations when sampling normally, so ~95% of draws land inside the band that was pointed at. |
| `grip` | `"end" \| "probe"` | `"end"` | As trend — end mounts the slopeSpread grips on the ends of the band's own upper edge, so opening the cone is not capped by how far one pinned column reaches. |
| `handles` | `boolean \| "hit"` | `true with an edit` | A grip on each spread: the intercept's at the anchor, the slope's on the upper edge (see grip). As on trend: unset, they draw where an edit reaches the row; false hides them; "hit" keeps them grabbable but invisible. |
| `handleSize` | `number` | `5` | Handle circle radius. |
| `handleColor` | `string` | `theme` | Handle circle paint. |
| `fillOpacity` | `number` | `0.18` | region / gradient — the ink of the filled envelope. Gradient divides it across levels so the stack compounds back to it. |
| `strokeOpacity` | `number` | `0.15` | samples — the ink of ONE line in the fan, so raising samples darkens the overlap and lowering this thins it back out. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x, y, intercept, slope` | | As trend — the axes, and the line the band surrounds. |
| `interceptSpread, slopeSpread` | `field` | HALF-WIDTHS in the field's own units: the symmetric form, and what one pointer distance sets. |
| `intercept1 / intercept2, slope1 / slope2` | `field` | Explicit asymmetric ranges, the same 1/2 span spelling area and rect use. These win wherever both forms are declared. |
Returns / emits: A **mark** emitting one `path` (region), `levels` paths (gradient), or `samples` `line`s — all inert and painted in the background layer — plus the optional spread handles.
### `edit.trend.*`
The trend-scoped edits. Each inverts the pointer through `x`/`y` and solves for the parameter it owns, writing the column that parameter’s channel names. A pinned parameter is never written.
JSON keyword: `edit.trend.intercept`, `edit.trend.slope`, `edit.trend.interceptSpread`, `edit.trend.slopeSpread`
```ts
edit.trend.intercept({ anchor, probe, ...EditOptions }) → Edit
edit.trend.slope({ anchor, probe, ...EditOptions }) → Edit
edit.trend.interceptSpread({ anchor, probe, ...EditOptions }) → Edit
edit.trend.slopeSpread({ anchor, probe, ...EditOptions }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `anchor` | `number` | `the mark's anchor` | The pivot: the x whose value a rotation holds, and where an intercept drag places the line. |
| `probe` | `number` | `the mark's probe` | The x a PINNED handle drag measures at (one drawn under grip: "probe"). An end-mounted grip, and a gesture carrying no node at all (a plane or probe pick), use the pointer's own x instead, so the line follows the cursor. |
Returns / emits: An **Edit** with `scope: "trend"`, claiming the handle tagged with its own channel. `trend()` generates the first two for you; declare them yourself to restage them, retarget them, or drive them from the plane.
## Its channels name the axes, not the columns
A trend's `x` and `y` channels name the plot's **axes**, not columns of its row. Declare their domains in the schema. Domains that span both sides of zero put the intercept in the middle of the frame.
When `axes` is unset, a chart with a trend crosses its axes at the origin. Set `axes: { origin: true | false }` to state the frame yourself. `origin: false` gives the ordinary left/bottom frame. See [Axis, Grid & Rule](https://elicitjs.github.io/marks/axes.md#global).
## Trend can't be created by a gesture
A trend line is **parametric**. Its position comes from `intercept` and `slope`, and a click has no `x`/`y` to invert into them, so a plane `create` can't add one. See the [create matrix](https://elicitjs.github.io/editing/existence.md#what-can-create). Set a trend by editing its parameters.
## Inert until an edit names the column
`trend()` with no edit draws the line without handles and writes nothing. Like every mark, it stays a view until an `edit` names the column a gesture sets: `edit.trend.intercept()` on the intercept channel, `edit.trend.slope()` on the slope channel. Set a stage on the edit, as elsewhere: `edit.trend.slope({ stage: 1 })`.
### Example: No edit, no writes
The line draws without handles, and the data never moves.
Try: drag the line. Nothing changes.
```javascript
const chart = Elicit({
width: 360, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
schema: {
x: { type: "quantitative", domain: [-10, 10] },
y: { type: "quantitative", domain: [-10, 10] },
intercept: { type: "quantitative" },
slope: { type: "quantitative" },
},
data: [{ intercept: 2, slope: 0.5 }],
marks: [
// No edit anywhere: the line draws without handles, and nothing you do to
// it changes the data. A mark is a VIEW until an edit names the column a
// gesture writes — trend is no exception, and used to be.
trend({
channels: {
intercept: { field: "intercept" },
slope: { field: "slope" },
},
}),
],
});
mount(chart.dom());
```
## Intercept, then slope
Stage 0: drag the intercept handle to set the level. Stage 1: drag either end grip to set the slope, rotating the line about the anchor.
The parameters are channels. Rename a column with `channels: { slope: { field: "r" } }`, or pin it to a constant with `{ datum }`. They are unscaled: each stays in its own units and is projected through `x` and `y`.
### Example: Trend line
Axes cross at the origin automatically; the line runs edge-to-edge through the plot.
Try: drag the centre (intercept) dot; press Next; drag an end dot.
```javascript
const chart = Elicit({
width: 360, height: 300,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
schema: {
x: { type: "quantitative", domain: [-10, 10] },
y: { type: "quantitative", domain: [-10, 10] },
intercept: { type: "quantitative" },
slope: { type: "quantitative" },
},
data: [{ intercept: 0, slope: 0.6 }],
marks: [
// A trend draws its line and two handles, but writes nothing until an edit
// names the column each handle sets. Staging goes on the edit, like any other:
// the intercept is live in stage 0, the slope in stage 1.
trend({
channels: {
intercept: { field: "intercept", edit: edit.trend.intercept({ stage: 0 }) },
slope: { field: "slope", edit: edit.trend.slope({ stage: 1 }) },
},
}),
],
});
mount(chart.dom());
const btn = document.createElement("button");
btn.textContent = "Next: set the slope";
btn.style.marginTop = "8px";
btn.onclick = () => { chart.nextStage(); btn.disabled = true; };
mount(btn);
```
### Example: Both handles at once
Omit the stages (default null) to leave both handles always active.
```javascript
const chart = Elicit({
width: 360, height: 300,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
schema: {
x: { type: "quantitative", domain: [-10, 10] },
y: { type: "quantitative", domain: [-10, 10] },
intercept: { type: "quantitative" },
slope: { type: "quantitative" },
},
data: [{ intercept: 2, slope: 0.5 }],
marks: [
// Unstaged: both handles live at once. Each edit claims its own handle, so
// dragging the intercept never moves the slope and vice versa.
trend({
channels: {
intercept: { field: "intercept", edit: edit.trend.intercept() },
slope: { field: "slope", edit: edit.trend.slope() },
},
}),
],
});
mount(chart.dom());
```
`axes` moves only the axis spines. The handles follow `anchor` and `probe`. `anchor` is 0 when 0 lies in the x domain, and the domain's start otherwise. Over a domain starting at 0 or above, that puts the intercept handle on a left/bottom y-axis. Pair it with `grip: "probe"` for a single slope handle at the domain's far end. The default pair of grips would put one on top of the intercept handle.
### Example: Left/bottom frame
axes: { origin: false }, plus a domain starting at 0 and grip: "probe" — the intercept handle sits on the y-axis, the one slope handle on the right edge.
```javascript
const chart = Elicit({
width: 360, height: 300,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
// Without this, axes here would still cross at zero — a trend mark is
// present and axes was otherwise unspecified. origin: false states the
// ordinary left/bottom frame explicitly instead of leaving it inferred.
axes: { origin: false },
schema: {
// A domain that doesn't need to span negative values, so trend's default
// anchor (0, whenever 0 lies in the x domain — here that's the domain's
// own start) lands exactly where the y-axis is drawn, instead of
// floating mid-plot the way it would over a domain like [-10, 10].
x: { type: "quantitative", domain: [0, 20] },
y: { type: "quantitative", domain: [0, 20] },
intercept: { type: "quantitative" },
slope: { type: "quantitative" },
},
data: [{ intercept: 2, slope: 0.5 }],
marks: [
trend({
// grip: "probe" mounts a single slope handle at the domain's far end.
// The default pair (grip: "end") would put its near-end grip on the
// same point as the intercept handle now that anchor sits at x = 0.
grip: "probe",
channels: {
intercept: { field: "intercept", edit: edit.trend.intercept() },
slope: { field: "slope", edit: edit.trend.slope() },
},
}),
],
});
mount(chart.dom());
```
## Rotating the line
The slope grips sit on the line’s ends. Dragging one passes the line through the pointer, so the line rotates a full turn: drag an end up and over the anchor, and the line swings past vertical and down the other side. Both ends carry the same edit, and each stays inside the plot at every angle.
A vertical line has no slope. The gesture holds while the pointer is in the anchor’s column, and `slope` grows without bound as you approach it. Bound it with a `clamp` on the column, as for any field.
`grip: "probe"` pins a single grip at `x = probe` instead, sliding vertically at that column. Reachable slope is then capped at `ySpan / (probe − anchor)`.
### Example: Swing it round
Both parameters live, with slope clamped to ±20.
Try: drag an end dot up and across the middle of the plot — the line keeps turning.
```javascript
const chart = Elicit({
width: 340, height: 300,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
schema: {
x: { type: "quantitative", domain: [-10, 10] },
y: { type: "quantitative", domain: [-10, 10] },
intercept: { type: "quantitative" },
slope: { type: "quantitative" },
},
data: [{ intercept: 0, slope: 0.6 }],
// The slope grows without bound as the line approaches vertical. Bound it the
// same way you bound any other column.
constraints: [clamp({ field: "slope", min: -20, max: 20 })],
marks: [
trend({
channels: {
intercept: { field: "intercept", edit: edit.trend.intercept() },
slope: { field: "slope", edit: edit.trend.slope() },
},
}),
],
});
mount(chart.dom());
const out = document.createElement("div");
out.style.cssText = "font:12px ui-monospace,monospace;margin-top:6px;color:#6F8294";
const show = () => {
const d = chart.getData()[0] || {};
out.textContent = "intercept " + d.intercept.toFixed(2) +
" slope " + d.slope.toFixed(2);
};
chart.on("change", show); show();
mount(out);
```
## The band around the line
`trendBand` takes the same two parameters plus a **spread** on each: `interceptSpread` and `slopeSpread`, half-widths in the field’s own units. It draws every line those ranges allow. The envelope is exact: piecewise linear, with one kink where `x` crosses zero and only the intercept range is left.
The two marks are views of one dataset. Put a plane or probe edit on the band or on the line, not both, or it runs twice per gesture. The band's spread channels take `edit.trend.interceptSpread()` and `edit.trend.slopeSpread()`, shown below.
### Example: A band around the line
Every line whose intercept is within aSd and whose slope is within bSd.
```javascript
const chart = Elicit({
width: 360, height: 300,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
schema: {
x: { type: "quantitative", domain: [-10, 10] },
y: { type: "quantitative", domain: [-10, 10] },
// The band's four elicited columns. Every column of the dataset belongs in
// the schema — that is the contract of what this chart elicits.
intercept: { type: "quantitative" },
slope: { type: "quantitative" },
aSd: { type: "quantitative" },
bSd: { type: "quantitative" },
},
data: [{ intercept: 1, slope: 0.4, aSd: 1.5, bSd: 0.25 }],
marks: [
trendBand({
fill: "#50AEB7",
channels: {
interceptSpread: { field: "aSd" },
slopeSpread: { field: "bSd" },
},
}),
// Drag either handle to move the line; the band above re-derives from the same
// two parameters, so it follows without carrying an edit of its own.
trend({
stroke: "#50AEB7",
channels: {
intercept: { field: "intercept", edit: edit.trend.intercept() },
slope: { field: "slope", edit: edit.trend.slope() },
},
}),
],
});
mount(chart.dom());
```
For an asymmetric band, name the ends instead: `intercept1`/`intercept2` and `slope1`/`slope2`, the same `1`/`2` spelling [`area`](https://elicitjs.github.io/marks/area.md#band) and `rect` use. Where both forms are declared, the range form wins. Pair it with `ordering` to keep the ends in order.
### Example: Editing the band
The spread edits put a grab on each spread: the intercept's at the anchor, the slope's on the ends of the band's upper edge.
Try: drag either band handle, then drag the line's own handles underneath.
```javascript
const chart = Elicit({
width: 360, height: 300,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
schema: {
x: { type: "quantitative", domain: [-10, 10] },
y: { type: "quantitative", domain: [-10, 10] },
intercept: { type: "quantitative" },
slope: { type: "quantitative" },
aSd: { type: "quantitative" },
bSd: { type: "quantitative" },
},
data: [{ intercept: 1, slope: 0.4, aSd: 2, bSd: 0.3 }],
marks: [
// The band is a VIEW. It draws the spreads; the handles below write them.
trendBand({
fill: "#8A78C0",
channels: {
interceptSpread: { field: "aSd", edit: edit.trend.interceptSpread() },
slopeSpread: { field: "bSd", edit: edit.trend.slopeSpread() },
},
}),
trend({
stroke: "#8A78C0",
channels: {
intercept: { field: "intercept", edit: edit.trend.intercept() },
slope: { field: "slope", edit: edit.trend.slope() },
},
}),
],
});
mount(chart.dom());
```
## Three readings of one band
`render` sets how the family is drawn. `region` (the default) is one polygon: the exact envelope. `gradient` stacks `levels` nested envelopes, so the ink darkens toward the line. `samples` draws individual lines from the family. Its `distribution` is `normal` (the bounds are a `sigma`-wide envelope, so about 95% of draws land inside) or `uniform` (every line in the range equally likely).
The filled forms use `fillOpacity` (default `0.18`). `samples` uses `strokeOpacity` (default `0.15`) for each line, so the fan gets denser as you raise `samples`. Lower `strokeOpacity` to thin it out.
### Example: region, gradient, samples
One band, three renderings of the same answer.
```javascript
const belief = [{ intercept: 1, slope: 0.4, aSd: 1.5, bSd: 0.25 }];
const spreads = { interceptSpread: { field: "aSd" }, slopeSpread: { field: "bSd" } };
const lineParams = {
intercept: { field: "intercept", edit: edit.trend.intercept() },
slope: { field: "slope", edit: edit.trend.slope() },
};
for (const render of ["region", "gradient", "samples"]) {
mount(Elicit({
width: 200, height: 170,
margins: { top: 10, right: 10, bottom: 22, left: 26 },
schema: {
x: { type: "quantitative", domain: [-10, 10] },
y: { type: "quantitative", domain: [-10, 10] },
intercept: { type: "quantitative" },
slope: { type: "quantitative" },
aSd: { type: "quantitative" },
bSd: { type: "quantitative" },
},
data: belief,
marks: [
trendBand({ render, levels: 6, samples: 80, fill: "#1B3F60", stroke: "#1B3F60", channels: spreads }),
// Three renderings of the SAME belief, so all three share one edit set.
trend({ stroke: "#1B3F60", channels: lineParams }),
],
}).dom());
}
```
## A correlation is a pinned trend
To elicit a correlation, pin the intercept at the origin and limit the slope to `[-1, 1]`. Pin with a constant channel, `intercept: { datum: 0 }`, which names no column, so no edit writes it. Limit with a `clamp`.
Stage 0 aims the line. Under [`probe`](https://elicitjs.github.io/editing/probe.md) the line follows the pointer's `x`, and a click sets it and advances. Stage 1 opens the band: `slopeSpread` is how far the line through the pointer tilts from the committed one, so the fan's edge sits under the cursor.
Both axes span `[-1, 1]` over a square plot, so the line's screen angle reads as `r`. This interface ships as [`widgets.lineCone`](https://elicitjs.github.io/widgets.md#linecone).
### Example: Line + Cone, from the general marks
Two clicks: aim the line, then open the cone.
Try: move the mouse, click, move again, click.
```javascript
const chart = Elicit({
width: 300, height: 300,
margins: { top: 14, right: 14, bottom: 14, left: 14 },
axes: false,
schema: {
// Standardized units, matched on both axes, so a slope of 1 is a 45° line.
x: { type: "quantitative", domain: [-1, 1] },
y: { type: "quantitative", domain: [-1, 1] },
r: { type: "quantitative", domain: [-1, 1], default: 0 },
spread: { type: "quantitative", domain: [0, 1], default: 0 },
},
data: [{ r: 0, spread: 0 }],
// What makes it a CORRELATION rather than a free trend — declared, not baked in.
constraints: [
clamp({ field: "r", min: -1, max: 1 }),
clamp({ field: "spread", min: 0, max: 1 }),
],
marks: [
trendBand({
render: "samples",
samples: 80,
channels: {
intercept: { datum: 0 }, // pinned at the origin
slope: { field: "r" },
slopeSpread: { field: "spread" },
},
}),
trend({
handles: false,
stroke: "#F2B94B",
strokeWidth: 5,
channels: {
intercept: { datum: 0 },
slope: { field: "r", edit: edit.trend.slope({ pick: "probe", stage: 0 }) },
slopeSpread: { field: "spread", edit: edit.trend.slopeSpread({ pick: "probe", stage: 1 }) },
},
}),
],
});
mount(chart.dom());
const out = document.createElement("div");
out.style.cssText = "font:12px ui-monospace,monospace;margin-top:6px;color:#6F8294";
const show = () => {
const d = chart.getData()[0] || {};
out.textContent = "stage " + chart.getStage() +
" · r=" + (d.r ?? 0).toFixed(2) + " spread=" + (d.spread ?? 0).toFixed(2);
};
chart.on("change", show); chart.on("stage", show); show();
mount(out);
```
---
# Needle
> Source: https://elicitjs.github.io/marks/needle/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`needle` draws a tapered pointer and hub for a gauge or dial. Its value is on the `theta` channel, and the `theta` scale's `range` sets the sweep in degrees: the default `[180, 0]` runs left to right through the top. A companion `axisRadial` draws the same `theta` scale, so give it the needle's range. `x`/`y` place the pivot, for many small needles in one chart.
## API reference
### `needle(options)`
Import `plot` from `elicitjs`. One needle (+ hub) per datum.
JSON keyword: `plot.needle`
```ts
needle({ channels, length, handles, handleSize, handleColor, baseWidth, tipWidth, id }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | Must include `theta` — the polar angular position. (`angle` is a mark’s rotation in place and is not read here.) Optional `x`/`y` place the pivot (default: plot centre). |
| `length` | `number` | `40% of min(w,h)` | Needle length in px. Or drive via the `size` channel. |
| `handles` | `boolean \| 'hit'` | `true` | The hub always draws. `true` paints it as a handle. `false` or `'hit'` paints it in the needle’s own fill and stroke. |
| `handleSize` | `number` | `5` | Hub circle radius in px. The hub is the needle's handle. |
| `handleColor` | `string` | `theme` | Hub fill. Defaults to the theme’s `handle` colour. |
| `baseWidth` | `number` | `10` | Width of the needle base in px. |
| `tipWidth` | `number` | `0` | Width of the needle tip in px. `0` tapers to a point. Set it equal to `baseWidth` for a bar of even width, such as a limb you grab far from its pivot. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `theta` | `linear \| point (deg)` | The elicited value, mapped to degrees by its scale. Default range `[180, 0]`. |
| `x / y` | `linear \| point` | Optional pivot position — categorical or quantitative. |
| `fill / stroke` | `style` | Needle colour. |
Returns / emits: A **mark** emitting a filled needle `path` and hub `circle` per datum.
## Semicircle gauge + centre text
A gauge combines `axisRadial` for the ticks, `needle`, and `text`. The default range `[180, 0]` puts 0 on the left and the maximum on the right.
### Example: Quantitative gauge
Domain [0, 100] maps to [180°, 0°] (left → right). Drag the needle.
Try: **Drag** the needle left or right.
```javascript
const chart = Elicit({
width: 320, height: 200,
margins: { top: 24, right: 16, bottom: 16, left: 16 },
axes: false,
data: [{ n: 62 }],
schema: { n: { type: "quantitative", domain: [0, 100] } },
marks: [
composite({
id: "gauge",
parts: [
axisRadial({
outerRadius: 100, ticks: 5,
channels: { theta: { field: "n", scale: { range: [180, 0] } } },
}),
needle({
length: 90, fill: "#50AEB7",
channels: {
theta: {
field: "n",
scale: { range: [180, 0] },
edit: rotate({ pivot: "mark", fold: false, pick: "direct" }),
},
},
}),
text({
fontSize: 22, dy: 28,
format: ".0f",
channels: {
text: { field: "n" },
textAnchor: { value: "middle" },
lineAnchor: { value: "middle" },
},
}),
],
}),
],
});
mount(chart.dom());
```
### Example: Right-facing
Same data; the needle and axisRadial share the theta range [-90, 90].
```javascript
const chart = Elicit({
width: 240, height: 280,
margins: { top: 16, right: 28, bottom: 16, left: 16 },
axes: false,
data: [{ n: 62 }],
schema: { n: { type: "quantitative", domain: [0, 100] } },
marks: [
axisRadial({
outerRadius: 100, ticks: 5,
channels: { theta: { field: "n", scale: { range: [-90, 90] } } },
}),
needle({
length: 90, fill: "#50AEB7",
channels: {
theta: {
field: "n",
scale: { range: [-90, 90] },
edit: rotate({ pivot: "mark", fold: false, pick: "direct" }),
},
},
}),
],
});
mount(chart.dom());
```
## Many needles on x × y
Each row is a pivot: `x` is categorical, `y` quantitative, and `theta` a third numeric answer. Drag a needle to write that row only.
### Example: Small needles in a scatter of pivots
Group on x, layer on y, answer on theta. Cartesian axes frame the pivots.
Try: **Drag** any small needle to change that cell’s answer.
```javascript
const chart = Elicit({
width: 420, height: 280,
margins: { top: 16, right: 16, bottom: 36, left: 40 },
data: [
{ g: "A", layer: 1, belief: 35 },
{ g: "B", layer: 1, belief: 62 },
{ g: "C", layer: 1, belief: 48 },
{ g: "A", layer: 2, belief: 70 },
{ g: "B", layer: 2, belief: 44 },
{ g: "C", layer: 2, belief: 81 },
],
schema: {
g: { type: "categorical", domain: ["A", "B", "C"] },
layer: { type: "quantitative", domain: [0.5, 2.5] },
belief: { type: "quantitative", domain: [0, 100] },
},
axes: {
x: { title: "group" },
y: { title: "layer", ticks: 2 },
},
marks: [
// A mini radial axis rings each pivot, so every needle shows the 0→100 span
// it encodes. Same x/y channels as the needle → one ring per row.
axisRadial({
outerRadius: 22, ticks: 0, tickSize: 0, tickPadding: 6, fontSize: 7,
stroke: "#BCC9D4",
channels: {
x: { field: "g" },
y: { field: "layer" },
theta: { field: "belief", scale: { range: [180, 0] } },
},
}),
needle({
length: 24, handleSize: 3, baseWidth: 6,
channels: {
x: { field: "g" },
y: { field: "layer" },
theta: {
field: "belief",
scale: { range: [180, 0] },
edit: rotate({ pivot: "mark", fold: false, pick: "direct" }),
},
fill: { field: "g" },
},
}),
],
});
mount(chart.dom());
```
## Full-circle dial
For a full 360° knob, set the `theta` range to `[-180, 180]` on the needle and on `axisRadial`. `rotate({ fold: false })` lets the needle travel the whole circle.
### Example: Quantitative dial
Rotate anywhere around the hub.
Try: **Drag** around the dial.
```javascript
const chart = Elicit({
width: 280, height: 280,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
data: [{ n: 0.35 }],
schema: { n: { type: "quantitative", domain: [0, 1] } },
marks: [
axisRadial({
outerRadius: 95, ticks: 8,
channels: { theta: { field: "n", scale: { range: [-180, 180] } } },
}),
needle({
length: 80, fill: "#20555A",
channels: {
theta: {
field: "n",
scale: { range: [-180, 180] },
edit: rotate({ pivot: "mark", fold: false, pick: "direct" }),
},
},
}),
text({
fontSize: 18, format: ".0%",
channels: {
text: { field: "n" },
textAnchor: { value: "middle" },
lineAnchor: { value: "middle" },
},
}),
],
});
mount(chart.dom());
```
## Ableton-style knob
A software knob is a [composite](https://elicitjs.github.io/marks/composite.md) of a ring (a dark track and a value fill) and a thin `needle` on the same `theta` scale. `arc` and `donut` divide a total among rows, but a knob's fill is one value swept from the arc's start, so the ring is a small custom mark built on `authoring.arcPath`. The needle carries `rotate({ pivot: "mark", fold: false, pick: "direct" })`. The ring has no edit and re-derives as you drag.
The span is a 270° arc with a gap at the bottom: `start: 225` (about 7 o'clock) to `end: -45` (about 5 o'clock). Set the needle's `scale.range` to the same span.
### Example: Compress knob
Ring fill + needle over one quantitative field. Drag the needle — the cyan slice follows.
Try: **Drag** the needle around the ring.
```javascript
// Ableton-style knob: a donut-slice ring (track + value fill) plus a needle.
// The ring is a tiny mark over authoring.arcPath; the needle carries rotate().
// Stock arc/donut partition a total among rows — a knob's fill is one value
// swept from the arc's start, so the ring is a short authoring mark instead.
const START = 225; // ~7 o'clock
const END = -45; // ~5 o'clock — 270° clockwise through the top
function knobArc(options = {}) {
const opts = authoring.normalizeMarkOptions(options, {
mark: "knobArc",
allow: ["outerRadius", "innerRadius", "start", "end", "track"],
});
const {
channels = {},
outerRadius = 90,
innerRadius = 78,
start = START,
end = END,
track = "#14283A",
} = opts;
return {
...authoring.markCommon(opts),
type: "knobArc",
channels,
build(data, scales, width, height) {
const cx = width / 2, cy = height / 2;
return data.flatMap((d, i) => {
const deg = authoring.encodeAngle(scales, channels, d, start, i, data);
const style = authoring.resolveStyle(
scales, channels, d, { fill: "#2B5D87" }, i, data,
);
const nodes = [];
const trackD = authoring.arcPath(cx, cy, outerRadius, start, end, { innerRadius });
if (trackD) {
nodes.push({
type: "path", d: trackD, fill: track, stroke: "none",
data: d, index: i, pointerEvents: "none",
});
}
const fillD = authoring.arcPath(cx, cy, outerRadius, start, deg, { innerRadius });
if (fillD) {
nodes.push({
type: "path", d: fillD, ...style, stroke: "none",
data: d, index: i, pointerEvents: "none",
});
}
// Max tick — the small end-cap Ableton puts at 5 o'clock.
const tip = authoring.polarToXY(cx, cy, (outerRadius + innerRadius) / 2, end);
nodes.push({
type: "circle", cx: tip.x, cy: tip.y, r: 2.5,
fill: track, stroke: "none",
data: d, index: i, pointerEvents: "none",
});
return nodes;
});
},
};
}
const chart = Elicit({
width: 260, height: 280,
margins: { top: 40, right: 24, bottom: 44, left: 24 },
axes: false,
theme: { background: "#14283A", ink: "#94A5B3" },
data: [{ level: 25 }],
schema: { level: { type: "quantitative", domain: [0, 100] } },
marks: [
composite({
id: "knob",
parts: [
text({
fontSize: 13, dy: -108,
channels: {
text: { value: "Compress" },
fill: { value: "#94A5B3" },
textAnchor: { value: "middle" },
lineAnchor: { value: "middle" },
},
}),
knobArc({
outerRadius: 88, innerRadius: 76,
start: START, end: END,
track: "#14283A",
channels: {
theta: { field: "level", scale: { range: [START, END] } },
fill: { value: "#2B5D87" },
},
}),
needle({
length: 70, baseWidth: 2.5,
handles: "hit",
fill: "#14283A", stroke: "#14283A",
channels: {
theta: {
field: "level",
scale: { range: [START, END] },
edit: rotate({ pivot: "mark", fold: false, pick: "direct" }),
},
},
}),
text({
fontSize: 14, dy: 108,
format: (v) => `${Math.round(v)} %`,
channels: {
text: { field: "level" },
fill: { value: "#94A5B3" },
textAnchor: { value: "middle" },
lineAnchor: { value: "middle" },
},
}),
],
}),
],
});
mount(chart.dom());
```
## Categorical needle
A discrete `theta` field uses a point scale, so a drag snaps to the nearest category. `axisRadial({ bands: true })` draws the coloured bands.
### Example: Likelihood gauge
Seven ordered categories across a top-facing arc.
Try: **Drag** the needle across categories.
```javascript
const chart = Elicit({
width: 360, height: 220,
margins: { top: 40, right: 70, bottom: 20, left: 70 },
axes: false,
// Let the long band labels ("VERY LIKELY D" …) spill into the margin instead of
// being clipped by the plot edge.
overflow: "visible",
data: [{ chance: "LEANING D" }],
schema: {
chance: {
type: "ordinal",
domain: ["VERY LIKELY D", "LIKELY D", "LEANING D", "TOSSUP",
"LEANING R", "LIKELY R", "VERY LIKELY R"],
},
},
marks: [
axisRadial({
outerRadius: 110, bands: true, bandWidth: 22,
tickSize: 0, tickPadding: 18, fontSize: 8,
channels: {
theta: { field: "chance", scale: { range: [180, 0] } },
// ColorBrewer RdBu is red→blue; reverse so D (left) is blue and R (right)
// is red — a proper 7-class diverging categorical palette.
fill: { field: "chance", scale: { scheme: "dddiverging", reverse: true } },
},
}),
needle({
length: 95, fill: "#EE7B5E",
channels: {
theta: {
field: "chance",
scale: { range: [180, 0] },
edit: rotate({ pivot: "mark", fold: false, pick: "direct" }),
},
},
}),
text({
fontSize: 14, dy: 32,
channels: {
text: { field: "chance" },
textAnchor: { value: "middle" },
lineAnchor: { value: "middle" },
},
}),
],
});
mount(chart.dom());
```
---
# Composite
> Source: https://elicitjs.github.io/marks/composite/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A composite is a glyph: a group of ordinary marks, its `parts`, over the same rows of the dataset. Each part encodes some fields, and a part whose channel carries an `edit` is a handle. Give a part a `frame:` channel and the composite becomes a box that its parts sit inside.
## API reference
### `composite(options)`
A glyph: a group of marks over the shared dataset. Import `plot` from `elicitjs`. Returns an **array of marks**, which `Elicit` flattens into its `marks` list. In **box mode** — switched on by a part stating a `frame:` channel — the composite’s own `x` / `y` / `size` place and size a per-row box, and the parts are placed inside it.
JSON keyword: `plot.composite`
```ts
composite({ parts, channels, edits, discreteScale, id }) → Mark[]
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `parts` | `Mark[]` | `[]` | The sub-marks, in z-order (later parts paint on top — visual parts first, handles last). Each part is an ordinary mark with its **own** `channels` / style shorthands (arm geometry, per-part stroke, a tip’s `size`). A part with an `edit` is a handle; a part without one is inert and the engine makes it `pointerEvents:"none"` so it can’t swallow a sibling’s drag. |
| `channels` | `object` | `{}` | Shared channel map merged into every part. Use it for glyph-wide bindings (`x`/`y`/`angle`/`fill`). A part’s own channel for the same name **wins** (shallow replace). Inherited `edit`s land on the last part only. In **box mode** `x` / `y` / `size` are withheld — they define the box, not each part’s position — and everything else still trickles. |
| `fill, angle, …` | `shorthand` | | Constant shorthands desugared into **composite** channels (shared by every part unless a part overrides). Parts keep their own shorthands too — e.g. a composite `angle`, per-part `stroke`. |
| `edits` | `Edit[]` | | Mark-level edits. They ride the **last** part — one dataset, so a whole-dataset edit declared on every part would fire once per part. In box mode they ride the **box**, whose channel map holds the glyph’s placement columns. |
| `discreteScale` | `'band' \| 'point'` | `'band'` | Stamped onto any part that doesn’t declare its own. A glyph usually sits in a band slot. |
| `id` | `string` | `'composite'` | Prefix for the parts’ generated ids (`id/0`, `id/1`, …), so each part keeps a stable identity across renders. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `frame: -0.4 (on x / y)` | `local position` | Local range `[-1, 1]` from the box’s centre, **y up** — so `{ frame: -0.4 }` is 40% of the way to the left edge. A local part that states **no** x/y sits at the origin, so parts never repeat the composite’s own position. Long form: `{ datum: -0.4, scale: "frame" }`. |
| `frame: 1 (on size / rx / ry / strokeWidth)` | `local magnitude` | Local range `[0, 1]`: a fraction of the box’s half-size, so the part scales with the glyph. |
| `frame: [lo, hi] (with a field)` | `field → box` | Maps the field’s **schema domain** onto that slice of the box. The range is on the channel, the domain on the schema — the same division as everywhere else. Long form: `scale: { type: "frame", range: […] }`. |
| `frame: [lo, hi] (with a categorical field)` | `categories → stops` | A `categorical` or `ordinal` field spreads its categories evenly from `lo` to `hi`, the first category at `lo`. An edit on the channel snaps to the nearest category. |
| `{ fn, frame: true }` | `derived local` | `fn(d)` returns local units, the same units as `{ frame: -0.4 }`. Use it to place a part where another part’s value puts it: a forearm at the end of an upper arm. It writes nothing, so it carries no edit. |
| `frame on angle / curvature` | `private scale` | No local box — the units are the channel’s own (degrees, half-chords). The scale is still per part, which is how two mirrored parts get opposite ranges without colliding on a global axis. |
Returns / emits: An **array of marks** — the parts, with ids assigned, composite channels merged in. In box mode the array is led by the **box**, which carries the composite’s x/y/size and covers the whole glyph — so a `move()` / `resize()` on those channels picks the glyph up from anywhere on it. Nothing about the glyph reaches the engine: it sees ordinary marks reading the one dataset.
## Lollipop
A lollipop is a stem plus a draggable tip. The stem is a `ruleX` spanning the baseline to the value. It carries no edit, so it is inert. The tip is a `point` that edits `value`. Drag a tip and its stem re-derives, because both marks read the same row.
### Example: One editable field (the tip)
The stem is a span ruleX (baseline → value); the tip point edits value.
Try: **Drag** a lollipop tip up or down.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ g: "A", value: 40 }, { g: "B", value: 62 },
{ g: "C", value: 48 }, { g: "D", value: 75 },
],
schema: {
g: { type: "categorical" },
value: { type: "quantitative", domain: [0, 100] },
},
marks: [
composite({
id: "lollipop",
parts: [
ruleX({
stroke: "#94A5B3", strokeWidth: 2,
channels: { x: { field: "g" }, y2: { field: "value" } },
}),
point({
fill: "#50AEB7", size: 7,
channels: {
x: { field: "g" },
y: { field: "value", edit: move() },
},
}),
],
}),
],
});
mount(chart.dom());
```
## Error bar
One row holds three editable fields: `mean` (the dot), `lo` and `hi` (the caps). Each is its own mark with an edit on a plain `y` channel, so dragging a cap moves only that end. The whisker is a `ruleX` spanning `lo` to `hi`, and follows the caps because it reads the same rows.
### Example: Independent handles per field
Each handle is its own mark. The whisker spans lo..hi and follows the caps.
Try: **Drag** the centre dot to move the mean, or a cap to move an end.
```javascript
const chart = Elicit({
width: 380, height: 280,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ g: "A", mean: 50, lo: 35, hi: 65 },
{ g: "B", mean: 62, lo: 55, hi: 72 },
{ g: "C", mean: 44, lo: 28, hi: 58 },
],
// lo, mean and hi all land on the y axis. The axis spans the UNION of their
// declared domains, so no chart-level y scale is needed.
schema: {
g: { type: "categorical", domain: ["A", "B", "C"] },
lo: { type: "quantitative", domain: [0, 60] },
mean: { type: "quantitative", domain: [0, 80] },
hi: { type: "quantitative", domain: [20, 100] },
},
marks: [
composite({
id: "errorbar",
parts: [
// Inert visual: no edit, so the engine makes it pointer-transparent.
ruleX({
stroke: "#6F8294", strokeWidth: 1.5,
channels: { x: { field: "g" }, y1: { field: "lo" }, y2: { field: "hi" } },
}),
point({
fill: "#50AEB7", size: 6,
channels: {
x: { field: "g" },
y: { field: "mean", edit: move() },
},
}),
tick({
stroke: "#20555A", strokeWidth: 2,
channels: { x: { field: "g" }, y: { field: "lo", edit: move() } },
}),
tick({
stroke: "#20555A", strokeWidth: 2,
channels: { x: { field: "g" }, y: { field: "hi", edit: move() } },
}),
],
}),
],
});
mount(chart.dom());
```
### Example: Coupled move, centre within ends
The dot's edit.custom sets mean from the pointer and shifts lo and hi by the same amount, so the whole bar moves. A constraint declared once on the spec keeps the centre within the ends. It applies to every part's edits, so a cap stops at the centre whichever handle you drag.
Try: **Drag the dot** — the whole bar travels. **Drag a cap** past the dot — it stops at the centre.
```javascript
const chart = Elicit({
width: 380, height: 280,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ g: "A", mean: 50, lo: 35, hi: 65 },
{ g: "B", mean: 62, lo: 55, hi: 72 },
],
schema: {
g: { type: "categorical", domain: ["A", "B"] },
lo: { type: "quantitative", domain: [0, 100] },
mean: { type: "quantitative", domain: [0, 100] },
hi: { type: "quantitative", domain: [0, 100] },
},
// Invariant on the DATA: the centre stays within the ends. A cap drag and a dot
// drag are different marks, but one rule gates both — which is exactly why a
// constraint is declared here, on the spec, and not inside either mark.
constraints: [
constraints.custom(({ active }) => active
? { hi: Math.max(active.hi, active.mean), lo: Math.min(active.lo, active.mean) }
: undefined),
],
marks: [
composite({
id: "errorbar",
parts: [
ruleX({
stroke: "#6F8294", strokeWidth: 1.5,
channels: { x: { field: "g" }, y1: { field: "lo" }, y2: { field: "hi" } },
}),
point({
fill: "#50AEB7", size: 6,
channels: {
x: { field: "g" },
// Coupled move: the dot shifts lo/hi by the mean's delta.
y: { field: "mean",
edit: edit.custom((ctx) => {
const d = ctx.datum;
const s = ctx.channels[0].scale;
const mean = s.invertValue(ctx.pointer.y);
const delta = mean - d.mean;
return { ...d, mean, lo: d.lo + delta, hi: d.hi + delta };
}) },
},
}),
tick({
stroke: "#20555A", strokeWidth: 2,
channels: { x: { field: "g" }, y: { field: "lo", edit: move() } },
}),
tick({
stroke: "#20555A", strokeWidth: 2,
channels: { x: { field: "g" }, y: { field: "hi", edit: move() } },
}),
],
}),
],
});
mount(chart.dom());
```
## Composite channels + per-part channels
Channels bind at two levels. The composite's `channels` (here `x`, `y`, `angle`) pass down to every part, so the glyph shares one position and one orientation. Each part still declares its own channels and shorthands: arm length, stroke colour, a hub's `fill` and `size`. A part's key wins on conflict. Inherited `edit`s attach to the last part only, so one `rotate()` spins the whole glyph once.
### Example: Shared x/y/angle; per-part stroke on crossing ticks
A + made of tickY (horizontal) and tickX (vertical). Composite channels bind position and angle once; each tick keeps its own stroke and length. The last part holds the inherited rotate() edit.
Try: **Drag** the darker (vertical) arm of a + to spin it.
```javascript
const chart = Elicit({
width: 380, height: 280,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 25, y: 35, theta: -15 },
{ x: 55, y: 60, theta: 40 },
{ x: 78, y: 28, theta: 75 },
{ x: 40, y: 78, theta: -50 },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
theta: { type: "quantitative", domain: [-180, 180] },
},
marks: [
composite({
id: "plus",
discreteScale: "point",
// Glyph-wide: every part inherits these (unless it overrides).
channels: {
x: { field: "x" },
y: { field: "y" },
angle: {
field: "theta",
scale: { range: [-180, 180] },
edit: rotate({ pivot: "mark", fold: false, pick: "direct" }),
},
},
parts: [
// Horizontal arm — own stroke/length; inherits x/y/angle (edit stripped).
tickY({ length: 28, stroke: "#B7DEE1", strokeWidth: 5 }),
// Vertical arm — own stroke; last part keeps the inherited rotate().
tickX({ length: 28, stroke: "#50AEB7", strokeWidth: 5 }),
],
}),
],
});
mount(chart.dom());
```
### Example: Same composite angle; hub point with its own fill/size
A square hub is the third part. It inherits x/y/angle from the composite and sets its own shape, fill and size; part channels win for those names. rotate() is still on the last part.
Try: **Drag** the hub (last part) to spin the whole glyph.
```javascript
const chart = Elicit({
width: 380, height: 280,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 30, y: 40, theta: 20 },
{ x: 60, y: 65, theta: -35 },
{ x: 75, y: 25, theta: 55 },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
theta: { type: "quantitative", domain: [-180, 180] },
},
marks: [
composite({
id: "crosshair",
discreteScale: "point",
channels: {
x: { field: "x" },
y: { field: "y" },
angle: {
field: "theta",
scale: { range: [-180, 180] },
edit: rotate({ pivot: "mark", fold: false, pick: "direct" }),
},
},
parts: [
tickY({ length: 32, stroke: "#94A5B3", strokeWidth: 3 }),
tickX({ length: 32, stroke: "#94A5B3", strokeWidth: 3 }),
// Hub: own shape/fill/size; inherits x/y/angle; keeps rotate() (last).
point({
shape: "square",
size: 6,
fill: "#F2B94B",
}),
],
}),
],
});
mount(chart.dom());
```
## Creating a whole glyph at once
A create gesture mints one row, and every part of the glyph encodes it, so one click adds a whole composite. See [what can be created](https://elicitjs.github.io/editing/existence.md#what-can-create). Put `create` on one part only (here the tip). A click then appends one row, not one per part. The inert stem re-derives from the same row, so the stem and tip appear together.
### Example: Double-click to add a lollipop
create() is on the tip only; the stem (an inert ruleX from baseline → value) re-derives from the same new row. One row in, one whole glyph out. count({ max }) caps the dataset.
Try: **Double-click** empty space to add a lollipop · **drag** a tip to move it.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 20, value: 45 },
{ x: 55, value: 70 },
{ x: 80, value: 30 },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
value: { type: "quantitative", domain: [0, 100] },
},
constraints: [ count({ max: 8 }) ],
marks: [
composite({
id: "lollipop",
parts: [
// The stem: inert, so it stays pointer-transparent and carries no create.
ruleX({
stroke: "#94A5B3", strokeWidth: 2,
channels: { x: { field: "x" }, y2: { field: "value" } },
}),
// The tip: the ONE part that owns the create. A plane gesture fans to every
// feature, so declaring create on a single part appends exactly one row —
// and because both parts read that row, a whole lollipop (stem + tip) appears.
// dblclick, since a move-drag also lives on this handle.
point({
fill: "#50AEB7", size: 7,
channels: {
x: { field: "x" },
y: { field: "value", edit: move() },
},
edits: [ create({ gesture: "dblclick", channels: ["x", "y"] }) ],
}),
],
}),
],
});
mount(chart.dom());
```
## A glyph with its own units
The parts above sit on the chart's axes. Some glyphs need their own units: a face's eye sits 16% of the way up *the face*, not at `y = 0.16` in the data.
Give a part a `frame:` channel and the composite becomes a **box**. The composite's `x` / `y` / `size` set each row's box centre and half-size, and `frame:` values are read inside that box:
- `x` / `y`: `[-1, 1]` from the centre, y up. `{ frame: -0.4 }` is 40% of the way to the left edge.
- `size` / `rx` / `ry` / `strokeWidth`: `[0, 1]`, a fraction of the half-size.
- `angle` / `curvature`: the channel's own units. Each part has its own scale, so two parts can take opposite ranges.
- `{ field: "f", frame: [lo, hi] }` maps the field's schema domain onto that slice of the box. The domain stays on the schema.
- A categorical field spreads its categories evenly over `[lo, hi]`, and an edit snaps to the nearest one.
- `{ fn: (d) => …, frame: true }` is derived in local units. Use it to place a part where another part's value puts it, such as a forearm at the end of an upper arm.
`x` / `y` / `size` describe the box, so they stay off the parts. A part that states no position sits at the centre. `{ value }` is in pixels, so use `frame:` for anything that should scale with the glyph.
### Example: A dial per row
The composite's x and size place a box. The dial states no position, so it sits at the centre at the box's full half-size; the needle spans it in local units and rotates through its own angle scale.
Try: **Drag** a needle around its own centre.
```javascript
const chart = Elicit({
width: 480, height: 300,
margins: { top: 20, right: 24, bottom: 40, left: 44 },
axes: { x: {}, y: {} },
data: [
{ site: "North", capacity: 30, load: 0.7 },
{ site: "South", capacity: 72, load: 0.3 },
],
schema: {
site: { type: "categorical", domain: ["North", "South"] },
capacity: { type: "quantitative", domain: [0, 100] },
load: { type: "quantitative", domain: [0, 1] },
},
marks: [
// One part states a channel in LOCAL units (`frame:`), so the composite
// becomes a BOX: its x / y / size place and size one per row. Inside it,
// x and y run [-1, 1] from the centre with y UP, and magnitudes are a
// fraction of the half-size.
composite({
id: "gauge",
channels: {
x: { field: "capacity" },
y: { value: 150 },
size: { value: 46 },
},
parts: [
// The dial: exactly the box's half-size. It states no position at all —
// inside a box, saying nothing means "here, at the glyph".
point({ channels: {
size: { frame: 1 },
fill: { value: "#EDF7F8" }, stroke: { value: "#6F8294" },
} }),
// The needle: a tick spanning the box's full width, rotated by `load`.
// The angle is a PRIVATE frame scale, so this glyph's degrees can't
// collide with another mark's — and the rotate inverts back through it.
tickY({ channels: {
x1: { frame: -0.85 },
x2: { frame: 0.85 },
angle: { field: "load", frame: [-80, 80],
edit: rotate({ pivot: "mark", pick: "direct" }) },
stroke: { value: "#EE7B5E" },
strokeWidth: { frame: 0.09 },
} }),
],
}),
],
});
mount(chart.dom());
```
For a single knob with a ring fill and a needle, see [Needle → Ableton-style knob](https://elicitjs.github.io/marks/needle.md#ableton).
## Why they're real scales
A `frame:` channel is a real scale, built once per row, so the ordinary edits work inside a box. `move`, `slide`, `rotate` and `resize` invert a gesture through the same mapping that placed the part, and `.accepts()` reports the field's real range to an [external control](https://elicitjs.github.io/editing/external-controls.md).
The chart's axes ignore `frame:` channels. An eye at `{ frame: -0.4 }` leaves the x domain and the axes unchanged.
## Everything scales together
A part's geometry is a fraction of the box, so resizing the glyph resizes its contents. An edit on an inner part still writes its own field on its own domain.
An edit on the composite's own `x` / `y` / `size` moves or resizes the whole glyph. The box covers the glyph, so you can grab it anywhere, including between the parts. A part with its own edit takes the drag first.
### Example: Resize the glyph, the contents follow
The outer disc is the box's half-size; the inner one is 0..0.8 of it. resize() is on the composite, so dragging the outer ring grows the whole glyph and the share stays put.
Try: **Drag the inner disc** up to raise its share · **drag the outer ring** outward to grow the glyph.
```javascript
const chart = Elicit({
width: 480, height: 300,
margins: { top: 20, right: 24, bottom: 40, left: 44 },
axes: { x: {}, y: false },
data: [
{ town: "Ayr", weight: 26, share: 0.7 },
{ town: "Bede", weight: 58, share: 0.3 },
{ town: "Cara", weight: 40, share: 0.5 },
],
schema: {
town: { type: "categorical", domain: ["Ayr", "Bede", "Cara"] },
weight: { type: "quantitative", domain: [10, 70] },
share: { type: "quantitative", domain: [0, 1] },
},
marks: [
composite({
id: "pip",
channels: {
x: { field: "town" },
// `size` is the box's HALF-SIZE, so resizing the glyph resizes everything
// placed in it. The edit lives here, on the glyph itself: the box is a
// real grab target covering the whole pip, so this picks it up bodily.
size: { field: "weight", scale: { range: [18, 54] }, edit: resize() },
},
parts: [
// The outer disc IS the box — full half-size, at the origin. It carries
// no edit of its own, so it is pointer-transparent and a drag on it
// reaches the box underneath.
point({ channels: {
size: { frame: 1 },
fill: { value: "#EDF7F8" }, stroke: { value: "#6F8294" },
} }),
// The inner disc is 0..0.8 of the half-size — a FRACTION, so it grows with
// the glyph and its edit still writes `share` on the same [0, 1] domain.
point({ channels: {
size: { field: "share", frame: [0, 0.8],
edit: slide({ axis: "y", increase: "up" }) },
fill: { value: "#50AEB7" },
} }),
],
}),
],
});
mount(chart.dom());
```
## What box mode returns
Box mode returns the box first, then the parts, all as plain marks. The box carries the composite's `x` / `y` / `size`, so those fields still build the chart's axes. Without an edit on them, the box is inert.
Two limits apply to a part placed in the box:
- A `{ fn }` channel is called once per row, as `(d, 0, [d])`, so it sees only its own row. Read the field instead. Its result is in pixels; add `frame: true` to return local units.
- A line-family mark inside a box is built one row at a time, so it cannot join rows into a series, and it logs a warning. To connect rows, position it on the global scales, or move it out of the composite.
A part with no `frame:` channel keeps the global scales, so one part of a glyph can still span to a data value.
## Build a face with one brow
[`face()`](https://elicitjs.github.io/marks/face.md) is a composite in box mode: a `point` head, two [`ellipse`](https://elicitjs.github.io/marks/ellipse.md) eyes, two `tickY` brows and a [`curveY`](https://elicitjs.github.io/marks/curve.md) mouth. It is a preset, so you can build a different face from the same parts. Here it has one brow instead of two.
The brow and the mouth are both [`curve`](https://elicitjs.github.io/marks/curve.md) marks. `curvature` is the apex's offset from the chord, as a fraction of the half-chord, so it scales with the glyph. Positive curvature bows to the left of the curve's direction, which arches a rightward chord upward. A descending `frame:` range reverses that, so a rising `grump` dips the brow and a rising `mood` deepens the smile.
### Example: One brow, two curves
Head, eyes, brow and mouth, all placed in the glyph's local units. The brow and the mouth are the same mark with opposite frame ranges.
Try: **Drag the unibrow down** to make a face grumpier · **drag a mouth up** to cheer it up.
```javascript
const chart = Elicit({
width: 520, height: 300,
margins: { top: 20, right: 24, bottom: 40, left: 24 },
axes: { x: {}, y: false },
data: [
{ who: "Ada", grump: 0.15, mood: 0.85 },
{ who: "Brun", grump: 0.55, mood: 0.50 },
{ who: "Cyd", grump: 0.95, mood: 0.10 },
],
schema: {
who: { type: "categorical", domain: ["Ada", "Brun", "Cyd"] },
grump: { type: "quantitative", domain: [0, 1] },
mood: { type: "quantitative", domain: [0, 1] },
},
marks: [
// A face is nothing but a composite in box mode — so if you want a face with
// ONE brow, you just use one part. Two `curveY`s do all the expression here:
// a unibrow across both eyes and a mouth under them.
composite({
id: "unibrow",
// Where the glyph goes and how big it is. Nothing inside restates this.
channels: { x: { field: "who" }, size: { value: 56 } },
parts: [
// Head: the box itself, at the origin.
point({ channels: {
size: { frame: 1 },
fill: { value: "#F2B94B" }, stroke: { value: "#C99128" },
} }),
// Eyes: pinned local positions, radius a fraction of the half-size.
point({ channels: {
x: { frame: -0.34 }, y: { frame: 0.12 }, size: { frame: 0.11 },
fill: { value: "#20555A" },
} }),
point({ channels: {
x: { frame: 0.34 }, y: { frame: 0.12 }, size: { frame: 0.11 },
fill: { value: "#20555A" },
} }),
// THE UNIBROW. `curvature` is the apex's offset from the chord as a
// fraction of the half-chord, and positive bows to the LEFT of travel —
// so on this rightward chord positive arches UP. The descending range
// turns a rising `grump` into a brow that dips toward the nose.
curveY({ channels: {
x1: { frame: -0.60 }, x2: { frame: 0.60 },
y: { frame: 0.46 },
curvature: { field: "grump", frame: [0.45, -0.35],
edit: slide({ axis: "y", increase: "down" }) },
stroke: { value: "#20555A" },
strokeWidth: { frame: 0.10 },
} }),
// The mouth, same mark and the same trick with the sign reversed.
curveY({ channels: {
x1: { frame: -0.34 }, x2: { frame: 0.34 },
y: { frame: -0.36 },
curvature: { field: "mood", frame: [0.6, -0.6],
edit: slide({ axis: "y", increase: "up" }) },
stroke: { value: "#20555A" },
strokeWidth: { frame: 0.06 },
} }),
],
}),
],
});
mount(chart.dom());
```
The [face page](https://elicitjs.github.io/marks/face.md) builds the preset's own parts the same way.
---
# Face (emotion)
> Source: https://elicitjs.github.io/marks/face/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`face()` encodes a row's fields as a face. Drag a feature to write its field back: pull the mouth into a smile, widen an eye, tilt a brow. It is a **preset** that returns a [composite in box mode](https://elicitjs.github.io/marks/composite.md#box): a `point` head, two `ellipse` eyes, two `tickY` brows and a `curveY` mouth, placed in the glyph's local units. Each parameter is a channel on one part, editable once you bind it to a field.
## API reference
### `face(options)`
Import `plot` from `elicitjs`. A **preset, not a mark**: it returns a [composite in box mode](https://elicitjs.github.io/marks/composite.md#box) — a head `point`, two `ellipse` eyes, two `tickY` brows and a `curveY` mouth — each placed in the glyph’s own local units. So every feature is its own drag target, and every parameter takes the universal edits. Its centre is placed by the x/y channels when present, else parked at the plot centre.
JSON keyword: `plot.face`
```ts
face({ channels, size, ink, edits, id }) → Mark[]
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `FaceChannels` | `emotion preset` | The channel map. The **six face params are channels** — bind a field with `mouthCurve: { field: 'joy', edit: slide({ axis: 'y' }) }`, or pin a constant with `{ value: 0.8 }` (a fraction of that param’s travel). Bind none and you get the emotion preset (mouthCurve ← valence, eyeScale ← arousal); binding any one replaces it. |
| `size` | `number \| ChannelSpec` | `band slot, else min(w,h)·0.35` | The box's half-size, which the head is drawn at — so every feature scales with it. Set it when drawing many faces so they don't overlap. |
| `ink` | `string` | `'#1f2937'` | The colour of the drawn features (eyes, brows, mouth). |
| `channels.x / .y` | `ChannelSpec` | | Optional: place the face centre in a plot (small-multiples, or an emotion-space scatter). An edit here rides on the box, which covers the whole glyph — so move() picks the face up from anywhere on it. |
| `fill, stroke` | `style` | `'#FFD666' / '#B7791F'` | The head's colour. |
| `edits` | `Edit[]` | | Mark-level edits. They go on the face’s box, which covers the whole glyph, so a whole-dataset edit (create) fires once per gesture. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `mouthCurve` | `→ mouth curvature` | Deep frown ∩ ↔ deep smile ∪. Natural edit: `slide({ axis: 'y', increase: 'up' })`. (Preset: ← `valence`.) |
| `mouthAsym` | `→ mouth angle` | Centred ↔ smirk. Natural edit: `rotate({ pivot: 'mark', pick: 'direct' })`. |
| `eyeScale` | `→ eye rx` | Pinpricks ↔ wide. Natural edit: `slide({ axis: 'x', increase: 'right' })`. (Preset: ← `arousal`.) |
| `eyeSquint` | `→ eye ry` | Round ↔ flat. Natural edit: `slide({ axis: 'y', increase: 'down' })`. Unbound, the eyes stay round as they widen. |
| `browHeight` | `→ brow y` | Slammed down ↔ high arch. Natural edit: `slide({ axis: 'y', increase: 'up' })`. |
| `browTilt` | `→ brow angle` | Sad (outer-down) ↔ angry (inner-down); the two brows mirror each other. Natural edit: `rotate({ pivot: 'mark', pick: 'direct' })`. |
| `x, y` | `→ box x, y` | Face centre; omitted parks it at the plot centre. move() on either picks the whole face up. |
| `size` | `→ box size` | The box's half-size, drawn as the head. resize() on it scales the whole glyph. |
Returns / emits: An **array of marks** (Elicit flattens it): the composite’s **box** — which draws one invisible hit circle per row, so `move()` / `resize()` on x/y/size picks the whole face up — then head, eyes, brows and mouth.
## One face — drag to feel
The emotion preset binds `mouthCurve` to `valence` and `eyeScale` to `arousal`. Binding any parameter yourself drops the preset. Pull the mouth up to smile, or drag an eye to widen it. Each gesture inverts through the field's scale, and the whole face re-derives.
Face edits are ordinary edits on its parts' channels: a `slide` on the mouth's curvature, a `slide` on an eye's radius.
### Example: Valence × arousal
The two-field emotion preset. The mouth and eyes are the drag targets themselves.
Try: **Drag the mouth** up/down (valence) or **drag an eye** sideways (arousal).
```javascript
const chart = Elicit({
width: 320, height: 320,
margins: { top: 12, right: 12, bottom: 12, left: 12 },
data: [ { valence: 0.3, arousal: 0.1 } ],
schema: {
valence: { type: "quantitative", domain: [-1, 1] },
arousal: { type: "quantitative", domain: [-1, 1] },
},
marks: [
// A face draws its features but writes nothing until an edit says so. The
// emotion preset binds mouthCurve ← valence and eyeScale ← arousal; declaring
// them here is what makes those two columns editable — and says which they are.
// Each param is a channel on a real part, so it takes the ordinary edits.
face({
channels: {
mouthCurve: { field: "valence", edit: slide({ axis: "y", increase: "up" }) },
eyeScale: { field: "arousal", edit: slide({ axis: "x", increase: "right" }) },
},
}),
],
});
mount(chart.dom());
```
## Turn on more expressions
Bind any subset of the six params in `channels`, each a `{ field }` with the edit you want. Unbound params stay neutral. Here every param is live: the mouth (↕ curve, ↔ smirk), the eyes (↔ aperture, ↕ squint), and the brows (↕ height, ↔ tilt).
Two params on one part share one gesture. Drag an eye sideways to open it, or down to squint it: `rx` and `ry` are two channels on one `ellipse`. Two edits on one part must read different components of the drag, one on `axis: "x"` and one on `axis: "y"`.
A brow's tilt drives an `angle` but uses `slide`, not `rotate`. You grab a brow at its own pivot, so `rotate` would swing through most of a half-turn in a few pixels.
### Example: Full Chernoff face
All six parameters bound to fields; grab any feature to sculpt the expression.
Try: **Drag** the mouth, an eye, or a brow — each is a separate mark.
```javascript
const chart = Elicit({
width: 340, height: 340,
margins: { top: 12, right: 12, bottom: 12, left: 12 },
data: [ {
curve: 0.7, smirk: 0.5,
aperture: 0.6, squint: 0.2, browH: 0.5, browT: 0.4,
} ],
schema: {
curve: { type: "quantitative", domain: [0, 1] },
smirk: { type: "quantitative", domain: [0, 1] },
aperture: { type: "quantitative", domain: [0, 1] },
squint: { type: "quantitative", domain: [0, 1] },
browH: { type: "quantitative", domain: [0, 1] },
browT: { type: "quantitative", domain: [0, 1] },
},
marks: [
face({
channels: {
// The mouth is one part, so one drag drives both of its params: the
// vertical component bends it, the horizontal one tilts it into a smirk.
mouthCurve: { field: "curve", edit: slide({ axis: "y", increase: "up" }) },
mouthAsym: { field: "smirk", edit: slide({ axis: "x", increase: "right" }) },
// Each eye is one ellipse: rx opens it, ry squints it. Horizontal and
// vertical drag, so one gesture on an eye reads as reshaping it.
eyeScale: { field: "aperture", edit: slide({ axis: "x", increase: "right" }) },
eyeSquint: { field: "squint", edit: slide({ axis: "y", increase: "down" }) },
// Each brow is one tick: height is where it SITS — a positional channel in
// the face's frame, so `move()` inverts straight back through it — and tilt
// is a magnitude, so it slides.
browHeight: { field: "browH", edit: move({ channels: ["y"] }) },
browTilt: { field: "browT", edit: slide({ axis: "x", increase: "right" }) },
},
}),
],
});
mount(chart.dom());
```
## Many faces in a plot
Give the face an `x` (or `y`) channel and it is placed like a `point`: one editable face per row, each with its own frame. Set `x: { field: 'valence' }, y: { field: 'arousal' }` and the faces form an emotion-space scatter that moves as you edit them.
### Example: A mood per person
Faces positioned along a categorical x; drag each one's mouth or eyes to set that person's emotion.
Try: **Drag** any face's mouth or an eye.
```javascript
const chart = Elicit({
width: 540, height: 260,
margins: { top: 16, right: 20, bottom: 34, left: 20 },
axes: { x: {}, y: false },
data: [
{ who: "Ana", valence: 0.6, arousal: 0.4 },
{ who: "Ben", valence: -0.5, arousal: -0.2 },
{ who: "Cy", valence: 0.1, arousal: 0.8 },
],
schema: {
who: { type: "categorical", domain: ["Ana", "Ben", "Cy"] },
valence: { type: "quantitative", domain: [-1, 1] },
arousal: { type: "quantitative", domain: [-1, 1] },
},
marks: [
face({
size: 46,
channels: {
x: { field: "who" },
// Declared, not implied: these are the two columns a drag on this face
// writes. (The emotion preset would DRAW the same binding, but a mark is
// inert until an edit names the column it touches.) Every face's parts are
// separate features, so a drag on Ana's mouth cannot reach Ben's.
mouthCurve: { field: "valence", edit: slide({ axis: "y", increase: "up" }) },
eyeScale: { field: "arousal", edit: slide({ axis: "x", increase: "right" }) },
},
}),
],
});
mount(chart.dom());
```
## Move and resize the head
`x`, `y` and `size` place the face's box, which sits under the head. Bind `x` and `y` to fields with `move()`, and dragging the head moves the whole face. The eyes, brows and mouth are drawn on top, so dragging one of them still edits the expression.
### Example: Drag the head to move it
x + y bound with move(); drag the head to move the face. The mouth and eyes still edit the emotion preset.
Try: **Drag** the head to move it · the mouth/eyes still work.
```javascript
const chart = Elicit({
width: 340, height: 320,
margins: { top: 12, right: 12, bottom: 12, left: 12 },
data: [ { px: 0.1, py: 0.1, valence: 0.4, arousal: 0.2 } ],
schema: {
px: { type: "quantitative", domain: [-1, 1] },
py: { type: "quantitative", domain: [-1, 1] },
valence: { type: "quantitative", domain: [-1, 1] },
arousal: { type: "quantitative", domain: [-1, 1] },
},
marks: [
face({
size: 62,
channels: {
// The head is an ordinary `point`, so it takes an ordinary `move()`. The
// eyes, brows and mouth are separate features drawn on top of it, so
// grabbing one of them edits the expression instead — no arbitration.
x: { field: "px", edit: move({ channels: ["x", "y"] }) },
y: { field: "py" },
mouthCurve: { field: "valence", edit: slide({ axis: "y", increase: "up" }) },
eyeScale: { field: "arousal", edit: slide({ axis: "x", increase: "right" }) },
},
}),
],
});
mount(chart.dom());
```
`size` is both the head's radius and the frame's half-size, so a `resize()` on it scales every feature. Use `resize()` or `move()` on a face, not both: they share the same grab target, and one drag would fire both.
### Example: Resize the whole glyph
size bound with resize(): the head grows and the eyes, brows and mouth grow with it, because they are placed in fractions of the frame.
Try: **Drag** the head outward to grow it, inward to shrink it.
```javascript
const chart = Elicit({
width: 340, height: 320,
margins: { top: 12, right: 12, bottom: 12, left: 12 },
data: [ { mag: 55, valence: 0.4 } ],
schema: {
mag: { type: "quantitative", domain: [30, 90] },
valence: { type: "quantitative", domain: [-1, 1] },
},
marks: [
face({
channels: {
// `size` is the head's radius AND the frame's half-size, so resizing it
// scales every feature with it. Give it a radius range — the default size
// range is the small [3, 18] a dot uses.
size: { field: "mag", scale: { range: [30, 92] }, edit: resize() },
mouthCurve: { field: "valence", edit: slide({ axis: "y", increase: "up" }) },
},
}),
],
});
mount(chart.dom());
```
## Showing a handle's track
A positional channel in the frame has a real scale, so `move()` on it travels exactly the range the scale spans. `guide: { track: true }` draws that range as a dashed segment. It is off by default.
### Example: A handle's travel range
The dashed segment is exactly the range the edit maps the pointer onto — drag past either end and the value stops.
Try: **Drag** a brow up and down along its dashed track.
```javascript
const chart = Elicit({
width: 320, height: 300,
margins: { top: 12, right: 12, bottom: 12, left: 12 },
data: [ { brow: 0.5 } ],
schema: {
brow: { type: "quantitative", domain: [0, 1] },
},
marks: [
face({
channels: {
// A brow's height is a POSITIONAL channel in the face's local frame, so
// `move()` inverts the pointer straight back through the very scale that
// placed it — and the frame scale's pixel range IS the travel range.
// `guide: { track: true }` draws that range, so what you see is the mapping.
browHeight: {
field: "brow",
edit: move({ channels: ["y"], guide: { track: true } }),
},
},
}),
],
});
mount(chart.dom());
```
## One face per day — click to add
A face is [creatable](https://elicitjs.github.io/editing/existence.md#what-can-create) like a `point`. A plane click inverts the pointer through the x and y scales to mint a datum, and every part draws from it. Mark-level `edits` go on the face's box, so `create` fires once per click.
Here the week starts with three days filled. Click an empty day to add its face. The click's height sets the `mood`, which also drives the smile. `unique({ field: "day" })` makes the day the identity, so each day holds at most one face.
### Example: Click an empty day to add a face
create() on an ordinal x (days) × numeric y (mood); unique({ field: "day" }) caps each day at one face. mouthCurve reads the same mood field, so a created face's smile matches where you clicked.
Try: **Click** an empty day to add its face · **drag** a mouth to adjust the mood.
```javascript
const chart = Elicit({
width: 560, height: 300,
margins: { top: 16, right: 20, bottom: 32, left: 34 },
axes: { x: {}, y: {} },
data: [
{ day: "Mon", mood: 0.7 },
{ day: "Wed", mood: 0.4 },
{ day: "Sat", mood: 0.9 },
],
schema: {
// Ordinal x: the week runs Mon → Sun in this order (a band axis).
day: { type: "ordinal", domain: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] },
// Numeric y in [0, 1]: how good the day felt. It also drives the smile.
mood: { type: "quantitative", domain: [0, 1] },
},
constraints: [ unique({ field: "day" }) ],
marks: [
face({
size: 24,
channels: {
x: { field: "day" },
y: { field: "mood" },
// Bind the smile to the SAME field as y: click higher → happier face,
// and a created face's expression derives from the mood create mints —
// no extra field to seed. The edit makes pulling the mouth write `mood`
// too, so the smile and the y position stay two views of one column.
mouthCurve: { field: "mood", edit: slide({ axis: "y", increase: "up" }) },
},
// A click on an empty day's column inverts the pointer to (day, mood) and
// mints one face there. Mark-level edits ride on the HEAD part, so the
// create fires once per click, not once per facial feature. A click that
// lands ON a face carries a node, so it never fires the plane create — and
// a click in a day that's already taken is rejected by `unique`.
edits: [ create({ channels: ["x", "y"] }) ],
}),
],
});
mount(chart.dom());
```
## It's just a composite
`face()` is built from public marks, so you can assemble one yourself. As a composite, it can also draw a network's nodes; see [Faces as nodes](https://elicitjs.github.io/marks/network.md#faces). Below is a smaller face written out in full: a `point` head, two `ellipse` eyes, two `tickY` brows and a `curveY` mouth, each placed in the [composite's box](https://elicitjs.github.io/marks/composite.md#box).
`frame:` marks a number as being in the glyph's own coordinates: `x` and `y` in `[-1, 1]` from the centre with y up, and radii as a fraction of the half-size. A part with no position sits at the centre, where the head goes. A field-bound channel maps the field's declared domain onto a slice of the box (`frame: [0.05, 0.19]`), and the edit inverts back through it.
Each brow is a `tickY` spanning a chord, with `worry` driving its height and tilt. The tilt ranges are mirrored, `[45, -45]` on the left and `[-45, 45]` on the right, so a rising `worry` tilts both brows into the same expression. Each part has its own `frame:` scale, so the two ranges stay independent.
### Example: A face, written out
The same construction face() performs, spelled out with composite + point + ellipse + tick + curve.
Try: **Drag** an eye sideways · **drag a brow** down to worry it · **drag** the mouth up and down.
```javascript
const chart = Elicit({
width: 320, height: 300,
margins: { top: 12, right: 12, bottom: 12, left: 12 },
data: [ { openness: 0.7, mood: 0.8, worry: 0.35 } ],
schema: {
openness: { type: "quantitative", domain: [0, 1] },
mood: { type: "quantitative", domain: [0, 1] },
worry: { type: "quantitative", domain: [0, 1] },
},
marks: [
// This is what `face()` returns. A part stating a `frame:` channel turns the
// composite into a BOX: its x / y / size say where the box is and how big,
// and a `frame:` channel is placed inside it — x and y in [-1, 1] from the
// centre with y UP, radii as a fraction of the half-size.
composite({
id: "myface",
channels: { size: { value: 92 } },
parts: [
// The head IS the box: radius 1 in local units, and no position at all —
// inside a box, saying nothing means "here, at the glyph".
point({ channels: {
size: { frame: 1 },
fill: { value: "#FFD666" },
stroke: { value: "#B7791F" },
} }),
// Two eyes. `rx` maps the field's domain onto a slice of the box, so the
// same drag means the same thing however big the head is.
ellipse({ channels: {
x: { frame: -0.4 },
y: { frame: 0.16 },
rx: { field: "openness", frame: [0.05, 0.19],
edit: slide({ axis: "x", increase: "right" }) },
ry: { frame: 0.12 },
fill: { value: "#1f2937" },
} }),
ellipse({ channels: {
x: { frame: 0.4 },
y: { frame: 0.16 },
rx: { field: "openness", frame: [0.05, 0.19],
edit: slide({ axis: "x", increase: "right" }) },
ry: { frame: 0.12 },
fill: { value: "#1f2937" },
} }),
// Two brows, each a tickY spanning a chord in the box. `worry` drives
// BOTH the height (a slide on y) and the tilt — and the two tilt ranges
// are MIRRORED, so one rising field tilts them into the same expression
// rather than the same direction. That only works because each part's
// frame scale is PRIVATE: a single global angle scale could not hold
// [45, -45] and [-45, 45] at once.
tickY({ channels: {
x1: { frame: -0.14 }, x2: { frame: -0.50 },
y: { field: "worry", frame: [0.57, 0.23],
edit: slide({ axis: "y", increase: "down" }) },
angle: { field: "worry", frame: [45, -45] },
stroke: { value: "#1f2937" },
strokeWidth: { frame: 0.055 },
} }),
tickY({ channels: {
x1: { frame: 0.14 }, x2: { frame: 0.50 },
y: { field: "worry", frame: [0.57, 0.23],
edit: slide({ axis: "y", increase: "down" }) },
angle: { field: "worry", frame: [-45, 45] },
stroke: { value: "#1f2937" },
strokeWidth: { frame: 0.055 },
} }),
// The mouth is a `curve`: a chord in the box plus a curvature. Positive
// bows up, so a descending range turns a rising mood into a deeper smile.
curveY({ channels: {
x1: { frame: -0.36 },
x2: { frame: 0.36 },
y: { frame: -0.34 },
curvature: { field: "mood", frame: [0.6, -0.6],
edit: slide({ axis: "y", increase: "up" }) },
stroke: { value: "#1f2937" },
strokeWidth: { frame: 0.055 },
} }),
],
}),
],
});
mount(chart.dom());
```
---
# Sticker
> Source: https://elicitjs.github.io/marks/sticker/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`sticker()` draws a rounded box with text inside and **sizes the box to the text**. A long note wraps at `maxWidth` and grows taller. Add `editText({ multiline: true })` to double-click and type into it. It is a preset over `composite`, made of a `rect` and a `text`, so every channel, scale, edit and constraint works as on other marks.
## API reference
### `sticker(options)`
Import `plot` from `elicitjs`. A rounded box with text inside, sized by the text. A preset over `composite`, so it desugars into an ordinary `rect` and `text`.
JSON keyword: `plot.sticker`
```ts
sticker({ channels, padding, cornerRadius, maxWidth, minWidth, minHeight, lineHeight, fontFamily, format, table, edits, id }) → Mark[]
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | `x`/`y` place the box and are shared by both parts. `text` is the string it holds. Label channels (`fontSize`, `textAnchor`, `dx`, `dy`) go to the text; every other channel (`fill`, `stroke`, `opacity`, `angle`) goes to the box. `width` and `height` pin a dimension and turn auto-sizing off for that axis; a pinned `width` is also the width the text wraps at, so a note resized narrower re-flows and grows taller. |
| `padding` | `number` | `10` | Space between the text and the box’s edge, in px. |
| `cornerRadius` | `number` | `6` | Corner radius in px. Set `0` for square corners. |
| `maxWidth` | `number` | `160` | The box stops growing here and the text wraps instead. Also the wrap width, so a long note gets taller rather than wider. A `width` channel replaces it on both counts. |
| `minWidth` | `number` | `60` | Keeps an empty or one-word note from collapsing to nothing. |
| `minHeight` | `number` | `0` | A floor for the box’s height, in px. |
| `lineHeight` | `number` | `1.35 × fontSize` | Baseline step between wrapped lines, in px. |
| `fontSize` | `number` | `13` | Used to measure as well as to draw, so the box matches what is painted. A `fontSize` channel still reaches the label, but the box is measured at this value. |
| `fontFamily` | `string` | `the theme’s font` | Measured with, when your page font differs from the theme’s. |
| `format` | `string \| fn` | `String` | Display formatter for the `text` channel: a d3-format string, or `(v) => string`. Display-only — the column stays raw, so `editText` still writes the real value. |
Returns / emits: Carries no edits of its own, like every mark. Put `move({ channels: ["x", "y"], mode: "relative" })` on `x` and `editText({ multiline: true })` in `edits`. Both land on the box: you drag and double-click the note, not its letters. Prefer `mode: "relative"` — an absolute move puts the box’s centre at the pointer, which snaps a note you grabbed by its corner.
### `editText(options)`
Write a typed string back into the `text` channel’s field. Double-click opens an editor over the mark; Enter or clicking away commits, Escape cancels.
JSON keyword: `edit.editText`
```ts
editText({ multiline, channels, when, stage }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `multiline` | `boolean` | `false` | Use a textarea, in which Enter inserts a newline and Cmd/Ctrl+Enter commits. Pair it with `sticker`, whose text wraps. |
| `channels` | `string[]` | `["text"]` | Which channel’s field to write. The default is right almost always. |
## Sizing
The box is measured from the `text` channel string, at the `fontSize` and `fontFamily` it is drawn in, plus `padding` on every side.
`maxWidth` is both the ceiling and the wrap width. A longer note breaks onto more lines and the box gets taller. `minWidth` keeps a one-word note from collapsing.
State a `width` or `height` channel to pin that dimension instead:
```js
sticker({ channels: { width: { value: 120 }, text: { field: "note" } } })
```
Auto-sizing stops for that axis only, so a pinned width still lets height follow the wrapped text. Size from the row with `{ fn }`, or read a column of pixel widths with `{ field: "w", scale: null }`.
A pinned `width` is also the wrap width, in place of `maxWidth`. Narrow a note and the text re-flows; with height still auto-sized, the box grows taller to fit.
## Resizing
Bind `width` to a field and give it an edit to make a resize handle. The channel is in pixels, so give it a `range` that matches the field's domain. The column then holds the box's width directly:
```js
width: {
field: "w",
scale: { range: [70, 260] },
edit: slide({ axis: "x", increase: "right", extent: 95, when: when.shift }),
}
```
`slide` changes the value by how far you drag, so the box stays put when you press it. `extent` is the drag distance that sweeps the whole domain. The box grows about its centre, so an `extent` of half the domain's span (`95` for a 190-wide domain) keeps the dragged edge under the pointer.
For grips on the note's sides, attach [`ui.handles()`](https://elicitjs.github.io/ui.md#handles) to the chart. A grip moves its own side and holds the other still, and the `width` channel needs no edit.
A `move` on `x` and a `slide` on `width` both read horizontal travel. Gate them with `when.shift` and `when.noShift` so each gets its own gesture.
Pin `height` the same way for a fixed-size card. Leave it off and height keeps following the text.
### Example: Resizable notes
Drag the width, and the text re-wraps to fit.
Try: **Shift-drag** a note sideways to resize it — the text re-wraps and the box gets taller as it narrows. **Drag** without Shift to move it, and **double-click** to retype.
```javascript
const chart = Elicit({
width: 460, height: 300,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
schema: {
note: { type: "categorical", open: true },
w: { type: "quantitative", domain: [70, 260] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
data: [
{ note: "Shift-drag my edge sideways. The text re-wraps to whatever width I end up.", w: 170, x: 32, y: 62 },
{ note: "Narrow notes get taller.", w: 100, x: 72, y: 28 },
],
marks: [
sticker({
fill: "#EBD6AD",
stroke: "rgba(70, 89, 107, 0.13)",
maxWidth: 260,
edits: [editText({ multiline: true })],
channels: {
x: {
field: "x",
edit: move({ channels: ["x", "y"], mode: "relative", when: when.noShift }),
},
y: { field: "y" },
width: {
field: "w",
scale: { range: [70, 260] },
edit: slide({ axis: "x", increase: "right", extent: 95, when: when.shift }),
},
text: { field: "note" },
},
}),
],
});
mount(chart.dom());
```
## Typing
`editText()` writes what you type back into the `text` channel's field. Put it in `edits`:
```js
sticker({
edits: [editText({ multiline: true })],
channels: { x: { field: "x" }, y: { field: "y" }, text: { field: "note" } },
})
```
Double-click a note to open an editor filling the box. `multiline: true` makes it a textarea: Enter inserts a newline, and Cmd/Ctrl+Enter or clicking away commits. Escape cancels either way. Without it you get a single-line field where Enter commits.
Drag or double-click anywhere on the box, including the gaps between words.
Typing needs the SVG renderer. Under `CanvasRenderer` a sticker draws and drags only.
## Editing a board
The universal edits do the rest:
- `move({ channels: ["x", "y"], mode: "relative" })` on `x` drags a note. Use `mode: "relative"` on anything with area: it moves by how far you drag and keeps the grab point under the pointer. The default `"absolute"` puts the note's centre at the pointer, so a big box jumps when you press it.
- `create()` in `edits` mints one where you click. Give it `defaults` so a new note arrives with a colour and a placeholder.
- `remove({ when: when.alt })` deletes the note under the pointer.
- `cycle()` on `fill` steps through the colours in that field's domain.
### Example: Sticky notes
Boxes sized by what you type.
Try: **Drag** a note. **Double-click** one and type — Enter makes a new line, Cmd/Ctrl+Enter commits, and the box resizes. **Click** a note to recolour it,**click** empty space to add one, and **Alt-click** to delete.
```javascript
const chart = Elicit({
width: 460, height: 300,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
schema: {
note: { type: "categorical", open: true },
tone: { type: "categorical", domain: ["#EBD6AD", "#C2DEBA", "#EDF7F8"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
data: [
{ note: "Drag me", tone: "#EBD6AD", x: 25, y: 75 },
{ note: "Double-click to rewrite. Long notes wrap and the box grows.", tone: "#C2DEBA", x: 70, y: 45 },
{ note: "Click empty space for a new one", tone: "#EDF7F8", x: 25, y: 22 },
],
marks: [
sticker({
stroke: "rgba(70, 89, 107, 0.13)",
maxWidth: 140,
edits: [
editText({ multiline: true }),
create({ defaults: { note: "New note", tone: "#EBD6AD" } }),
remove({ when: when.alt }),
],
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "note" },
fill: { field: "tone", scale: null, edit: cycle() },
},
}),
],
});
mount(chart.dom());
```
## Diagram board
A diagram board is a `network` schema with a `sticker` over the nodes and a `link` over the links. List `link()` first so connectors sit behind the boxes.
With `curve: "orthogonal"`, each connector leaves a box at a right angle from one of its edges. It docks to the sticker's measured box and routes around any note in the way. See [where a link meets a node](https://elicitjs.github.io/marks/network.md#routing).
Give the sticker a `ports` channel with `edit.network.connect()` on it. Hover a box and a port appears on each edge. Drag from one to another box to connect them; drop on a port to pin that end, or on the box to connect at its facing port. The `link` mark's `sourceSide` and `targetSide` channels name the columns the sides are written to — see [Ports](https://elicitjs.github.io/marks/network.md#ports). Dragging a box's body still moves it.
`edit.network.rewire()` on the link puts a handle on each end while you hover it: drag one to another box to reconnect, or into space to disconnect. Deleting a box drops its connectors, because a link must name a node that exists.
### Example: Flowchart
Boxes you type into, connectors you drag, flip and restyle.
Try: **Double-click** a box and type — Enter makes a new line, Cmd/Ctrl+Enter commits, and the box grows to fit. **Hover** a box and **drag** from one of its ports to another box to connect them; drop on a port to pin that end, or on the box to connect at its facing port. **Hover** a connector and drag its end to reconnect it, or into space to remove it. **Drag** a box around another and watch its connectors follow. **Click** a connector to switch it between an elbow and a curve, and **Alt-click** one to reverse it. **Click** empty space for a new box, and **Alt-click** a box to delete it — its connectors go too.
```javascript
const chart = Elicit({
width: 520, height: 360,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
steps: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
flows: {
role: "links",
directed: true,
fields: {
source: { type: "ref" },
target: { type: "ref" },
kind: { type: "categorical", domain: ["orthogonal", "bezier"] },
// The edge each end meets, or null to slide along the box.
fromSide: { type: "categorical", domain: ["top", "right", "bottom", "left"] },
toSide: { type: "categorical", domain: ["top", "right", "bottom", "left"] },
},
},
},
},
data: {
steps: [
{ id: "s1", label: "Draft the question", x: 22, y: 82 },
{ id: "s2", label: "Pilot it with five readers", x: 74, y: 60 },
{ id: "s3", label: "Ship", x: 30, y: 18 },
],
flows: [
{ source: "s1", target: "s2", kind: "orthogonal" },
{ source: "s2", target: "s1", kind: "orthogonal" },
{ source: "s2", target: "s3", kind: "bezier" },
],
},
marks: [
link({
stroke: "#94A5B3",
strokeWidth: 1.5,
channels: {
curve: { field: "kind" },
sourceSide: { field: "fromSide" },
targetSide: { field: "toSide" },
},
edits: [
edit.network.rewire(),
edit.network.reverse({ when: when.alt }),
cycle({ channels: ["curve"], when: when.noAlt }),
],
}),
sticker({
fill: "#F9F4EC",
stroke: "#C99128",
maxWidth: 130,
cornerRadius: 8,
edits: [
editText({ multiline: true }),
create({ defaults: { label: "New step" } }),
remove({ when: when.alt }),
],
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "label" },
// A dot on each edge, shown when you hover a box: drag from one to connect.
ports: {
value: true,
edit: edit.network.connect({ defaults: { kind: "orthogonal" } }),
},
},
}),
],
});
mount(chart.dom());
```
## Notes on a scale
A sticker is placed through the same scales as any mark. Point `x` at a categorical field and the notes sit in columns. `move` inverts the drag through that band scale, so dropping a note in another column writes the new category into the row.
The lane a note ends in is the answer. `getData()` returns it as `lane`. Sort within a lane by pointing `y` at a quantitative field, as here with `rank`.
### Example: Lanes
A band scale on x, so a drag re-files a card.
Try: **Drag** a card into another lane — it snaps to the column and the row’s `lane` changes. **Double-click** to retype, **click** empty space to add a card, and **Alt-click** to delete.
```javascript
const chart = Elicit({
width: 480, height: 320,
margins: { top: 24, right: 16, bottom: 30, left: 16 },
axes: { x: {}, y: false },
schema: {
note: { type: "categorical", open: true },
lane: { type: "categorical", domain: ["Now", "Next", "Later"] },
rank: { type: "quantitative", domain: [0, 100] },
},
data: [
{ note: "Measure the text", lane: "Now", rank: 80 },
{ note: "Wrap long notes", lane: "Now", rank: 40 },
{ note: "Resize a note by its edge", lane: "Next", rank: 65 },
{ note: "Wire notes together", lane: "Later", rank: 55 },
],
marks: [
grid({ channel: "x" }),
sticker({
fill: "#ECF3F9",
stroke: "#1D4467",
maxWidth: 120,
edits: [
editText({ multiline: true }),
create({ defaults: { note: "New card" } }),
remove({ when: when.alt }),
],
channels: {
x: { field: "lane", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "rank" },
text: { field: "note" },
},
}),
],
});
mount(chart.dom());
```
---
# Geo
> Source: https://elicitjs.github.io/marks/geo/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
Geo marks place rows by longitude and latitude through a chart-level `projection`, instead of x/y scales. Frame any place by fitting GeoJSON or a lon/lat bounding box in `projection.domain`, or by passing a live `d3.geo*` instance with your own `center` and `scale`. `geoBasemap({ geojson })` draws vector maps and `geoTile()` lays Web Mercator raster tiles behind your marks.
## API reference
### `projection (ElicitSpec)`
Chart option. Accepts a named projection (fits the world), an options object fitted to a GeoJSON `domain`, or a live `d3.geo*` instance (required when setting `center` / `scale` directly). It frames the first view; [zoom and pan](https://elicitjs.github.io/marks/geo.md#zoom-pan) move the view through the `lon` and `lat` domains. Auto axes default off when set.
JSON keyword: `spec`
```ts
projection: "mercator" | "albers-usa" | "equal-earth" | "orthographic" | …
projection: { type, domain?, rotate?, parallels?, clipAngle?, precision?, inset?, … }
projection: d3.geoMercator().center([lon, lat]).scale(s).translate([w / 2, h / 2])
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `type` | `string \| fn` | | Named projection (e.g. "mercator", "albers-usa", "equal-earth", "orthographic", "identity") or a d3.geo* factory. |
| `domain` | `GeoJSON` | `{ type: "Sphere" }` | GeoJSON FeatureCollection, Feature, or Geometry fitted into the plot frame. Pass `{ type: "MultiPoint", coordinates: [[w, s], [e, n]] }` to frame a lon/lat box with no polygon winding issues. |
| `inset / insetTop / …` | `number` | `0` | Pixel padding inside the plot frame when fitting domain. |
| `rotate` | `[λ, φ, γ?]` | | Spherical rotation in degrees. Pass [-lon, -lat] to centre a globe or conic projection on [lon, lat]. |
| `parallels / clipAngle / precision` | `d3-geo` | `— / — / 0.15` | Forwarded to the underlying d3-geo projection. |
### `geoBasemap({ geojson, … })`
Inert background map. Pass topology as a mark option — `geojson` — not as `Elicit` data. Load your own: `const map = await fetch("…").then(r => r.json())` then `geoBasemap({ geojson: map })`. A FeatureCollection draws **one path per feature** so boundaries show.
JSON keyword: `plot.geoBasemap`
```ts
geoBasemap({ geojson, fill, stroke, strokeWidth, id }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `geojson` | `GeoJSON` | | FeatureCollection, Feature, or Geometry. Required for a visible basemap. |
| `fill / stroke / strokeWidth` | `style` | `'#e2e8f0' / '#94a3b8' / 0.75` | Chrome styling (also via channels). |
### `geoTile({ url, … })`
Raster basemap from a slippy-map tile server (OSM, CARTO, satellite, or your own). Requires `projection: "mercator"` or a `d3.geoMercator()` instance: tiles are pre-rendered in Web Mercator, so other projections draw nothing and log a warning. Inert chrome, like `geoBasemap` — compose both to draw boundaries over imagery.
JSON keyword: `plot.geoTile`
```ts
geoTile() → Mark // OSM standard + attribution
geoTile({ url, subdomains, tileSize, opacity, attribution, attributionSize, minZoom, maxZoom, zoomOffset, id }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `url` | `string \| fn` | `OSM standard` | Template `{s}/{z}/{x}/{y}`, or a function of the tile. |
| `subdomains` | `string[]` | `[]` | Hosts to rotate `{s}` across (e.g. a, b, c). |
| `opacity` | `number` | `1` | Dim the imagery so overlaid data reads. |
| `attribution` | `string \| null` | `"© OpenStreetMap contributors"` | Drawn bottom-right. A licence condition of every tile service — only pass null if you render the credit yourself. |
| `attributionSize` | `number` | `9` | Attribution font size in px. |
| `zoomOffset / minZoom / maxZoom` | `number` | `0 / 0 / 19` | Nudge or clamp the chosen zoom level (picked from the fitted scale). |
| `tileSize` | `number` | `256` | Edge length of one tile in px. Set it for a server that serves retina tiles. |
Returns / emits: A mark emitting image nodes into the background layer, keyed by {z}/{x}/{y} so on-screen tiles survive a re-render without re-fetching.
### `geoPoint / geoPolygon / geoLine / geoText / geoRect`
Editable overlays. Import `plot` from `elicitjs`. `geoText` is `text` with the projection doing the placement — it shares the node shape, so `editText` / `cycle` / `rotate` work on it unchanged.
JSON keyword: `plot.geoPoint`, `plot.geoPolygon`, `plot.geoLine`, `plot.geoText`, `plot.geoRect`
```ts
geoPoint({ channels: { lon, lat, size, fill }, edits }) → Mark
geoPolygon({ channels: { geometry, fill } }) → Mark // one region per row, drawn from GeoJSON
geoPolygon({ channels: { lon, lat, series }, handles, handleSize, handleColor }) → Mark // one region across rows; a vertex is a row
geoLine({ channels: { lon, lat, series, order }, handles, handleSize, handleColor, closed }) → Mark // one line across rows; a vertex is a row
geoLine({ channels: { coordinates }, handles }) → Mark // one line per row, drawn from a list
geoText({ channels: { lon, lat, text }, dx, dy, format }) → Mark
geoRect({ channels: { west, south, east, north } }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `closed` | `boolean` | `false` | `geoLine` with `lon`/`lat` channels: join the last vertex to the first and fill the region. A `geoPolygon` with those channels is this form. On the `coordinates` form it logs a warning. |
| `handles / handleSize / handleColor` | `boolean \| 'hit' / number / string` | `handles where an edit reaches the row / 5 / the line's stroke` | Vertex handles on `geoLine` and a `lon`/`lat` `geoPolygon`, as on `line`. `true` draws one at every vertex, `false` draws none, and `"hit"` keeps them grabbable but unseen. A line from a `coordinates` cell draws them only when you set `handles`. A `geometry` `geoPolygon` has no vertex rows, so these options log a warning there. |
| `format` | `string \| fn` | `String` | `geoText` display formatter for the `text` channel. Display-only. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `lon / lat` | `quantitative` | Position in degrees. One dot per row on geoPoint, the anchor on geoText; on geoLine, connects the rows into one path; on geoPolygon, into one closed region. |
| `geometry` | `GeoJSON` | geoPolygon path geometry on each row. Drawn as given; to edit vertices use lon / lat rows. |
| `coordinates` | `[[lon,lat],…]` | geoLine vertex list, one line per row. Drawn as given; to edit vertices use lon / lat rows. |
| `text` | `string` | geoText label content (raw, unscaled). Retype it with `editText()`. |
| `fontSize / textAnchor / lineAnchor / angle` | `literal` | geoText glyph channels — same as the `text` mark. |
| `dx / dy` | `px` | geoText visual nudge off the anchor (does not move the lon/lat a drag writes). |
| `west/south/east/north` | `quantitative` | geoRect geographic AABB. |
| `fill / stroke / size` | `style` | Ordinary style scales (not projected). |
Returns / emits: Marks emitting path / circle / text / rect nodes in projected pixel space.
### `edit.geo.*`
Geo-scoped edits (`scope: "geo"`). Each is a universal edit on the map’s channels: `move`, `create`, `line.draw`, `line.moveSeries` and `brushRect`. They write `lon`/`lat` through the chart projection, and a declared domain on those fields limits them. Delete a pin, a vertex or a box with `remove`.
JSON keyword: `edit.geo.move`, `edit.geo.create`, `edit.geo.draw`, `edit.geo.moveSeries`, `edit.geo.brush`, `edit.geo.createRect`
```ts
edit.geo.move() — drag a geoPoint, a geoText or a geoLine vertex
edit.geo.create() — click to place a lon/lat row
edit.geo.draw({ minDist }) — drag to draw a geoLine or geoPolygon, a row per vertex (minDist: 8 px between vertices)
edit.geo.moveSeries() — drag a whole geoLine, or a geoPolygon by its inside
edit.geo.brush({ resize, move, edgeInset }) — resize/move a geoRect (resize: 'both' | 'x' | 'y' | 'none')
edit.geo.createRect({ width, height, edgeInset }) — click open map to mint a bbox (degrees)
```
## Framing a location
A bare projection name such as `projection: "mercator"` fits the whole world. Point the map at a specific place in one of three ways:
- **Fit a GeoJSON object:** `projection: { type: "mercator", domain: geojson, inset: 6 }`. Any FeatureCollection, Feature, or Geometry fills the plot frame. Note that `d3-geo` treats clockwise exterior rings as the interior of a polygon (opposite to RFC 7946), so a reversed polygon zooms out to the globe and logs a warning.
- **Fit a lon/lat bounding box (no GeoJSON needed):** pass a `MultiPoint` of the southwest and northeast corners as `domain`: `domain: { type: "MultiPoint", coordinates: [[west, south], [east, north]] }`. A `MultiPoint` has no ring winding, so it fits any rectangle reliably.
- **Centre on `[lon, lat]` and zoom level:** pass a live `d3.geoMercator()` instance directly as `projection`. Options such as `center` and `scale` belong on a `d3.geo*` instance rather than the plain `projection` options object. For Web Mercator tiles, slippy-map zoom level `z` converts directly to scale with `(256 * 2 ** z) / (2 * Math.PI)`, and `translate([innerWidth / 2, innerHeight / 2])` puts `center` in the middle of the plot.
For globe or regional projections such as `"orthographic"` or `"conic-conformal"`, pass `rotate: [-lon, -lat]` in the `projection` options object to centre on `[lon, lat]`.
`lon` and `lat` are placed through the projection, so their `schema` entries only need `{ type: "quantitative" }`. Declare a `domain` on either to bound where a pin can be dropped or dragged. With [zoom and pan](#zoom-pan), the domains hold the window on show.
### Example: Frame any region with a bounding box
Pass two opposite corners as a GeoJSON MultiPoint in projection.domain. Swap the two pairs to move the map anywhere on Earth.
Try: **Click** the map to drop a pin; **drag** any pin to move it.
```javascript
// Fit the map to any region by passing its southwest and northeast corners
// as a GeoJSON MultiPoint — no GeoJSON polygon file or ring-winding needed.
const londonBounds = {
type: "MultiPoint",
coordinates: [
[-0.22, 51.46], // [west, south]
[ 0.02, 51.56], // [east, north]
],
};
const chart = Elicit({
width: 520, height: 360,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
projection: { type: "mercator", domain: londonBounds },
data: [
{ lon: -0.1276, lat: 51.5072, place: "Westminster" },
{ lon: -0.0877, lat: 51.5136, place: "City of London" },
{ lon: -0.0098, lat: 51.4826, place: "Greenwich" },
],
schema: {
lon: { type: "quantitative" },
lat: { type: "quantitative" },
place: { type: "categorical" },
},
marks: [
geoTile(),
geoPoint({
size: 7, fill: "#EE7B5E", stroke: "#fff", strokeWidth: 2,
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
},
edits: [edit.geo.move(), edit.geo.create({ defaults: { place: "new pin" } })],
}),
],
});
mount(chart.dom());
```
### Example: Centre on coordinates and switch locations
A live d3.geoMercator() with .center([lon, lat]), .scale(scaleForZoom(z)) and .translate([W / 2, H / 2]) frames the first view. A button writes the lon and lat domains with setDomain() to jump to a new city.
Try: **Click** a city button to reframe the map · **click** the map to drop a pin · **drag** a pin to move it.
```javascript
const W = 520, H = 360;
// Web Mercator slippy-map zoom level z → d3.geoMercator scale.
// Roughly: z = 4 continent, z = 11 city, z = 15 neighbourhood or campus.
const scaleForZoom = (z) => (256 * 2 ** z) / (2 * Math.PI);
const PLACES = {
Tokyo: { center: [139.6917, 35.6895], zoom: 11, pins: [{ lon: 139.7006, lat: 35.6896, place: "Shinjuku" }, { lon: 139.7671, lat: 35.6812, place: "Tokyo Station" }] },
London: { center: [-0.1276, 51.5072], zoom: 11, pins: [{ lon: -0.1276, lat: 51.5072, place: "Westminster" }, { lon: -0.0759, lat: 51.5055, place: "Tower Bridge" }] },
"New York":{ center: [-73.9857, 40.7484], zoom: 11, pins: [{ lon: -73.9857, lat: 40.7484, place: "Midtown" }, { lon: -73.9654, lat: 40.7829, place: "Central Park" }] },
Vancouver: { center: [-123.1207, 49.268], zoom: 12, pins: [{ lon: -123.1207, lat: 49.2827, place: "Downtown" }, { lon: -123.1560, lat: 49.2680, place: "Kitsilano" }] },
};
// A projection centred on [lon, lat] at slippy-map zoom z.
const projectionAt = (center, zoom) => d3.geoMercator()
.center(center)
.scale(scaleForZoom(zoom))
.translate([W / 2, H / 2]);
// Pass a live d3.geoMercator() instance to frame the first view.
const proj = projectionAt(PLACES.Tokyo.center, PLACES.Tokyo.zoom);
const chart = Elicit({
width: W, height: H,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
projection: proj,
data: PLACES.Tokyo.pins,
schema: {
lon: { type: "quantitative" },
lat: { type: "quantitative" },
place: { type: "categorical" },
},
marks: [
geoTile(),
geoPoint({
size: 7, fill: "#EE7B5E", stroke: "#fff", strokeWidth: 2,
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
},
edits: [edit.geo.move(), edit.geo.create({ defaults: { place: "new pin" } })],
}),
],
});
mount(chart.dom());
const controls = document.createElement("div");
controls.style.cssText = "display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin-top:10px;font:12px system-ui";
const readout = document.createElement("span");
readout.style.color = "#6F8294";
// The lon and lat window a centre and a zoom level show.
const windowAt = (center, zoom) => {
const p = projectionAt(center, zoom);
return {
lon: [p.invert([0, H / 2])[0], p.invert([W, H / 2])[0]],
lat: [p.invert([W / 2, H])[1], p.invert([W / 2, 0])[1]],
};
};
// The lon and lat domains are the map's view, so setDomain() moves it.
const goTo = (name) => {
const { center, zoom, pins } = PLACES[name];
const { lon, lat } = windowAt(center, zoom);
chart.setDomain("lon", lon);
chart.setDomain("lat", lat);
chart.setData(pins);
readout.textContent = `${name} · [${center[0].toFixed(2)}, ${center[1].toFixed(2)}] · z${zoom}`;
};
for (const name of Object.keys(PLACES)) {
const b = document.createElement("button");
b.textContent = name;
b.onclick = () => goTo(name);
b.style.cssText = "padding:4px 10px;border:1px solid #BCC9D4;border-radius:6px;background:transparent;color:inherit;cursor:pointer";
controls.append(b);
}
controls.append(readout);
mount(controls);
readout.textContent = `Tokyo · [${PLACES.Tokyo.center[0].toFixed(2)}, ${PLACES.Tokyo.center[1].toFixed(2)}] · z${PLACES.Tokyo.zoom}`;
```
## Zooming and panning
A map zooms and pans with the same view edits as any chart: `view: { edits: [edit.view.zoom(), edit.view.pan()] }`. The wheel zooms about the place under the pointer. A drag on open map pans; a drag on a pin, vertex or study box still edits that mark.
On a map the view edits write the `lon` and `lat` domains, and the projection moves to show that window. So a map view is undoable, and `chart.setDomain("lon", [west, east])` with `chart.setDomain("lat", [south, north])` sets it from a button. `chart.setDomain("lon", null)` restores the declared domain, or the view the projection framed when none is declared.
- **Limits:** `min` and `max` are zoom levels, as multiples of the view the projection frames. A declared `lon` or `lat` domain is the widest window the view reaches; `limit: false` lifts it.
- **Both axes:** a projection places longitude and latitude together, so a map moves both. `channels` and `minSpan` have no effect.
- **Projections:** the window is exact on a cylindrical projection such as `"mercator"` or `"equirectangular"`. On a conic or azimuthal projection the view fits the window's bounding box, so it shows a little more at the corners.
- **Sizes:** pins, strokes and labels keep their pixel size. `edit.view.zoom({ mode: "magnify" })` scales them with the map. `geoTile()` and `geoBasemap()` keep their stroke width in both modes.
Set `margins: { top: 0, right: 0, bottom: 0, left: 0 }` so tiles, vector outlines and marks clip to the frame. Raster tiles load at the zoom level on show.
### Example: Zoom and pan an OpenStreetMap basemap
edit.view.zoom({ min, max }) and edit.view.pan() in the view. The buttons write the same lon and lat domains with setDomain().
Try: **Scroll** to zoom · **drag** open map to pan · **drag** a pin to move it · **click** open map to add a pin.
```javascript
const W = 520, H = 360;
const scaleForZoom = (z) => (256 * 2 ** z) / (2 * Math.PI);
// The home view: Tokyo at slippy-map zoom 11. Zoom and pan never change it.
const HOME_ZOOM = 11;
const proj = d3.geoMercator()
.center([139.6917, 35.6895])
.scale(scaleForZoom(HOME_ZOOM))
.translate([W / 2, H / 2]);
// Zoom levels are multiples of the home view: out to z2, in to z18.
const [MIN, MAX] = [2 ** (2 - HOME_ZOOM), 2 ** (18 - HOME_ZOOM)];
const chart = Elicit({
width: W, height: H,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
projection: proj,
data: [
{ lon: 139.7006, lat: 35.6896, place: "Shinjuku" },
{ lon: 139.7671, lat: 35.6812, place: "Tokyo Station" },
{ lon: 139.7454, lat: 35.6586, place: "Tokyo Tower" },
],
schema: {
lon: { type: "quantitative" },
lat: { type: "quantitative" },
place: { type: "categorical" },
},
// The same view edits as any chart. Tiles load at the zoom level on show.
view: {
edits: [edit.view.zoom({ min: MIN, max: MAX }), edit.view.pan()],
},
marks: [
geoTile(),
// A drag on a pin still moves the pin; a drag on open map pans.
geoPoint({
size: 7, fill: "#EE7B5E", stroke: "#fff", strokeWidth: 2,
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
},
edits: [
edit.geo.move(),
edit.geo.create({ defaults: { place: "new pin" } }),
],
}),
],
});
mount(chart.dom());
// The window on show: the lon and lat domains, or the home view before any zoom.
const edge = (x, y) => proj.invert([x, y]);
const HOME = {
lon: [edge(0, H / 2)[0], edge(W, H / 2)[0]],
lat: [edge(W / 2, H)[1], edge(W / 2, 0)[1]],
};
const windowNow = () => {
const s = chart.getSchema();
return { lon: s.lon.domain || HOME.lon, lat: s.lat.domain || HOME.lat };
};
const levelNow = () => {
const [lo, hi] = windowNow().lon;
return (HOME.lon[1] - HOME.lon[0]) / (hi - lo);
};
// A button writes the same domains the wheel does.
const zoomBy = (k) => {
const level = levelNow() * k;
if (level < MIN || level > MAX) return;
const win = windowNow();
for (const field of ["lon", "lat"]) {
const [lo, hi] = win[field];
const mid = (lo + hi) / 2;
const half = (hi - lo) / 2 / k;
chart.setDomain(field, [mid - half, mid + half]);
}
};
const controls = document.createElement("div");
controls.style.cssText = "display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin-top:10px;font:12px system-ui";
const readout = document.createElement("span");
readout.style.color = "#6F8294";
const addButton = (label, onclick) => {
const b = document.createElement("button");
b.textContent = label;
b.onclick = onclick;
b.style.cssText = "padding:4px 10px;border:1px solid #BCC9D4;border-radius:6px;background:transparent;color:inherit;cursor:pointer";
controls.append(b);
};
addButton("Zoom in", () => zoomBy(1.5));
addButton("Zoom out", () => zoomBy(1 / 1.5));
// null takes the written domain away: the map draws as the projection framed it.
addButton("Reset", () => { chart.setDomain("lon", null); chart.setDomain("lat", null); });
controls.append(readout);
mount(controls);
const show = () => {
const { lon, lat } = windowNow();
const z = HOME_ZOOM + Math.log2(levelNow());
readout.textContent = `z${z.toFixed(1)} · [${((lon[0] + lon[1]) / 2).toFixed(3)}, ${((lat[0] + lat[1]) / 2).toFixed(3)}]`;
};
chart.on("change", show);
show();
```
### Example: Zoom and pan a GeoJSON basemap
The projection is fitted to the GeoJSON once. Zoom and pan write the lon and lat domains; Reset takes them away with setDomain(field, null).
Try: **Scroll** to zoom · **drag** open map to pan · **drag** or **click** to edit pins.
```javascript
const W = 520, H = 360, PAD = 12;
// The home view: a projection fitted to the GeoJSON. Zoom and pan never change it.
const proj = d3.geoMercator().fitExtent([[PAD, PAD], [W - PAD, H - PAD]], vancouver);
const [MIN, MAX] = [0.6, 12];
const chart = Elicit({
width: W, height: H,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
projection: proj,
data: [
{ lon: -123.1207, lat: 49.2827, place: "Downtown" },
{ lon: -123.1560, lat: 49.2680, place: "Kitsilano" },
{ lon: -123.1000, lat: 49.2630, place: "Mount Pleasant" },
],
schema: {
lon: { type: "quantitative" },
lat: { type: "quantitative" },
place: { type: "categorical" },
},
// The same view edits as any chart. On a map they write the lon and lat
// domains, and the projection moves to show that window.
view: {
edits: [edit.view.zoom({ min: MIN, max: MAX }), edit.view.pan()],
},
marks: [
geoBasemap({ geojson: vancouver, fill: "#EDF7F8", stroke: "#46596B", strokeWidth: 0.8 }),
geoPoint({
size: 7, fill: "#50AEB7", stroke: "#fff", strokeWidth: 1.5,
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
},
edits: [
edit.geo.move(),
edit.geo.create({ defaults: { place: "new pin" } }),
],
}),
],
});
mount(chart.dom());
// The window on show: the lon and lat domains, or the home view before any zoom.
const edge = (x, y) => proj.invert([x, y]);
const HOME = {
lon: [edge(0, H / 2)[0], edge(W, H / 2)[0]],
lat: [edge(W / 2, H)[1], edge(W / 2, 0)[1]],
};
const windowNow = () => {
const s = chart.getSchema();
return { lon: s.lon.domain || HOME.lon, lat: s.lat.domain || HOME.lat };
};
const levelNow = () => {
const [lo, hi] = windowNow().lon;
return (HOME.lon[1] - HOME.lon[0]) / (hi - lo);
};
// A button writes the same domains the wheel does.
const zoomBy = (k) => {
const level = levelNow() * k;
if (level < MIN || level > MAX) return;
const win = windowNow();
for (const field of ["lon", "lat"]) {
const [lo, hi] = win[field];
const mid = (lo + hi) / 2;
const half = (hi - lo) / 2 / k;
chart.setDomain(field, [mid - half, mid + half]);
}
};
const controls = document.createElement("div");
controls.style.cssText = "display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin-top:10px;font:12px system-ui";
const readout = document.createElement("span");
readout.style.color = "#6F8294";
const addButton = (label, onclick) => {
const b = document.createElement("button");
b.textContent = label;
b.onclick = onclick;
b.style.cssText = "padding:4px 10px;border:1px solid #BCC9D4;border-radius:6px;background:transparent;color:inherit;cursor:pointer";
controls.append(b);
};
addButton("Zoom in", () => zoomBy(1.5));
addButton("Zoom out", () => zoomBy(1 / 1.5));
// null takes the written domain away: the map draws as the projection framed it.
addButton("Reset", () => { chart.setDomain("lon", null); chart.setDomain("lat", null); });
controls.append(readout);
mount(controls);
const show = () => { readout.textContent = `${levelNow().toFixed(1)}×`; };
chart.on("change", show);
show();
```
## Providing basemap data
`geoBasemap` draws the map and cannot be edited. Pass it GeoJSON, and pass the same object as `projection.domain` so the map fills the frame. The examples below use Vancouver's 22 local areas (`vancouver` in the docs scope); your app imports or fetches its own file.
### Example: Vancouver local areas
Pass any FeatureCollection: geoBasemap({ geojson }). Fit with projection.domain. In your app: const map = await fetch("…/my-map.geojson").then(r => r.json()).
```javascript
// docs inject `vancouver`; your app loads GeoJSON then passes it in:
// const vancouver = await fetch("data/vancouver-neighborhoods.json").then(r => r.json());
const chart = Elicit({
width: 520, height: 360,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
data: [],
schema: {},
marks: [
geoBasemap({
geojson: vancouver,
fill: "#EDF7F8",
stroke: "#46596B",
strokeWidth: 0.8,
}),
],
});
mount(chart.dom());
```
## Real basemaps (OSM raster tiles)
`geoTile()` lays a raster basemap — a pyramid of 256px tiles from a tile server — behind your marks. Tiles are pre-rendered in Web Mercator, so it requires `projection: "mercator"` or a `d3.geoMercator()` instance; other projections draw nothing and log a warning instead of a misaligned map. Lon/lat marks and `edit.geo.*` gestures work the same on top, because they use the same projection. Every tile service requires attribution as a licence condition, and `geoTile()` draws it by default. Public OSM tiles are rate-limited, so in production point `url` at your own server or a paid provider.
### Example: Pins on OpenStreetMap
geoTile() replaces geoBasemap, so no GeoJSON is needed. Fit the view with a two-corner MultiPoint in projection.domain.
Try: **Click** to drop a pin; **drag** it. Lon/lat come back as data.
```javascript
const chart = Elicit({
width: 520, height: 360,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
// No GeoJSON needed: fit the projection to a two-corner lon/lat box.
projection: {
type: "mercator",
domain: {
type: "MultiPoint",
coordinates: [
[-123.225, 49.198], // [west, south]
[-123.023, 49.297], // [east, north]
],
},
},
data: [
{ lon: -123.1207, lat: 49.2827, place: "Downtown" },
{ lon: -123.1560, lat: 49.2680, place: "Kitsilano" },
],
schema: {
lon: { type: "quantitative" },
lat: { type: "quantitative" },
place: { type: "categorical" },
},
marks: [
geoTile(), // defaults to OSM standard + its attribution
geoPoint({
size: 7, fill: "#EE7B5E", stroke: "#fff", strokeWidth: 2,
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
},
edits: [edit.geo.move(), edit.geo.create({ defaults: { place: "new pin" } })],
}),
],
});
mount(chart.dom());
```
### Example: Tiles under the neighbourhood outlines
geoTile() lays the imagery, geoBasemap() draws the boundaries over it (fill "none"), and the elicited marks sit on top of both. Dim the tiles with opacity so your data stays readable.
Try: **Drag** a study box; **click** open map to add one.
```javascript
const chart = Elicit({
width: 520, height: 360,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
data: [{ name: "study area", west: -123.140, south: 49.275, east: -123.100, north: 49.290 }],
schema: {
name: { type: "categorical" },
west: { type: "quantitative", domain: [-123.27, -123.02] },
south: { type: "quantitative", domain: [49.20, 49.32] },
east: { type: "quantitative", domain: [-123.27, -123.02] },
north: { type: "quantitative", domain: [49.20, 49.32] },
},
marks: [
// A lighter, less busy basemap than OSM standard. Any {z}/{x}/{y} server works.
geoTile({
url: "https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
subdomains: ["a", "b", "c"],
opacity: 0.85,
attribution: "© OpenStreetMap · © CARTO",
}),
// Vector boundaries on top of the imagery.
geoBasemap({ geojson: vancouver, fill: "none", stroke: "#20555A", strokeWidth: 0.8 }),
geoRect({
fill: "rgba(80, 174, 183, 0.18)", stroke: "#37919B", strokeWidth: 1.5,
channels: {
west: { field: "west" },
south: { field: "south" },
east: { field: "east" },
north: { field: "north" },
},
edits: [
edit.geo.brush({ edgeInset: 10 }),
edit.geo.createRect({ width: 0.024, height: 0.014, defaults: { name: "new area" } }),
],
}),
],
});
mount(chart.dom());
```
## Place and move points on the map
`geoPoint` places a row at its lon/lat through the projection. Click empty space to add a point, and drag one to move it. Lon/lat come back through `onChange` and `getData()`.
### Example: Pins on Vancouver
Seeded near Downtown & Kitsilano; click elsewhere to add more.
Try: **Click** to place a pin; **drag** an existing one.
```javascript
const chart = Elicit({
width: 520, height: 360,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
data: [
{ lon: -123.1207, lat: 49.2827, label: "Downtown" },
{ lon: -123.1560, lat: 49.2680, label: "Kits" },
],
schema: {
lon: { type: "quantitative", domain: [-123.27, -123.02] },
lat: { type: "quantitative", domain: [49.20, 49.32] },
label: { type: "categorical" },
},
marks: [
geoBasemap({ geojson: vancouver, fill: "#EDF7F8", stroke: "#46596B", strokeWidth: 0.8 }),
geoPoint({
size: 8, fill: "#50AEB7", stroke: "#fff", strokeWidth: 1.5,
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
},
edits: [edit.geo.move(), edit.geo.create()],
}),
],
});
mount(chart.dom());
```
## Label and rename places
`geoText` is a text mark positioned by the projection instead of x/y scales. Every other text behaviour carries over: `editText()` to retype the content, `cycle()` to advance a categorical label, `rotate()` on `angle`. Pair it with a `geoPoint` that reads the same rows, and the label follows when you drag the dot. `dx`/`dy` offset the text from its anchor and leave the lon/lat unchanged.
### Example: Named pins you can rename
geoPoint carries the drag; geoText carries the label. editText() opens an inline editor on double-click and writes the string back to the row.
Try: **Double-click** a name to retype it · **drag** a dot (the label follows) · **click** the map to add a pin.
```javascript
const chart = Elicit({
width: 520, height: 360,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
data: [
{ lon: -123.1207, lat: 49.2827, place: "Downtown" },
{ lon: -123.1560, lat: 49.2680, place: "Kitsilano" },
{ lon: -123.1000, lat: 49.2630, place: "Mt Pleasant" },
],
schema: {
lon: { type: "quantitative", domain: [-123.27, -123.02] },
lat: { type: "quantitative", domain: [49.20, 49.32] },
place: { type: "categorical" },
},
marks: [
geoBasemap({ geojson: vancouver, fill: "#EDF7F8", stroke: "#6F8294", strokeWidth: 0.7 }),
geoPoint({
size: 6, fill: "#1B3F60", stroke: "#fff", strokeWidth: 1.5,
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
},
edits: [edit.geo.move(), edit.geo.create({ defaults: { place: "new place" } })],
}),
// The label: same rows, positioned by the same projection, nudged above the dot.
geoText({
dy: -12, fontSize: 12, fill: "#20555A",
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
text: { field: "place" },
},
edits: [editText({ channel: "text" })],
}),
],
});
mount(chart.dom());
```
## Recolour neighbourhoods
Regions you already have are dataset rows with a `geometry` field: the basemap features you want answers for, copied into the data. The basemap underneath stays as it is. To reshape a region, see [Regions you can reshape](#regions).
### Example: Cycle fill on selected local areas
Kitsilano, Fairview, Mount Pleasant, Downtown — click to cycle category.
Try: **Click** a shaded neighbourhood to cycle its colour.
```javascript
const editable = vancouver.features
.filter(f => ["Kitsilano", "Fairview", "Mount Pleasant", "Downtown"].includes(f.properties.name))
.map(f => ({
name: f.properties.name,
geometry: f.geometry,
fill: "A",
}));
const chart = Elicit({
width: 520, height: 360,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
data: editable,
schema: {
name: { type: "categorical" },
fill: { type: "categorical", domain: ["A", "B", "C"] },
geometry: { type: "categorical" },
},
marks: [
geoBasemap({ geojson: vancouver, fill: "#EDF7F8", stroke: "#6F8294", strokeWidth: 0.7 }),
geoPolygon({
stroke: "#20555A", strokeWidth: 1.2, fillOpacity: 0.75,
channels: {
geometry: { field: "geometry", scale: null },
fill: {
field: "fill",
scale: { scheme: "dd" },
edit: cycle(),
},
},
}),
],
});
mount(chart.dom());
```
## Draw lines over the city
A `geoLine` with `lon`/`lat` channels draws one line across the rows, so each vertex is a row. `edit.geo.draw` adds a row at every step of a drag. Give the mark a `series` channel and each stroke starts a new line. `edit.geo.move` drags a vertex by its handle, and `remove` deletes one. Put `draw` and `move` on one mark: press a handle to reshape, or drag anywhere else to draw.
### Example: Draw a path across Vancouver
Each stroke is one route. Every vertex is a row with its own lon and lat.
Try: **Drag** across the map to sketch a route · **drag** a vertex to reshape it.
```javascript
const chart = Elicit({
width: 520, height: 360,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
data: [],
schema: {
route: { type: "categorical" }, // the series key: one per stroke
lon: { type: "quantitative", domain: [-123.27, -123.02] },
lat: { type: "quantitative", domain: [49.20, 49.32] },
},
marks: [
geoBasemap({ geojson: vancouver, fill: "#EDF7F8", stroke: "#46596B", strokeWidth: 0.8 }),
geoLine({
stroke: "#EE7B5E", strokeWidth: 2.5, handleSize: 4,
channels: {
series: { field: "route" },
lon: { field: "lon" },
lat: { field: "lat" },
},
// Press a vertex to move it; drag anywhere else to draw.
edits: [edit.geo.draw(), edit.geo.move()],
}),
],
});
mount(chart.dom());
```
### Example: Reshape a seeded Broadway line
Five seeded rows, one per vertex. edit.geo.move() drags each by its handle.
Try: **Drag** a vertex handle.
```javascript
const chart = Elicit({
width: 520, height: 360,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
// One row per vertex, in the order they connect.
data: [
{ lon: -123.185, lat: 49.264 },
{ lon: -123.155, lat: 49.263 },
{ lon: -123.120, lat: 49.263 },
{ lon: -123.080, lat: 49.262 },
{ lon: -123.050, lat: 49.261 },
],
schema: {
lon: { type: "quantitative", domain: [-123.27, -123.02] },
lat: { type: "quantitative", domain: [49.20, 49.32] },
},
marks: [
geoBasemap({ geojson: vancouver, fill: "#EDF7F8", stroke: "#46596B", strokeWidth: 0.8 }),
geoLine({
stroke: "#EE7B5E", strokeWidth: 2.5, handleSize: 6,
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
},
edits: [edit.geo.move()],
}),
],
});
mount(chart.dom());
```
## Connected scatter over the map
A `geoLine` and a `geoPoint` over the same rows draw a trail and its stops. Dragging a stop re-derives the trail. Rows connect in array order. An `order` channel sorts them by a column, and a `series` channel draws one trail per group.
For a line you already have, give `geoLine` a `coordinates` channel (a `[[lon, lat], …]` list on each row) or a `geometry` channel (a GeoJSON `LineString`). It draws one line per row.
### Example: A route across Vancouver
Five stops connected in `stop` order. The dots are a geoPoint mark with edit.geo.move(). The trail follows because both marks read the same dataset.
Try: **Drag** a stop to reroute; **click** the map to append one.
```javascript
const chart = Elicit({
width: 520, height: 360,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
data: [
{ stop: 1, lon: -123.1850, lat: 49.2720, place: "Kitsilano" },
{ stop: 2, lon: -123.1480, lat: 49.2660, place: "Fairview" },
{ stop: 3, lon: -123.1150, lat: 49.2640, place: "Mount Pleasant" },
{ stop: 4, lon: -123.1000, lat: 49.2790, place: "Strathcona" },
{ stop: 5, lon: -123.1207, lat: 49.2870, place: "Downtown" },
],
schema: {
stop: { type: "quantitative" },
lon: { type: "quantitative", domain: [-123.27, -123.02] },
lat: { type: "quantitative", domain: [49.20, 49.32] },
place: { type: "categorical" },
},
marks: [
geoBasemap({ geojson: vancouver, fill: "#EDF7F8", stroke: "#6F8294", strokeWidth: 0.7 }),
// The connector: lon/lat channels -> one path across the rows, in `stop` order.
geoLine({
stroke: "#EE7B5E", strokeWidth: 2,
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
// `order` is a channel: it names the column the trail is sorted by.
order: { field: "stop" },
},
}),
// The stops: their own feature, so a drag lands on one dot.
geoPoint({
size: 6, fill: "#EE7B5E", stroke: "#fff", strokeWidth: 1.5,
channels: {
lon: { field: "lon" },
lat: { field: "lat" },
},
edits: [edit.geo.move(), edit.geo.create({ defaults: { place: "new stop" } })],
}),
],
});
mount(chart.dom());
```
## Regions you can reshape
Give `geoPolygon` `lon`/`lat` channels and it draws a closed region across the rows, a row per vertex. A `series` channel draws one region per group. `edit.geo.move` drags a vertex, `edit.geo.moveSeries` drags the whole region by its inside, and `remove` deletes a vertex. `edit.geo.draw` adds a region: `when: when.far` keeps it to presses away from the regions already there. A `geoLine` takes the same form with `closed: true`.
### Example: A region you can reshape
Four seeded rows make one region. Draw another anywhere outside it.
Try: **Drag** a vertex to reshape · **drag** the inside to move it · **drag** across open map to draw another.
```javascript
const chart = Elicit({
width: 520, height: 360,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
// One row per vertex. `area` groups the rows into regions.
data: [
{ area: "a", lon: -123.160, lat: 49.280 },
{ area: "a", lon: -123.105, lat: 49.286 },
{ area: "a", lon: -123.090, lat: 49.258 },
{ area: "a", lon: -123.140, lat: 49.248 },
],
schema: {
area: { type: "categorical", domain: ["a"], open: true },
lon: { type: "quantitative", domain: [-123.27, -123.02] },
lat: { type: "quantitative", domain: [49.20, 49.32] },
},
marks: [
geoBasemap({ geojson: vancouver, fill: "#EDF7F8", stroke: "#46596B", strokeWidth: 0.8 }),
geoPolygon({
stroke: "#EE7B5E", strokeWidth: 2, handleSize: 5,
channels: {
series: { field: "area" },
lon: { field: "lon" },
lat: { field: "lat" },
},
edits: [
edit.geo.move(), // a vertex, by its handle
edit.geo.moveSeries(), // the whole region, by its inside
edit.geo.draw({ when: when.far }), // a new region, away from the others
],
}),
],
});
mount(chart.dom());
```
## Geographic rectangles
`geoRect` boxes are aligned to lon/lat, so they can look slightly curved under Mercator. Drag an edge or corner to reshape a box, drag its body to move it, or click empty space to add another. The zone you press in holds for the whole drag. The cursor shows the zone before you press.
### Example: Study areas over the city
edit.geo.brush() resizes and moves; edit.geo.createRect() mints a new box on a click in open space (a click on an existing box grabs it). Pass move: false for resize only, or { edgeInset } to widen the grab band.
Try: **Drag** a corner or edge to reshape · **drag** the middle to move · **click** empty map to add a box.
```javascript
const chart = Elicit({
width: 520, height: 360,
margins: { top: 8, right: 8, bottom: 8, left: 8 },
projection: { type: "mercator", domain: vancouver, inset: 6 },
data: [
{ name: "downtown", west: -123.140, south: 49.275, east: -123.100, north: 49.290 },
{ name: "west side", west: -123.185, south: 49.245, east: -123.150, north: 49.262 },
],
schema: {
name: { type: "categorical" },
west: { type: "quantitative", domain: [-123.27, -123.02] },
south: { type: "quantitative", domain: [49.20, 49.32] },
east: { type: "quantitative", domain: [-123.27, -123.02] },
north: { type: "quantitative", domain: [49.20, 49.32] },
},
marks: [
geoBasemap({ geojson: vancouver, fill: "#EDF7F8", stroke: "#6F8294", strokeWidth: 0.7 }),
geoRect({
fill: "rgba(80, 174, 183, 0.18)", stroke: "#37919B", strokeWidth: 1.5,
channels: {
west: { field: "west" },
south: { field: "south" },
east: { field: "east" },
north: { field: "north" },
},
edits: [
edit.geo.brush({ edgeInset: 10 }),
edit.geo.createRect({ width: 0.024, height: 0.014, defaults: { name: "new area" } }),
],
}),
],
});
mount(chart.dom());
```
---
# Network
> Source: https://elicitjs.github.io/marks/network/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A **network** is two tables, nodes and the links between them, declared with `structure: "network"`. `node()` draws a labelled dot, and `link()` draws one connector per link row, with arrowheads when directed; a `ports` channel marks where links can meet a node. `edit.network.connect`, `rewire` and `reverse` build the topology, and `create`, `move`, `editText` and `remove` work as on any other mark.
## API reference
### `link(options)`
Import `plot` from `elicitjs`. One line per row of the links table, drawn between the two nodes it references.
JSON keyword: `plot.link`
```ts
link({ channels, curve, curvature, spread, arrow, arrowSize, inset, sourceInset, targetInset, loopRadius, cornerRadius, sourceSide, targetSide, sourceOffset, targetOffset, labelBackground, labelPadding, labelRadius, labelOpacity, format, handles, handleSize, handleColor, table, edits, id }) → Mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | All optional. `source`/`target` name the reference columns (default: the link table’s two `ref` fields).`x`/`y` say how a *node* is positioned (default: the node table’s `x` and `y`). `text` draws a label on the path. `curve` and `arrow` take a column, so one mark can draw several kinds of connector. Style channels (`stroke`, `strokeWidth`, `opacity`) read the link row. `sourceSide`/`targetSide` with a `field` name the columns a connection writes its sides to. |
| `curve` | `"line" \| "step" \| "stepBefore" \| "stepAfter" \| "orthogonal" \| "arc" \| "bezier"` | `"line"` | The connector’s shape. `step` and its two variants are right-angled elbows drawn between node centres; `orthogonal`is the flowchart elbow, docked to each node’s box edge. `arc` is a quadratic bow and `bezier` a cubic with square tangents. A link whose source and target are the same node draws a loop whatever you set here. |
| `curvature` | `number \| "auto"` | `"auto"` | How far a link bows, as a fraction of its length. `"auto"` reads it off the data: links sharing a pair of nodes fan apart, and a pair joined by one link stays straight. A number bows every link by that amount. |
| `spread` | `number` | `0.16` | The gap between adjacent links of one pair under `curvature: "auto"`. |
| `arrow` | `"auto" \| "none" \| "target" \| "source" \| "both"` | `"auto"` | Which ends carry a filled triangle. `"auto"` draws one at the target end when the links table declares `directed: true`, and none otherwise. `true` and `false` are accepted for `"target"` and `"none"`. |
| `arrowSize` | `number` | `6` | Arrowhead length in px. The end it caps is inset by the same amount. |
| `loopRadius` | `number` | `22` | How far a self-loop reaches out from its node, in px. More loops on one node take other edges, then nest. |
| `inset` | `number` | `0` | The connection buffer: how far from a node’s shape a link stops, in px. `sourceInset` and `targetInset` set each end separately. An end at a port touches the port. With no node mark, it is measured from the node’s position. |
| `cornerRadius` | `number` | `8` | Rounds the turns of a `"orthogonal"` connector, in px. `0` draws square corners. |
| `sourceSide` | `null \| "top" \| "right" \| "bottom" \| "left"` | `null` | Which edge the connector leaves the source node by. `null` (the default) leaves it unpinned: it meets the facing port, or slides along a node that has no ports. A named edge pins it at that edge’s midpoint. `targetSide` does the same for the other end. Both read per row like `curve`. As a channel with a `field`, the column is also what `connect` and `rewire` write. |
| `sourceOffset` | `number \| channel` | `0` | Where along its edge the source end docks, as a fraction of the edge from the midpoint, `-0.4` to `0.4`. Positive runs clockwise around the box. `targetOffset` does the same for the other end. Both read per row like a side, and neither writes to the dataset. |
| `labelBackground` | `boolean \| string` | `off` | A plate behind `channels.text`, so a label sitting on its own connector stays readable. `true` uses the theme’s backdrop, which reads as a gap in the line; a colour string sets it outright. |
| `labelOpacity` | `number` | `0.9` | The plate’s fill opacity — lower it to let the connector show through. |
| `labelPadding` | `number` | `3` | Space between the label and the plate’s edge, in px. |
| `labelRadius` | `number` | `3` | The plate’s corner radius, in px. |
| `sourceInset / targetInset` | `number` | `inset` | Override `inset` for one end only. |
| `targetOffset` | `number \| channel` | `0` | Where along its edge the target end docks; see `sourceOffset`. |
| `targetSide` | `null \| "top" \| "right" \| "bottom" \| "left"` | `null` | Which edge the connector enters the target node by; see `sourceSide`. |
| `format` | `string \| fn` | `String` | Display formatter for `channels.text`: a d3-format string, or `(v) => string`. It formats the label; the column keeps its value. |
| `handles` | `boolean \| 'hit'` | `true` | Endpoint grips, drawn where a channel carries an edit. `'hit'` keeps the grip grabbable and invisible. |
| `handleSize` | `number` | `5` | Pixel radius of each endpoint grip. |
| `handleColor` | `string` | `theme` | Grip fill. Defaults to the theme’s `handle` colour. |
| `table` | `string` | `the links-role table` | Which table to draw, by name — the universal option every mark takes. You rarely need it here: `link` resolves the table filling the `links` role, whatever you called it. |
### `node(options)`
Import `plot` from `elicitjs`. A dot with a label, as one mark — a preset over `composite`, so it desugars into an ordinary `point` and `text`. Not network-specific: point it at any table.
JSON keyword: `plot.node`
```ts
node({ channels, dy, shape, size, format, table, edits, id }) → Mark[]
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | `x`/`y` are stated once for both parts. A `text` channel draws the label. Label channels (`fontSize`, `textAnchor`, `dx`) go to the text; every other channel (`fill`, `stroke`, `size`, `symbol`) goes to the dot. |
| `dy` | `number` | `-16` | Label offset in px, positive downwards. |
| `shape` | `"circle" \| "square"` | `"circle"` | Passed to the dot. |
| `format` | `string \| fn` | `String` | Display formatter for the label: a d3-format string, or `(v) => string`. Display-only. |
Returns / emits: Add the edits you want. Put `move()` on `x`, `editText()` on `text`, and `edit.network.connect()` on a `ports` channel. An edit on `x`/`y` grabs the dot.
### `channels.ports`
A channel on the mark that draws the nodes — `point`, `ellipse`, `rect`, `text`, `sticker`, `node`, `face` or a `composite`. It puts a dot on the edges a link may use, on the shape the mark draws. Put `edit.network.connect()` on it to drag new links from the dots.
```ts
ports: { value | fn | field, edit }
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `true \| side \| side[] \| { out, in }` | | Which edges get a dot. `true` is all four, either way. A side or a list of sides is those edges, either way. `{ out, in }` splits them on a directed network: links leave by `out` and arrive by `in`. `false` is none. Use `fn` or `field` to vary it per node. |
| `edit` | `Edit` | `none` | `edit.network.connect()` starts a link from a dot. With no edit, the dots appear while you drag a link’s end, as places to drop it. |
Returns / emits: Dots show where a link can go. Hover a node to see the edges a link can leave by. During a drag, the dots that accept the link light up.
### `edit.network.connect(options)`
Drag from a dot to another node to create a link. Put it on the node mark’s `ports` channel, or on the node mark itself. A dashed band follows the pointer. The row gets the columns the `link` mark’s channels name. A second link between one pair needs `multi: true` on the links table, and a link from a node to itself needs `selfLoops: true`.
JSON keyword: `edit.network.connect`
```ts
connect({ defaults, threshold, when, stage }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `defaults` | `object` | `{}` | Extra fields to seed the new link row with, over the schema’s defaults. |
| `threshold` | `number` | `28` | How near a node’s centre a drop connects, in px, when the nodes draw no shape. With a shape, a drop anywhere on the node connects, and a dot pins its edge. |
| `when` | `(ctx) => boolean` | `null` | Splits drags on a node mark that also carries `move`: pair `when.shift` with `when.noShift`. Leave it out on a `ports` channel. |
### `edit.network.rewire(options)`
Drag a link’s end to reconnect it. Put it in a `link` mark’s `edits`. Hover a connector to see a handle at each end. Drop the end on a dot to re-point it and pin that edge, on a node’s body to re-point it, or on empty space to remove the link. It follows the links table’s `multi` and `selfLoops` like `connect`.
JSON keyword: `edit.network.rewire`
```ts
rewire({ channels, threshold, when, stage }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `string[]` | `["source", "target"]` | Which ends get a handle. |
| `threshold` | `number` | `28` | How near the release must land to a node, in px. |
### `edit.network.reverse(options)`
Swap a link’s two ends. Put it on the `link` mark; it fires on a click anywhere along the line. Where the link records its sides in columns, they swap with the ends, so each node keeps its port.
JSON keyword: `edit.network.reverse`
```ts
reverse({ when, stage }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `when` | `(ctx) => boolean` | `null` | Needed when the link mark carries another click edit, such as `remove`. On a links table declared `directed: false` it logs a warning and leaves the row as it is. |
## Declaring the structure
`structure: "network"` gives the dataset two tables in the roles `nodes` and `links`. The default, `"table"`, is a single table declared as a bare field map.
```js
schema: {
structure: "network",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
links: {
source: { type: "ref" },
target: { type: "ref" },
weight: { type: "quantitative", domain: [0, 1] },
},
},
}
```
`key: true` marks the column that identifies a node. `type: "ref"` marks a column that names one; its domain is the key column's values. Pair `key` with `open: true` so a gesture that mints a node can give it a new identity.
`data` is keyed by table name. A table you leave out starts empty.
```js
data: {
nodes: [{ id: "a", label: "Ana", x: 20, y: 70 }],
links: [],
}
```
`getData()`, `onChange` and `setData` use the same shape.
### Example: Nodes, no links
links: [] — the topology is drawn by gesture.
Try: **Shift-drag** from one node to another to connect them. **Drag** a node to move it, **double-click** its label to rename it, **click** empty space to add one, and **Alt-click** to delete.
```javascript
const chart = Elicit({
width: 460, height: 280,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
links: {
source: { type: "ref" },
target: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "n1", label: "Start here", x: 24, y: 72 },
{ id: "n2", label: "Then here", x: 74, y: 66 },
{ id: "n3", label: "And here", x: 48, y: 22 },
],
links: [],
},
marks: [
link({ inset: 3, stroke: "#94A5B3", strokeWidth: 1.5 }),
node({
size: 10,
fill: "#50AEB7",
edits: [
edit.network.connect({ when: when.shift }),
create({ defaults: { label: "New node" } }),
remove({ when: when.alt }),
],
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], when: when.noShift }) },
y: { field: "y" },
text: { field: "label", edit: editText() },
},
}),
],
});
mount(chart.dom());
```
## Kinds of network
Three flags on the links table say what its pairs mean. Declare them on the long form:
```js
tables: {
nodes: { fields: { … } },
links: {
directed: true,
multi: true,
selfLoops: true,
fields: { source: { type: "ref" }, target: { type: "ref" } },
},
}
```
`directed` and `multi` together give the four usual kinds of network:
| kind | `directed` | `multi` | one pair may have |
| --- | --- | --- | --- |
| graph | `false` | — | one link |
| digraph | `true` | — | one link each way |
| multigraph | `false` | `true` | any number of links |
| multidigraph | `true` | `true` | any number, either way |
`selfLoops: true` adds links from a node to itself to any of the four. See [Parallel links and loops](#multi).
- `directed: true` draws an arrowhead at the target and bows reciprocal links apart, so `a → b` and `b → a` stay readable. It also enables `edit.network.reverse`.
- `directed: false` treats a pair as unordered: `b → a` is the same link as `a → b`.
- With `directed` left out, links draw without arrowheads, and `a → b` and `b → a` are two different links.
### Example: Directed links
directed: true — arrowheads, and a reciprocal pair that bows apart.
Try: **Alt-click** a connector to reverse it. **Shift-drag** between two nodes to add another — connect them the other way round too, and the pair bows apart. **Drag** a node to move it.
```javascript
const chart = Elicit({
width: 460, height: 280,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
name: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
links: {
role: "links",
directed: true,
fields: {
source: { type: "ref" },
target: { type: "ref" },
},
},
},
},
data: {
nodes: [
{ id: "a", name: "Ana", x: 20, y: 68 },
{ id: "b", name: "Ben", x: 76, y: 68 },
{ id: "c", name: "Cleo", x: 48, y: 20 },
],
links: [
{ source: "a", target: "b" },
{ source: "b", target: "a" },
{ source: "b", target: "c" },
],
},
marks: [
link({
inset: 3,
stroke: "#94A5B3",
strokeWidth: 1.5,
edits: [edit.network.reverse({ when: when.alt })],
}),
node({
size: 10,
fill: "#50AEB7",
edits: [edit.network.connect({ when: when.shift })],
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], when: when.noShift }) },
y: { field: "y" },
text: { field: "name" },
},
}),
],
});
mount(chart.dom());
```
## Parallel links and loops
`multi: true` lets `connect` and `rewire` add a link between two nodes that already share one. Links between the same two nodes fan apart (`curvature: "auto"`).
`selfLoops: true` lets them link a node to itself. Drag from a port to another port of the same node, or move off the port and release on the node's body.
A link from a node to itself draws as a loop. It leaves and returns by one edge, or goes round the node from an `out` port to an `in` port. More loops on the same node take the free edges first, then nest outward. `loopRadius` sets how far a loop reaches (default `22`).
Rows holding a parallel pair or a loop always draw. With `multi: false` or `selfLoops: false`, they also log a warning.
### Example: A state machine
directed, multi and selfLoops: two events from Open to Closed, and events that leave a state where it was.
Try: **Hover** a state and drag from a port to another state to add a transition, even where one already runs. Drag to another port of the same state to add a loop. **Double-click** a label to rename the event. **Hover** a transition and drag an end to move it, or into empty space to delete it.
```javascript
const chart = Elicit({
width: 560, height: 240,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
states: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
transitions: {
role: "links",
// A multidigraph with loops: two events may join the same pair of
// states, and an event may leave a state where it was.
directed: true,
multi: true,
selfLoops: true,
fields: {
source: { type: "ref" },
target: { type: "ref" },
event: { type: "categorical", open: true },
},
},
},
},
data: {
states: [
{ id: "locked", label: "Locked", x: 12, y: 62 },
{ id: "closed", label: "Closed", x: 50, y: 62 },
{ id: "open", label: "Open", x: 88, y: 62 },
],
transitions: [
{ source: "closed", target: "open", event: "open" },
{ source: "open", target: "closed", event: "close" },
{ source: "open", target: "closed", event: "slam" },
{ source: "closed", target: "locked", event: "lock" },
{ source: "locked", target: "closed", event: "unlock" },
{ source: "locked", target: "locked", event: "wrong key" },
{ source: "closed", target: "closed", event: "knock" },
],
},
marks: [
link({
stroke: "#46596B",
strokeWidth: 1.5,
labelBackground: true,
channels: { text: { field: "event" } },
edits: [edit.network.rewire(), editText()],
}),
sticker({
fill: "#ECF3F9",
stroke: "#1D4467",
cornerRadius: 14,
maxWidth: 90,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "label" },
ports: { value: true, edit: edit.network.connect({ defaults: { event: "event" } }) },
},
}),
],
});
mount(chart.dom());
```
## Naming the tables
Name the tables for your data, and give each a `role`:
```js
tables: {
claims: { role: "nodes", fields: { … } },
supports: { role: "links", fields: { … } },
}
```
`data` and `getData()` are then keyed `claims` and `supports`. Marks and edits find their table by role, so `link()` draws `supports` by default. The [argument map](#draw) below uses these names.
## Drawing a network
`node()` draws a dot with a label above it. It takes `x` and `y` once for both, and draws the label from a `text` channel. It is a preset over `composite` and works on any table. Any other mark can draw the nodes too; see [What can be a node](#node-marks).
`link()` draws the links table. Each end sits at the node its `ref` column names.
### Example: Argument map
Nodes carry a claim; links point from a reason to what it supports.
Try: **Drag** a node to move it. **Shift-drag** from one node to another to connect them. **Click** empty space to add a claim, **double-click** its label to write it, and **Alt-click** a node to delete it.
```javascript
const chart = Elicit({
width: 460, height: 300,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
claims: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
text: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
supports: {
role: "links",
fields: {
source: { type: "ref" },
target: { type: "ref" },
},
},
},
},
data: {
claims: [
{ id: "c1", text: "Ban cars downtown", x: 50, y: 78 },
{ id: "c2", text: "Cuts emissions", x: 20, y: 28 },
{ id: "c3", text: "Hurts shops", x: 80, y: 28 },
],
supports: [
{ source: "c2", target: "c1" },
{ source: "c3", target: "c1" },
],
},
marks: [
link({ arrow: true, inset: 3, stroke: "#94A5B3" }),
node({
size: 11,
fill: "#50AEB7",
edits: [
edit.network.connect({ when: when.shift }),
create({ defaults: { text: "New claim" } }),
remove({ when: when.alt }),
],
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], when: when.noShift }) },
y: { field: "y" },
text: { field: "text", edit: editText() },
},
}),
],
});
mount(chart.dom());
```
## Connector styles
`curve` sets a link's shape:
| `curve` | shape |
| --- | --- |
| `"line"` | straight segment (the default) |
| `"step"` | right-angled elbow, turning midway |
| `"stepBefore"` / `"stepAfter"` | elbow turning at the source / at the target |
| `"orthogonal"` | elbow that leaves each node square out of one of its edges |
| `"arc"` | quadratic bow to one side |
| `"bezier"` | cubic with square tangents |
The `"step"` kinds turn on the straight line between two node positions. `"orthogonal"` leaves and arrives perpendicular to an edge of the node's shape; see [Where a link meets a node](#routing). `cornerRadius` rounds its turns (default `8`; `0` is square).
Give `curve` a column to mix shapes in one mark:
```js
link({ channels: { curve: { field: "kind" } } })
```
Any column works, or `{ fn: d => … }` to map one. `arrow` reads a column the same way, so one field can drive both shape and arrowheads.
`curvature` sets how far a link bows. The default, `"auto"`, fans out links that share a pair of nodes and keeps a lone link straight. On a directed network every link bows to the same side of its direction, so `a → b` and `b → a` separate. Pass a number to bow every link equally, and `spread` to change the gap `"auto"` leaves between siblings.
Under `"auto"`, a lone `"arc"` draws straight. A `"line"` with curvature draws as an arc, so links sharing a pair fan apart on a plain `link()`.
A link whose source and target are the same node draws a loop; see [Parallel links and loops](#multi).
A `click` edit such as `reverse` or `remove` responds anywhere along the line.
### Example: Connector shapes
One link() mark, a kind column driving curve, at a fixed curvature: 0.1.
Try: **Click** a connector to step it to the next shape in the `kind` domain. The label is the column, so it changes with it — and stepping one to `line` draws an arc, since this mark sets a curvature.
```javascript
const chart = Elicit({
width: 460, height: 330,
margins: { top: 18, right: 34, bottom: 18, left: 34 },
axes: false,
schema: {
structure: "network",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
links: {
source: { type: "ref" },
target: { type: "ref" },
kind: {
type: "categorical",
domain: ["line", "step", "stepBefore", "stepAfter", "orthogonal", "arc", "bezier"],
},
},
},
},
data: {
nodes: [
{ id: "l1", x: 6, y: 92 }, { id: "r1", x: 94, y: 82 },
{ id: "l2", x: 6, y: 73 }, { id: "r2", x: 94, y: 63 },
{ id: "l3", x: 6, y: 54 }, { id: "r3", x: 94, y: 44 },
{ id: "l4", x: 6, y: 35 }, { id: "r4", x: 94, y: 25 },
{ id: "l5", x: 6, y: 16 }, { id: "r5", x: 94, y: 6 },
],
links: [
{ source: "l1", target: "r1", kind: "step" },
{ source: "l2", target: "r2", kind: "stepBefore" },
{ source: "l3", target: "r3", kind: "stepAfter" },
{ source: "l4", target: "r4", kind: "arc" },
{ source: "l5", target: "r5", kind: "bezier" },
],
},
marks: [
link({
inset: 4,
stroke: "#50AEB7",
strokeWidth: 2,
// A fixed bow. These links share no pair of nodes, so "auto" would leave
// every one of them flat — including the arc, whose only parameter this is.
curvature: 0.1,
fontSize: 11,
labelBackground: true,
channels: {
curve: { field: "kind" },
text: { field: "kind" },
},
edits: [cycle({ channels: ["curve"] })],
}),
point({ size: 4, fill: "#94A5B3", channels: { x: { field: "x" }, y: { field: "y" } } }),
],
});
mount(chart.dom());
```
## Where a link meets a node
A link meets the shape the node mark draws: a dot's circle, a rect's edges, a sticker's paper. With no node mark, it ends at each node's position.
How an end meets the shape depends on whether the node has [ports](#ports):
- **With ports**, an end connects to a port. A pinned end uses the port on its side. An unpinned end uses the usable port facing the other node, and switches ports when the nodes pass each other.
- **Without ports**, an unpinned end slides. It sits where the line between the two centres leaves the shape, and moves smoothly as the nodes move. A pinned end sits at the middle of its edge.
`inset` sets how far from a node's shape a link stops, in px (default `0`). `sourceInset` and `targetInset` set each end. An end at a port touches the port. An arrowhead fits in the gap.
An `"orthogonal"` connector leaves each end square to its edge and joins the two with the fewest turns. Two sliding ends nearly in line join with one straight leg; further apart, they join with a Z. It routes around a node in the way. Overlapping nodes get the plain route. `"line"` and `"bezier"` connectors also meet the shape, and a bezier leaves a pinned edge square-on.
A node turned by `angle` turns its edges and ports with it, and a side names the node's own edge. An `"orthogonal"` connector runs on the screen's axes, so it meets a turned node on the upright box around it.
`sourceOffset` and `targetOffset` move a pinned end along its edge, as a fraction from `-0.4` to `0.4`. Positive runs clockwise: right along the top, down the right, left along the bottom, up the left.
### Example: Routing
Notes without ports: one connector straightened, one detouring around a node, one taking the perpendicular edges.
Try: **Drag** *Legal review* out of the way and the long connector takes the direct route. **Drag** *Score* sideways and its connector from *Collect* goes from straight to a Z. **Drag** *Ship* in a circle round *Publish* and watch the ends slide along the boxes.
```javascript
const chart = Elicit({
width: 520, height: 360,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
schema: {
structure: "network",
tables: {
steps: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 480] },
y: { type: "quantitative", domain: [0, 320] },
w: { type: "quantitative", domain: [40, 200] },
h: { type: "quantitative", domain: [24, 200] },
},
},
flows: {
role: "links",
directed: true,
fields: { source: { type: "ref" }, target: { type: "ref" } },
},
},
},
data: {
steps: [
// Collect sits 8px out of line with Score: close enough to join straight.
{ id: "collect", label: "Collect", x: 60, y: 220, w: 92, h: 40 },
{ id: "score", label: "Score", x: 68, y: 110, w: 92, h: 40 },
// Review stands in the corridor between Score and Publish.
{ id: "review", label: "Legal review", x: 200, y: 150, w: 72, h: 180 },
// Ship is up and to the right of Publish, with a tight gap between them.
{ id: "publish", label: "Publish", x: 300, y: 120, w: 80, h: 40 },
{ id: "ship", label: "Ship", x: 430, y: 46, w: 80, h: 40 },
],
flows: [
{ source: "collect", target: "score" },
{ source: "score", target: "publish" },
{ source: "publish", target: "ship" },
],
},
marks: [
link({
curve: "orthogonal",
inset: 4,
stroke: "#50AEB7",
strokeWidth: 2,
}),
sticker({
fill: "#EDF7F8",
stroke: "#37919B",
cornerRadius: 6,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
text: { field: "label" },
},
}),
],
});
mount(chart.dom());
```
## Ports
A **port** is a dot on a node's edge where a link starts or ends. Declare ports with a `ports` channel on the mark that draws the nodes (any mark in [What can be a node](#node-marks)), and put `edit.network.connect()` on it:
```js
sticker({
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "label" },
ports: {
value: { out: ["right"], in: ["left"] },
edit: edit.network.connect(),
},
},
})
```
The value sets which edges a link may use. Use `fn` or `field` instead of `value` to vary it per node.
| `value` | ports |
| --- | --- |
| `true` | all four edges, either way |
| `"right"` or `["left", "right"]` | those edges, either way |
| `{ out: ["right"], in: ["left"] }` | links leave by the right and arrive by the left (directed networks) |
| `false` | none |
Hover a node to see the ports a link can leave by. Start a drag and the ports that accept it light up. Both follow the `out` and `in` edges and the dataset's constraints.
Drag from a port and a dashed connector follows the pointer. Release on a port to connect there, or on a node's body to connect at its facing port. Release on empty space to cancel. Drag the body to move the node.
### Example: Connecting from ports
Stickers whose links leave by the right and arrive by the left.
Try: **Hover** a note: one port, on the right. **Drag** from it and only left-hand ports appear. Drop on one and `getData()` gains a row with both sides.
```javascript
const chart = Elicit({
width: 520, height: 320,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
notes: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
flows: {
role: "links",
directed: true,
fields: {
source: { type: "ref" },
target: { type: "ref" },
// The edge each end meets, or null to slide along the box.
fromSide: { type: "categorical", domain: ["top", "right", "bottom", "left"] },
toSide: { type: "categorical", domain: ["top", "right", "bottom", "left"] },
},
},
},
},
data: {
notes: [
{ id: "idea", label: "Idea", x: 14, y: 72 },
{ id: "draft", label: "Draft", x: 48, y: 72 },
{ id: "review", label: "Review", x: 84, y: 24 },
{ id: "ship", label: "Ship", x: 84, y: 80 },
],
flows: [
{ source: "idea", target: "draft", fromSide: "right", toSide: "left" },
{ source: "draft", target: "review", fromSide: "right", toSide: "left" },
],
},
marks: [
link({
curve: "orthogonal",
stroke: "#50AEB7",
strokeWidth: 2,
// The columns a connection writes.
channels: {
sourceSide: { field: "fromSide" },
targetSide: { field: "toSide" },
},
edits: [edit.network.rewire(), remove({ when: when.alt })],
}),
sticker({
fill: "#EDF7F8",
stroke: "#37919B",
cornerRadius: 6,
maxWidth: 110,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "label" },
// Links leave by the right edge and enter by the left.
ports: {
value: { out: ["right"], in: ["left"] },
edit: edit.network.connect(),
},
},
}),
],
});
mount(chart.dom());
```
`ports: true` lets any edge connect to any edge, for a diagram you lay out freely.
### Example: Any side to any side
An undirected concept map. Two ties are pinned to edges; two meet whichever port faces the other note.
Try: **Drag** *What is at stake* above *Trust in forecasts*: its unpinned tie moves to the facing ports. **Drag** from any port to any other note. **Click** empty space for a new idea, **double-click** one to rename it.
```javascript
const chart = Elicit({
width: 560, height: 340,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
ideas: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
ties: {
role: "links",
directed: false,
fields: {
source: { type: "ref" },
target: { type: "ref" },
fromSide: { type: "categorical", domain: ["top", "right", "bottom", "left"] },
toSide: { type: "categorical", domain: ["top", "right", "bottom", "left"] },
},
},
},
},
data: {
ideas: [
{ id: "trust", label: "Trust in forecasts", x: 50, y: 50 },
{ id: "past", label: "Past accuracy", x: 14, y: 18 },
{ id: "source", label: "Who made it", x: 86, y: 18 },
{ id: "range", label: "Shown as a range", x: 14, y: 84 },
{ id: "stakes", label: "What is at stake", x: 86, y: 84 },
],
ties: [
{ source: "trust", target: "past", fromSide: "top", toSide: "right" },
{ source: "trust", target: "source", fromSide: "right", toSide: "bottom" },
// Unpinned: each end meets the port facing the other note.
{ source: "trust", target: "range", fromSide: null, toSide: null },
{ source: "trust", target: "stakes", fromSide: null, toSide: null },
],
},
marks: [
link({
curve: "bezier",
stroke: "#8A78C0",
strokeWidth: 1.5,
channels: {
sourceSide: { field: "fromSide" },
targetSide: { field: "toSide" },
},
edits: [edit.network.rewire(), remove({ when: when.alt })],
}),
sticker({
fill: "#EDF7F8",
stroke: "#6B5AA2",
cornerRadius: 8,
maxWidth: 120,
edits: [editText(), create({ defaults: { label: "New idea" } })],
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "label" },
// Every edge, either way.
ports: { value: true, edit: edit.network.connect() },
},
}),
],
});
mount(chart.dom());
```
## Recording sides
To record which edge each end uses, name the columns in `sourceSide` and `targetSide` channels on the `link` mark. Declare them in the links table as `categorical` over `"top"`, `"right"`, `"bottom"` and `"left"`:
```js
link({
channels: {
sourceSide: { field: "fromSide" },
targetSide: { field: "toSide" },
},
})
```
The gestures write those columns, and write `source` and `target` to the links table's `ref` columns:
| gesture | the links table |
| --- | --- |
| port to port | a new row, with both sides |
| port to a node’s body | a new row; the target side is `null` |
| a link’s end to another node | that row re-pointed, with its new side |
| a link’s end to empty space | that row removed |
A `null` side is unpinned. It meets the facing port, or slides along a node that has no ports. With no side channel or [side option](#sides), every end is unpinned.
`edit.network.rewire()` in the `link` mark's `edits` puts a handle on each end while you hover the connector. Drag one to another node to reconnect it, or into empty space to disconnect it. `rewire({ channels: ["target"] })` handles one end only.
### Example: Reconnect and disconnect
node() dots with ports on the left and right, and rewire on the link.
Try: **Drag** from a port to another node’s port. **Hover** a connector, then drag its end onto another node to reconnect it, or into space to disconnect it.
```javascript
const chart = Elicit({
width: 460, height: 280,
margins: { top: 28, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
name: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
links: {
source: { type: "ref" },
target: { type: "ref" },
sourceSide: { type: "categorical", domain: ["left", "right"] },
targetSide: { type: "categorical", domain: ["left", "right"] },
},
},
},
data: {
nodes: [
{ id: "a", name: "Ana", x: 16, y: 70 },
{ id: "b", name: "Ben", x: 84, y: 70 },
{ id: "c", name: "Cleo", x: 50, y: 20 },
],
links: [
{ source: "a", target: "c", sourceSide: "right", targetSide: "left" },
{ source: "c", target: "b", sourceSide: "right", targetSide: "left" },
],
},
marks: [
link({
curve: "bezier",
stroke: "#94A5B3",
strokeWidth: 1.5,
channels: {
sourceSide: { field: "sourceSide" },
targetSide: { field: "targetSide" },
},
// Hover a connector for a handle at each end.
edits: [edit.network.rewire()],
}),
node({
size: 10,
fill: "#50AEB7",
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"] }) },
y: { field: "y" },
text: { field: "name" },
ports: { value: ["left", "right"], edit: edit.network.connect() },
},
}),
],
});
mount(chart.dom());
```
Constraints decide which ports show. Here each step shows an `out` port until it has one outgoing link.
### Example: Only usable ports
An end step takes links in but sends none out, and a constraint allows each step one outgoing link.
Try: **Hover** *Ask*: no port, since it already leads somewhere. **Hover** *Done*: no port either. **Drag** from *Check* and only the left-hand ports of the other steps appear. Drag the end of *Ask*’s link into space and its port comes back.
```javascript
const chart = Elicit({
width: 520, height: 300,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
steps: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["step", "end"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
next: {
role: "links",
directed: true,
fields: {
source: { type: "ref" },
target: { type: "ref" },
fromSide: { type: "categorical", domain: ["top", "right", "bottom", "left"] },
toSide: { type: "categorical", domain: ["top", "right", "bottom", "left"] },
},
},
},
},
data: {
steps: [
{ id: "ask", label: "Ask", kind: "step", x: 12, y: 50 },
{ id: "check", label: "Check", kind: "step", x: 42, y: 20 },
{ id: "fix", label: "Fix", kind: "step", x: 42, y: 80 },
{ id: "done", label: "Done", kind: "end", x: 86, y: 50 },
],
next: [{ source: "ask", target: "check", fromSide: "right", toSide: "left" }],
},
// Each step leads to one next step.
constraints: [
constraints.custom(({ data }) => {
const sources = data.map((d) => d.source);
return new Set(sources).size === sources.length;
}, { table: "links" }),
],
marks: [
link({
curve: "orthogonal",
stroke: "#6F8294",
strokeWidth: 1.5,
channels: {
sourceSide: { field: "fromSide" },
targetSide: { field: "toSide" },
},
edits: [edit.network.rewire()],
}),
sticker({
cornerRadius: 6,
maxWidth: 100,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "label" },
fill: { field: "kind", scale: { range: ["#F9F4EC", "#F0F7EE"] } },
// An end step takes links in but sends none out.
ports: {
fn: (d) => (d.kind === "end" ? { in: ["left"] } : { out: ["right"], in: ["left"] }),
edit: edit.network.connect(),
},
},
}),
],
});
mount(chart.dom());
```
## Pinned sides
As options, `sourceSide` and `targetSide` pin every link's ends to `"top"`, `"right"`, `"bottom"` or `"left"`, so a diagram reads the same way however the boxes are arranged. Both default to `null`. A pinned end leaves its edge square-on, and routes around its own box if the other node is behind it.
The options set how links draw and write nothing to the data. Give one `{ fn: d => … }` to derive a side from a column you already have. To record sides in the data, use channels; see [Recording sides](#recording).
### Example: Pinned sides
curve: orthogonal with sourceSide and targetSide fixed, so flow reads left to right.
Try: **Drag** a stage anywhere. Every connector still leaves the right edge and enters the left one, and `getData()` changes only `x` and `y`.
```javascript
const chart = Elicit({
width: 460, height: 320,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
schema: {
structure: "network",
tables: {
stages: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [40, 200] },
h: { type: "quantitative", domain: [24, 120] },
},
},
flows: {
role: "links",
directed: true,
fields: { source: { type: "ref" }, target: { type: "ref" } },
},
},
},
data: {
stages: [
{ id: "a", label: "Collect", x: 22, y: 76, w: 92, h: 40 },
{ id: "b", label: "Score", x: 70, y: 76, w: 92, h: 40 },
{ id: "c", label: "Publish", x: 46, y: 22, w: 92, h: 40 },
],
flows: [
{ source: "a", target: "b" },
{ source: "b", target: "c" },
],
},
marks: [
link({
curve: "orthogonal",
cornerRadius: 10,
inset: 4,
stroke: "#50AEB7",
strokeWidth: 2,
// Every flow leaves the right of its stage and enters the left of the next,
// wherever the two boxes end up. Drop the two sides to let position choose.
sourceSide: "right",
targetSide: "left",
}),
sticker({
fill: "#EDF7F8",
stroke: "#37919B",
cornerRadius: 6,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
text: { field: "label" },
},
}),
],
});
mount(chart.dom());
```
## What can be a node
Any mark that draws a shape at an `x` and a `y` can draw the nodes: `point`, `rect`, `text`, a `composite`, and the rest. Point it at the nodes table; channels, scales and edits work as usual. See [Which table a mark draws](https://elicitjs.github.io/schema.md#table).
Links meet the shape the mark draws, and a [`ports`](#ports) channel puts ports on that shape's edges:
| mark | a link meets |
| --- | --- |
| `point`, `node` | the dot's circle, or a square symbol's edges |
| `ellipse` | the ellipse, at `rx` and `ry` |
| `rect`, `sticker` | the box's edges |
| `text` | the box around the measured text, so an emoji or a word works |
| `face`, any `composite` placing parts in its [box](https://elicitjs.github.io/marks/composite.md#box) | the box's circle |
| any other `composite` | its first part that draws a shape |
A glyph puts `ports` on its main shape: the box's circle, or its first shape part. When a glyph draws a shape and a label, links meet the shape, so a `node()`'s links meet its dot.
### Example: Emoji as nodes
A plain text() mark draws the nodes, with ports on every side of each emoji.
Try: **Hover** an emoji and drag from a port to another to link them. **Drag** an emoji to move it. **Hover** a link and drag its end to re-point it, or into empty space to remove it.
```javascript
const chart = Elicit({
width: 540, height: 260,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
feelings: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
emoji: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
leadsTo: {
role: "links",
directed: true,
fields: { source: { type: "ref" }, target: { type: "ref" } },
},
},
},
data: {
feelings: [
{ id: "tired", emoji: "😴", x: 12, y: 50 },
{ id: "stressed", emoji: "😟", x: 40, y: 82 },
{ id: "angry", emoji: "😠", x: 68, y: 82 },
{ id: "calm", emoji: "😌", x: 40, y: 18 },
{ id: "happy", emoji: "😀", x: 88, y: 50 },
],
leadsTo: [
{ source: "tired", target: "stressed" },
{ source: "stressed", target: "angry" },
{ source: "tired", target: "calm" },
{ source: "calm", target: "happy" },
],
},
marks: [
link({ curve: "arc", curvature: 0.15, stroke: "#94a3b8", strokeWidth: 1.5, edits: [edit.network.rewire()] }),
// A plain text mark is the node: its glyph's box is where links meet it.
text({
fontSize: 36,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "emoji" },
ports: { value: true, edit: edit.network.connect() },
},
}),
],
});
mount(chart.dom());
```
## Faces as nodes
To draw the nodes with [`face`](https://elicitjs.github.io/marks/face.md), give it `x` and `y` columns on the nodes table and put the `ports` channel on it. Here a link leaves by the right or the bottom and arrives by the left or the top. The face keeps its own edits: `move` on the head, and `slide` on the mouth.
### Example: Whose mood rubs off on whom
face() over a network's nodes table, with ports out on the right and bottom and in on the left and top.
Try: **Hover** a face and drag from a port to another face to link them. **Drag** a mouth to change the mood, or a face to move it.
```javascript
const chart = Elicit({
width: 540, height: 320,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
people: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
valence: { type: "quantitative", domain: [-1, 1] },
arousal: { type: "quantitative", domain: [-1, 1] },
},
},
sways: {
role: "links",
// Whose mood rubs off on whom.
directed: true,
fields: { source: { type: "ref" }, target: { type: "ref" } },
},
},
},
data: {
people: [
{ id: "ana", x: 16, y: 72, valence: 0.7, arousal: 0.3 },
{ id: "ben", x: 50, y: 22, valence: -0.6, arousal: 0.5 },
{ id: "cy", x: 84, y: 72, valence: 0.1, arousal: -0.4 },
],
sways: [
{ source: "ana", target: "ben" },
{ source: "ben", target: "cy" },
],
},
marks: [
link({
curve: "bezier",
stroke: "#94a3b8",
strokeWidth: 1.5,
edits: [edit.network.rewire()],
}),
face({
size: 34,
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
mouthCurve: { field: "valence", edit: slide({ axis: "y", increase: "up" }) },
eyeScale: { field: "arousal" },
// A link leaves a face on the right or below, and arrives on the left or above.
ports: {
value: { out: ["right", "bottom"], in: ["left", "top"] },
edit: edit.network.connect(),
},
},
}),
],
});
mount(chart.dom());
```
## Building the topology
Three edits are specific to networks. The rest is ordinary editing.
`edit.network.connect()` creates a link. Put it on a [`ports`](#ports) channel, or in the node mark's `edits` to drag from a node's body. On the body, separate it from `move` with `when`: `connect({ when: when.shift })` beside `move({ when: when.noShift })`. With `selfLoops: true`, release on the starting node to draw a loop. When the nodes draw no shape, a drop within `threshold` px of a node's centre connects.
`edit.network.rewire()` moves a link's ends; see [Recording sides](#recording).
`edit.network.reverse()` on the `link` mark swaps the two ends on a click. Columns the link records its sides in swap with the ends, so each node keeps the port the link meets it at. Every other column stays. Give it a `when` if the mark carries another click edit. On `directed: false` it leaves the row unchanged and logs a warning.
`create()` mints a node where you click. The node table's `key` gives it an identity, so you can link it straight away.
`remove()` deletes a node and every link to it.
[`ui.network()`](https://elicitjs.github.io/ui/network.md) puts these edits behind icons and a menu: a **+** beside a port that adds a linked node, link and detach icons beside it, and a right-click menu to add a node of a chosen category.
### Example: Weighted links
A link's own columns drive its width and colour, and rewire moves its source end.
Try: **Drag** a name to move it. **Hover** a link, then drag the handle at its source end onto a different person to re-point it.
```javascript
const chart = Elicit({
width: 440, height: 280,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
name: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
links: {
source: { type: "ref" },
target: { type: "ref" },
strength: { type: "quantitative", domain: [0, 1], default: 0.5 },
},
},
},
data: {
nodes: [
{ id: "a", name: "Ana", x: 20, y: 70 },
{ id: "b", name: "Ben", x: 70, y: 82 },
{ id: "c", name: "Cleo", x: 78, y: 26 },
{ id: "d", name: "Dev", x: 26, y: 20 },
],
links: [
{ source: "a", target: "b", strength: 0.9 },
{ source: "b", target: "c", strength: 0.3 },
{ source: "c", target: "d", strength: 0.6 },
{ source: "d", target: "a", strength: 0.2 },
],
},
marks: [
link({
inset: 3,
channels: {
strokeWidth: { field: "strength", scale: { range: [1, 7] } },
stroke: { field: "strength", scale: { scheme: "ddramp" } },
},
// A handle at each link's source end, shown when you hover the link.
edits: [edit.network.rewire({ channels: ["source"] })],
}),
node({
size: 10,
fill: "#20555A",
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"] }) },
y: { field: "y" },
text: { field: "name" },
},
}),
],
});
mount(chart.dom());
```
## Link attributes
A link row is a row like any other. Give the links table columns, then encode them on `link()`'s style channels or edit them with `set`, `cycle` and `editText`.
`channels.text` draws a label at the midpoint, and takes `editText()` as a `text` mark does. Double-click anywhere along the connector to open the editor.
`stroke` and `strokeWidth` paint the connector and its arrowhead. `fill` paints the label (default: the theme's ink).
A label sits on its connector. `labelBackground` puts a plate behind it:
```js
link({ labelBackground: true, channels: { text: { field: "note" } } })
```
`true` uses the theme's backdrop, which reads as a gap in the line. Pass a colour string for any other plate. `labelOpacity` (default `0.9`) sets how much of the connector shows through. `labelPadding` and `labelRadius` size the plate.
### Example: Link attributes
A link's own columns drive its width, its colour and its label.
Try: **Double-click** a connector to retype its label. **Drag** a name to move it — the connectors and their labels follow.
```javascript
const chart = Elicit({
width: 460, height: 290,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
structure: "network",
tables: {
people: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
name: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
ties: {
role: "links",
fields: {
source: { type: "ref" },
target: { type: "ref" },
note: { type: "categorical", open: true },
trust: { type: "quantitative", domain: [0, 1] },
},
},
},
},
data: {
people: [
{ id: "a", name: "Ana", x: 18, y: 70 },
{ id: "b", name: "Ben", x: 80, y: 72 },
{ id: "c", name: "Cleo", x: 50, y: 20 },
],
ties: [
{ source: "a", target: "b", note: "worked together", trust: 0.9 },
{ source: "b", target: "c", note: "met once", trust: 0.25 },
],
},
marks: [
link({
inset: 3,
fontSize: 11,
labelBackground: true,
channels: {
strokeWidth: { field: "trust", scale: { range: [1, 6] } },
stroke: { field: "trust", scale: { scheme: "ddramp" } },
text: { field: "note" },
},
edits: [editText()],
}),
node({
size: 10,
fill: "#20555A",
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"] }) },
y: { field: "y" },
text: { field: "name" },
},
}),
],
});
mount(chart.dom());
```
---
# Hierarchy
> Source: https://elicitjs.github.io/marks/hierarchy/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A **hierarchy** is nodes that sit inside each other, declared with `structure: "hierarchy"`: one table of nodes, and a `nesting` table with one row per containment. `constraints.contain` governs which rows can hold others, [layout](https://elicitjs.github.io/layout.md) rules size containers and arrange their contents (`layout.hierarchy.contain`, `layout.dodge`, `layout.row`, `layout.column`, `layout.grid`, `layout.pack`), and `edit.hierarchy.nest` drops a node into a container or out of one. A mark's `contains` option is a shorthand for container eligibility and fitting on that mark.
## API reference
### `structure: "hierarchy"`
Three tables: `nodes`, `nesting` and an optional `links`. One nesting row says one node is inside another.
```ts
schema: { structure: "hierarchy", tables: { nodes, nesting, links? } }
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `nodes` | `table` | `required` | One row per node. Needs a `key: true` column. Named anything with `role: "nodes"`. |
| `nesting` | `table` | `required` | A field map like any other table, named anything with `role: "nesting"`. Its first two `ref` columns are the contained node, then its container. A node has at most one container. Further columns take a `type`, `domain` and `default` as usual. |
| `links` | `table` | `none` | As in a [network](https://elicitjs.github.io/marks/network.md): `link()` draws it and `edit.network.*` edits it. |
### `constraints.contain(options)`
Pure-data membership rule over a hierarchy’s `nesting` table. It guards every edit and `ds.set`. Rows in the seed or `setData` that break it are kept, and one warning names them. An edit is refused only for a break it adds.
JSON keyword: `constraints.contain`
```ts
constraints.contain({ parent?, child?, maxDepth?, maxChildren?, table? }) → Constraint
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `table` | `string` | `'nesting'` | The nesting table, by role or by name. |
| `parent` | `(d, i, rows) => boolean` | `any node` | Which rows of the nodes table may hold other nodes. |
| `child` | `(d, i, rows) => boolean` | `any node` | Which rows of the nodes table may sit inside a container. |
| `maxDepth` | `number` | `∞` | Maximum nesting depth (top-level nodes are depth 0). |
| `maxChildren` | `number` | `∞` | Maximum direct children per container. |
### `mark.contains`
Shorthand option on any shape mark in a hierarchy. Scopes container eligibility to rows boxed by that mark and configures their `padding` and `fit`. Equivalent to `constraints.contain` plus `layout.hierarchy.contain` for that mark.
JSON keyword: `contains`
```ts
contains: true | ((d, i, rows) => boolean) | { where?, padding?, fit? }
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `where` | `(d, i, rows) => boolean` | `every row the mark boxes` | Predicate picking which of the mark’s rows can hold other nodes. |
| `padding` | `number \| { top, right, bottom, left }` | `10` | Room in px between a container’s edge and its contents. |
| `fit` | `boolean \| 'x' \| 'y'` | `false` | Size the container to enclose its contents on both axes (`true`), width only (`"x"`), height only (`"y"`), or keep its given size (`false`). |
### `edit.hierarchy.nest(options)`
Drop a node into the container under the pointer, or out of one. Put it on the mark you drag, beside a `move`.
JSON keyword: `edit.hierarchy.nest`
```ts
edit.hierarchy.nest({ defaults, when }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `defaults` | `object` | `{}` | Values for any further columns of the nesting row it writes. |
## Declaring the structure
`structure: "hierarchy"` gives the dataset a `nodes` table and a `nesting` table. A `links` table is optional.
```js
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
kind: { type: "categorical", domain: ["group", "note"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600], default: 130 },
h: { type: "quantitative", domain: [0, 400], default: 80 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
}
```
`getData()`, `onChange` and `setData` use one array per table. A table you leave out of `data` starts empty.
### Example: Groups and notes
constraints.contain picks the rows that hold others; layout.hierarchy.contain({ fit: true }) sizes them to their contents.
Try: **Drag** a note into a group or out of one. **Drag** a group to move it with its contents. Watch `nesting` and the group’s `w`/`h` in the data.
```javascript
const chart = Elicit({
width: 520, height: 340,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["group", "note"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600], default: 130 },
h: { type: "quantitative", domain: [0, 400], default: 80 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "g1", label: "Research", kind: "group", x: 25, y: 60, w: 130, h: 80 },
{ id: "g2", label: "Build", kind: "group", x: 75, y: 60, w: 130, h: 80 },
{ id: "n1", label: "Interviews", kind: "note", x: 20, y: 68, w: 88, h: 28 },
{ id: "n2", label: "Survey", kind: "note", x: 28, y: 50, w: 88, h: 28 },
{ id: "n3", label: "Prototype", kind: "note", x: 75, y: 60, w: 88, h: 28 },
{ id: "n4", label: "Drag me in", kind: "note", x: 50, y: 14, w: 88, h: 28 },
],
nesting: [
{ child: "n1", parent: "g1" },
{ child: "n2", parent: "g1" },
{ child: "n3", parent: "g2" },
],
},
constraints: [
// Only groups hold other nodes.
constraints.contain({ parent: (d) => d.kind === "group" }),
],
layout: [
// A group's size follows its contents; a note keeps its own.
layout.hierarchy.contain({ padding: 12, fit: true }),
layout.dodge(),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "group" ? "#EDF7F8" : "#EBD6AD") },
},
}),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
// A group's name sits above its box, which is as tall as its `h` column.
dy: { fn: (d) => (d.kind === "group" ? -d.h / 2 - 8 : 0) },
},
}),
],
});
mount(chart.dom());
```
## The nesting table
The nesting table is declared like any other table: a field map, with a type for every column.
It needs two `ref` columns. The first names the contained node and the second names its container. Both point at the nodes table's `key: true` column, so their values are node identities. The column names are yours.
```js
nesting: {
child: { type: "ref" }, // the contained node
parent: { type: "ref" }, // its container
}
```
One row is one membership. A node with no row is at the top level. A node has at most one container, and cannot contain itself or any node inside it. A row from `data` or `setData` that breaks either rule is dropped with a warning, and so is a row that names a missing node.
Add any other columns you want to record about a membership. They take a `type`, a `domain` and a `default` like columns anywhere else. A row made by a drop takes each column's `default`, or the value you pass in `edit.hierarchy.nest({ defaults })`.
```js
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
coder: { type: "categorical", domain: ["seed", "participant"], default: "participant" },
}
```
Deleting a node removes the nesting rows that name it. Its contents move to the top level.
## Naming the tables
Name the tables for your data and give each a `role`: `"nodes"`, `"nesting"` or `"links"`. A table named after its role needs no `role`, which is the short form used above.
```js
tables: {
topics: { role: "nodes", fields: { … } },
memberships: { role: "nesting", fields: { … } },
}
```
`data`, `getData()` and `setData` are then keyed `topics` and `memberships`. Marks, constraints, layouts and edits find each table by its role.
### Example: Named tables, and a column on the membership
topics and memberships, by role. A dropped quote's row takes coder's default.
Try: **Drag** the loose quote into a theme and read its `memberships` row: `coder` is `participant`, where the seeded rows say `seed`.
```javascript
const chart = Elicit({
width: 520, height: 320,
margins: { top: 20, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
// Named for the data; `role` says which table each one is.
topics: {
role: "nodes",
fields: {
name: { type: "categorical", key: true, open: true },
kind: { type: "categorical", domain: ["theme", "quote"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600], default: 130 },
h: { type: "quantitative", domain: [0, 400], default: 80 },
},
},
memberships: {
role: "nesting",
fields: {
// The first ref is the contained node, the second its container.
quote: { type: "ref" },
theme: { type: "ref" },
// A column of its own: every membership row carries one.
coder: { type: "categorical", domain: ["seed", "participant"], default: "participant" },
},
},
},
},
data: {
topics: [
{ name: "Trust", kind: "theme", x: 25, y: 58, w: 130, h: 80 },
{ name: "Cost", kind: "theme", x: 75, y: 58, w: 130, h: 80 },
{ name: "\u201cIt just works\u201d", kind: "quote", x: 25, y: 58, w: 104, h: 26 },
{ name: "\u201cToo pricey\u201d", kind: "quote", x: 75, y: 58, w: 104, h: 26 },
{ name: "\u201cWho sees my data?\u201d", kind: "quote", x: 50, y: 12, w: 140, h: 26 },
],
memberships: [
{ quote: "\u201cIt just works\u201d", theme: "Trust", coder: "seed" },
{ quote: "\u201cToo pricey\u201d", theme: "Cost", coder: "seed" },
],
},
constraints: [
constraints.contain({ parent: (d) => d.kind === "theme" }),
],
layout: [
layout.hierarchy.contain({ padding: 12, fit: true }),
layout.dodge(),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "theme" ? "#EDF7F8" : "#EBD6AD") },
},
}),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "name" },
dy: { fn: (d) => (d.kind === "theme" ? -d.h / 2 - 8 : 0) },
},
}),
],
});
mount(chart.dom());
```
## Containers
Containment splits cleanly into two pieces: **eligibility** (a pure-data invariant) and **geometry** (a pixel-space layout rule).
- `constraints.contain({ parent, child, maxDepth, maxChildren })` decides which rows may hold others, which may sit inside a container, and how deep or full a container may get. It guards every edit and `ds.set`. Rows in the seed or `setData` that break it are kept, and one warning names them; an edit is refused only for a break it adds.
- `layout.hierarchy.contain({ where, padding, fit })` sets the room between a container's edge and its contents, and whether the container sizes itself to fit them (`fit: true`, `"x"`, `"y"`, or `false`). `where` picks the containers that take this padding and fit. Which rows may take a drop is still `constraints.contain` or a mark's `contains`.
```js
constraints: [
constraints.contain({ parent: (d) => d.kind === "group" }),
],
layout: [
layout.hierarchy.contain({ padding: 12, fit: true }),
],
```
When a chart draws different kinds of node with separate marks, or when one mark owns its own containers, the mark option `contains` is a shorthand for both:
```js
rect({
contains: { where: (d) => d.kind === "group", padding: 12, fit: true },
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
},
})
```
`contains: true` lets every row drawn by that mark hold others, and `contains: (d) => …` picks rows with default padding. `scale: null` reads `w` and `h` as pixels.
A fitted container writes its size back to the mark's size fields (`width`/`height`, `size`, `rx`/`ry`, or `x1`/`x2`/`y1`/`y2`), so a resize edit leaves those fitted columns alone while an empty container stays editable. When a container loses its last child, it returns to each fitted column's schema `default` and keeps its top-left corner. Declare a `default` for every fitted column; without one, the container shrinks to its padding and logs a warning.
```js
w: { type: "quantitative", domain: [0, 600], default: 130 },
```
The fitted size is in the data, so other channels can read it. The examples here place a group's name from its `h` column.
### Example: Groups inside groups
A container is fitted after its contents, at any depth.
Try: **Drag** a person between teams. **Drag** the Web team out of Engineering and into Design. Every group it leaves or joins re-fits.
```javascript
const chart = Elicit({
width: 560, height: 380,
margins: { top: 20, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["group", "person"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600], default: 100 },
h: { type: "quantitative", domain: [0, 400], default: 60 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "org", label: "Company", kind: "group", x: 40, y: 55, w: 100, h: 60 },
{ id: "eng", label: "Engineering", kind: "group", x: 25, y: 55, w: 100, h: 60 },
{ id: "des", label: "Design", kind: "group", x: 60, y: 55, w: 100, h: 60 },
{ id: "web", label: "Web", kind: "group", x: 25, y: 40, w: 100, h: 60 },
{ id: "p1", label: "Ana", kind: "person", x: 18, y: 72, w: 56, h: 26 },
{ id: "p2", label: "Ben", kind: "person", x: 32, y: 72, w: 56, h: 26 },
{ id: "p3", label: "Cy", kind: "person", x: 18, y: 38, w: 56, h: 26 },
{ id: "p4", label: "Dee", kind: "person", x: 32, y: 38, w: 56, h: 26 },
{ id: "p5", label: "Eli", kind: "person", x: 60, y: 60, w: 56, h: 26 },
{ id: "p6", label: "New hire", kind: "person", x: 88, y: 20, w: 70, h: 26 },
],
nesting: [
{ child: "eng", parent: "org" },
{ child: "des", parent: "org" },
{ child: "web", parent: "eng" },
{ child: "p1", parent: "eng" },
{ child: "p2", parent: "eng" },
{ child: "p3", parent: "web" },
{ child: "p4", parent: "web" },
{ child: "p5", parent: "des" },
],
},
layout: [layout.dodge()],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
// Shorthand on the mark: groups hold others and fit round their contents.
contains: { where: (d) => d.kind === "group", padding: 18, fit: true },
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "group" ? "#2B5D87" : "#ffffff") },
fillOpacity: { fn: (d) => (d.kind === "group" ? 0.12 : 1) },
},
}),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
// Inside the top padding, so nested groups' names do not collide.
dy: { fn: (d) => (d.kind === "group" ? -d.h / 2 + 10 : 0) },
dx: { fn: (d) => (d.kind === "group" ? -d.w / 2 + 10 : 0) },
textAnchor: { fn: (d) => (d.kind === "group" ? "start" : "middle") },
},
}),
],
});
mount(chart.dom());
```
### Example: Any node can hold others
contains: { padding: 14, fit: true } — drop one node on another to make a group.
Try: **Drag** Apple onto Fruit. **Click** empty space to add a node and **Alt-click** one to delete it. Deleting a group releases its contents.
```javascript
const chart = Elicit({
width: 480, height: 320,
margins: { top: 20, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600], default: 80 },
h: { type: "quantitative", domain: [0, 400], default: 28 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "a", label: "Fruit", x: 25, y: 70, w: 80, h: 28 },
{ id: "b", label: "Apple", x: 60, y: 75, w: 80, h: 28 },
{ id: "c", label: "Pear", x: 75, y: 45, w: 80, h: 28 },
{ id: "d", label: "Tool", x: 25, y: 25, w: 80, h: 28 },
{ id: "e", label: "Hammer", x: 60, y: 18, w: 80, h: 28 },
],
nesting: [],
},
layout: [layout.dodge()],
marks: [
rect({
cornerRadius: 6,
fill: "#E3F1DF",
stroke: "#5C9A4B",
// Every node may hold others: drop one on another to make a group.
contains: { padding: 14, fit: true },
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
create({ defaults: { label: "New", w: 80, h: 28 } }),
remove({ when: when.alt }),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
},
}),
text({
fontSize: 11,
fill: "#3A6630",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
// A node that has grown past a single line is a group: name it above.
dy: { fn: (d) => (d.h > 30 ? -d.h / 2 - 8 : 0) },
},
}),
],
});
mount(chart.dom());
```
## Padding and spacing
Every container keeps `padding` between its edge and its contents. The default is 10px. Give one number, or a side each; a side you leave out takes the default.
```js
layout: [
layout.hierarchy.contain({ padding: { top: 30, right: 12, bottom: 12, left: 12 }, fit: true }),
layout.dodge({ gap: 10 }),
]
```
A fitted container is sized to leave that room. A container with a size of its own moves its contents inside it.
Add `layout.dodge({ gap, where, in })` to push overlapping siblings apart. `gap` defaults to 8px, `where` picks the rows that take part, and `in` scopes it to `"all"` (default), `"roots"`, `"containers"`, or a container predicate. Round nodes keep the gap edge to edge. A `composite` dodges as a whole, with every part, its label included.
Nodes dodge their siblings: the contents of one container dodge each other, and top-level nodes dodge each other. When two overlap, the node you just dropped stays put and the other moves the shortest distance that clears it. When that leaves no room, the contents pack in reading order from the top-left. A container that grows pushes its neighbours the same way, and they take their contents along. A pushed node stays inside its container's padding, or inside the plot at the top level.
Nodes are pushed apart on release, and when data arrives through `setData`. While you drag, they are drawn where the release will put them. Seeded data is spaced once, at the start.
### Example: Room for a name, and no overlaps
padding by side; layout.dodge({ gap: 10 }) pushes overlapping siblings apart on release.
Try: **Drop** the loose note on top of Interviews: Interviews and Survey make room. **Drag** Research onto Build and let go.
```javascript
const chart = Elicit({
width: 520, height: 340,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["group", "note"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600], default: 130 },
h: { type: "quantitative", domain: [0, 400], default: 80 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "g1", label: "Research", kind: "group", x: 25, y: 60, w: 130, h: 80 },
{ id: "g2", label: "Build", kind: "group", x: 62, y: 60, w: 130, h: 80 },
{ id: "n1", label: "Interviews", kind: "note", x: 25, y: 66, w: 88, h: 28 },
{ id: "n2", label: "Survey", kind: "note", x: 25, y: 52, w: 88, h: 28 },
{ id: "n3", label: "Prototype", kind: "note", x: 62, y: 60, w: 88, h: 28 },
{ id: "n4", label: "Drop me on a note", kind: "note", x: 44, y: 12, w: 120, h: 28 },
],
nesting: [
{ child: "n1", parent: "g1" },
{ child: "n2", parent: "g1" },
{ child: "n3", parent: "g2" },
],
},
constraints: [
// Only groups hold other nodes.
constraints.contain({ parent: (d) => d.kind === "group" }),
],
layout: [
// The top side leaves room for the name.
layout.hierarchy.contain({
padding: { top: 30, right: 12, bottom: 12, left: 12 },
fit: true,
}),
// Overlapping siblings are pushed 10px apart when a drag ends.
layout.dodge({ gap: 10 }),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "group" ? "#EDF7F8" : "#EBD6AD") },
},
}),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
// A group's name sits in its top padding.
dy: { fn: (d) => (d.kind === "group" ? -d.h / 2 + 15 : 0) },
},
}),
],
});
mount(chart.dom());
```
## Arranging contents
Add an arrangement rule to `layout` to place contents in slots or packed clusters. See [Layout](https://elicitjs.github.io/layout.md) for the full vocabulary, including flat tables and networks.
| Rule | Contents | | --- | --- | | `layout.dodge({ gap, where, in })` | Where you drop them, pushed apart when they overlap. | | `layout.row({ gap, in })` | Left to right from the top-left. A row with a fixed width wraps at it. | | `layout.column({ gap, in })` | Top to bottom from the top-left. A column with a fixed height wraps at it. | | `layout.grid({ columns, gap, in })` | Equal cells, the size of the largest node, `columns` to a row. | | `layout.pack({ gap, keep, in })` | Drawn together where you drop them, touching. |
In a hierarchy, `row`, `column`, `grid` and `pack` default to `in: "containers"`. Pass `in: "roots"` to arrange top-level nodes, `in: "all"` for both, or `in: (d) => …` to arrange different container kinds differently — for example `layout.row({ in: "roots" })` beside `layout.column({ in: (d) => d.kind === "lane" })`.
In a row, column or grid, the order of the contents is the answer. Drag a node within its container to reorder it. Drop one into a container and it takes the nearest slot. While you drag, the other nodes open a space where it will land. On release, every node snaps to its slot.
A pack has no order. A node you drop there moves in to touch the others, and the others stay where they are. Nothing in a pack moves until you let go, so the node you aim at holds still. Round nodes pack as circles. Boxes pack as boxes, so they meet edge to edge.
`keep` sets how a dropped node moves in:
| `keep` | The node moves | | --- | --- | | `"distance"` | To the free spot nearest where you let go. The default. | | `"angle"` | Straight towards the node in the middle of the pack, or away from it, until it touches. Its direction from the middle stays the same. |
Use `"angle"` when where a node sits around the middle is the answer.
`gap` is the space between slots, 8px by default. `columns` sets a grid's cells to a row. Without it, a grid fills a fixed width, or makes a square.
```js
layout: [
layout.hierarchy.contain({ padding: { top: 30, right: 10, bottom: 10, left: 10 }, fit: true }),
layout.column({ gap: 6 }),
]
```
The order is read from the `x` and `y` columns, which hold each node's slot. A fitted container keeps its top-left corner and grows right and down. A pack is fitted round its contents.
### Example: A board that grows
layout.column({ gap: 6 }) — each lane stacks its cards and fits round them.
Try: **Drag** Pilot study above Write survey. **Drag** Ethics form into Done, between the cards there. Doing returns to its default size.
```javascript
const chart = Elicit({
width: 560, height: 360,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["lane", "card"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
// An empty lane returns to this size.
w: { type: "quantitative", domain: [0, 600], default: 140 },
h: { type: "quantitative", domain: [0, 600], default: 70 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "todo", label: "To do", kind: "lane", x: 18, y: 80, w: 140, h: 70 },
{ id: "doing", label: "Doing", kind: "lane", x: 50, y: 80, w: 140, h: 70 },
{ id: "done", label: "Done", kind: "lane", x: 82, y: 80, w: 140, h: 70 },
{ id: "a", label: "Write survey", kind: "card", x: 18, y: 80, w: 120, h: 28 },
{ id: "b", label: "Recruit", kind: "card", x: 18, y: 70, w: 120, h: 28 },
{ id: "c", label: "Pilot study", kind: "card", x: 18, y: 60, w: 120, h: 28 },
{ id: "d", label: "Ethics form", kind: "card", x: 50, y: 80, w: 120, h: 28 },
{ id: "e", label: "Literature", kind: "card", x: 82, y: 80, w: 120, h: 28 },
],
nesting: [
{ child: "a", parent: "todo" },
{ child: "b", parent: "todo" },
{ child: "c", parent: "todo" },
{ child: "d", parent: "doing" },
{ child: "e", parent: "done" },
],
},
constraints: [
constraints.contain({ parent: (d) => d.kind === "lane", child: (d) => d.kind === "card" }),
],
layout: [
// A lane grows down as cards join it, leaving room at the top for its name.
layout.hierarchy.contain({
padding: { top: 30, right: 10, bottom: 10, left: 10 },
fit: true,
}),
// Cards stack top to bottom, in order, inside each lane.
layout.column({ gap: 6 }),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "lane" ? "#EDF7F8" : "#FFFFFF") },
},
}),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
dy: { fn: (d) => (d.kind === "lane" ? -d.h / 2 + 15 : 0) },
},
}),
],
});
mount(chart.dom());
```
### Example: Rows inside rows
layout.row({ gap: 6 }) — rows hold tiles and other rows, at any depth.
Try: **Drag** A2 into any row. **Drag** a whole row into another one.
```javascript
const chart = Elicit({
width: 560, height: 300,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
kind: { type: "categorical", domain: ["row", "tile"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
// An empty row returns to this size.
w: { type: "quantitative", domain: [0, 600], default: 60 },
h: { type: "quantitative", domain: [0, 400], default: 50 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "outer", kind: "row", x: 10, y: 75, w: 60, h: 50 },
{ id: "A1", kind: "tile", x: 12, y: 75, w: 40, h: 34 },
{ id: "B1", kind: "tile", x: 20, y: 75, w: 40, h: 34 },
{ id: "inner", kind: "row", x: 30, y: 75, w: 60, h: 50 },
{ id: "A1-1", kind: "tile", x: 32, y: 75, w: 40, h: 34 },
{ id: "deep", kind: "row", x: 40, y: 75, w: 60, h: 50 },
{ id: "B1-1", kind: "tile", x: 42, y: 75, w: 40, h: 34 },
{ id: "B2", kind: "tile", x: 50, y: 75, w: 40, h: 34 },
{ id: "C2", kind: "tile", x: 58, y: 75, w: 40, h: 34 },
{ id: "spare", kind: "row", x: 20, y: 25, w: 60, h: 50 },
{ id: "A2", kind: "tile", x: 50, y: 25, w: 40, h: 34 },
],
nesting: [
{ child: "A1", parent: "outer" },
{ child: "B1", parent: "outer" },
{ child: "inner", parent: "outer" },
{ child: "A1-1", parent: "inner" },
{ child: "deep", parent: "inner" },
{ child: "B1-1", parent: "deep" },
{ child: "B2", parent: "deep" },
{ child: "C2", parent: "deep" },
],
},
constraints: [
constraints.contain({ parent: (d) => d.kind === "row" }),
],
layout: [
// Rows hold tiles and other rows, left to right, and fit round them.
layout.hierarchy.contain({ padding: 8, fit: true }),
layout.row({ gap: 6 }),
layout.dodge({ in: "roots" }),
],
marks: [
rect({
cornerRadius: 5,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "row" ? "#EDF7F8" : "#FFFFFF") },
},
}),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { fn: (d) => (d.kind === "tile" ? d.id : "") },
},
}),
],
});
mount(chart.dom());
```
### Example: A grid
layout.grid({ columns: 3, gap: 8 }) — fixed boards that fill in reading order.
Try: **Drag** items onto Drop. **Drag** an item between two others to reorder.
```javascript
const chart = Elicit({
width: 560, height: 320,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
// The two boards are the question, so they stay where they are.
lock: (d, i, table) => table === "nodes" && d.kind === "board",
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["board", "item"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600] },
h: { type: "quantitative", domain: [0, 400] },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "keep", label: "Keep", kind: "board", x: 27, y: 50, w: 220, h: 250 },
{ id: "drop", label: "Drop", kind: "board", x: 73, y: 50, w: 220, h: 250 },
...["🍎", "🍌", "🍇", "🥕", "🥦", "🧀", "🍞", "🍫"].map((label, k) => ({
id: "i" + k, label, kind: "item", x: 27, y: 50, w: 52, h: 52,
})),
],
nesting: ["i0", "i1", "i2", "i3", "i4", "i5", "i6", "i7"].map((child) => ({ child, parent: "keep" })),
},
constraints: [
constraints.contain({ parent: (d) => d.kind === "board", child: (d) => d.kind === "item" }),
],
layout: [
// No `fit`: a board keeps its size. Items fill three cells to a row under its name.
layout.hierarchy.contain({ padding: { top: 30, right: 14, bottom: 14, left: 14 } }),
layout.grid({ columns: 3, gap: 8 }),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "board" ? "#EDF7F8" : "#FFFFFF") },
},
}),
text({
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
fontSize: { fn: (d) => (d.kind === "board" ? 11 : 24) },
dy: { fn: (d) => (d.kind === "board" ? -d.h / 2 + 15 : 0) },
},
}),
],
});
mount(chart.dom());
```
### Example: Packed circles
layout.pack({ gap: 3 }) — an item lands where you drop it, touching the others.
Try: **Drag** Rain into Unlikely. **Drag** every item out of a set and it returns to its default radius.
```javascript
const chart = Elicit({
width: 560, height: 340,
margins: { top: 24, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["set", "item"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
// An empty set returns to this radius.
r: { type: "quantitative", domain: [0, 300], default: 30 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "likely", label: "Likely", kind: "set", x: 28, y: 50, r: 30 },
{ id: "unlikely", label: "Unlikely", kind: "set", x: 72, y: 50, r: 30 },
{ id: "a", label: "Rain", kind: "item", x: 28, y: 50, r: 22 },
{ id: "b", label: "Wind", kind: "item", x: 28, y: 50, r: 16 },
{ id: "c", label: "Heat", kind: "item", x: 28, y: 50, r: 18 },
{ id: "d", label: "Fog", kind: "item", x: 28, y: 50, r: 14 },
{ id: "e", label: "Snow", kind: "item", x: 72, y: 50, r: 20 },
{ id: "f", label: "Hail", kind: "item", x: 72, y: 50, r: 15 },
],
nesting: [
{ child: "a", parent: "likely" },
{ child: "b", parent: "likely" },
{ child: "c", parent: "likely" },
{ child: "d", parent: "likely" },
{ child: "e", parent: "unlikely" },
{ child: "f", parent: "unlikely" },
],
},
constraints: [
constraints.contain({ parent: (d) => d.kind === "set", child: (d) => d.kind === "item" }),
],
layout: [
// Items gather where they are dropped; the set encloses them.
layout.hierarchy.contain({ padding: 6, fit: true }),
layout.pack({ gap: 3 }),
],
marks: [
point({
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
size: { field: "r", scale: null },
fill: { fn: (d) => (d.kind === "set" ? "#EDF7F8" : "#C3B9DF") },
},
}),
text({
fontSize: 10,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
dy: { fn: (d) => (d.kind === "set" ? -d.r - 8 : 0) },
},
}),
],
});
mount(chart.dom());
```
### Example: Packed boxes
layout.pack({ keep: "angle", gap: 6 }) — a card keeps its direction from Price.
Try: **Drag** Fuel to the far right of the board. It slides in beside Price on that side.
```javascript
const chart = Elicit({
width: 560, height: 340,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
// The board is the question, so it stays where it is.
lock: (d, i, table) => table === "nodes" && d.kind === "board",
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["board", "goal", "item"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600] },
h: { type: "quantitative", domain: [0, 400] },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "board", label: "What drives the price?", kind: "board", x: 50, y: 50, w: 520, h: 300 },
{ id: "price", label: "Price", kind: "goal", x: 50, y: 48, w: 96, h: 40 },
{ id: "a", label: "Demand", kind: "item", x: 18, y: 78, w: 84, h: 32 },
{ id: "b", label: "Supply", kind: "item", x: 84, y: 76, w: 84, h: 32 },
{ id: "c", label: "Fuel", kind: "item", x: 14, y: 22, w: 64, h: 32 },
{ id: "d", label: "Taxes", kind: "item", x: 86, y: 18, w: 72, h: 32 },
{ id: "e", label: "Season", kind: "item", x: 52, y: 10, w: 84, h: 32 },
],
nesting: ["price", "a", "b", "c", "d", "e"].map((child) => ({ child, parent: "board" })),
},
constraints: [
constraints.contain({ parent: (d) => d.kind === "board" }),
],
layout: [
// Each card slides in to touch, keeping its direction from Price.
layout.hierarchy.contain(),
layout.pack({ keep: "angle", gap: 6 }),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "board" ? "#EDF7F8" : d.kind === "goal" ? "#C3B9DF" : "#FFFFFF") },
},
}),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
dy: { fn: (d) => (d.kind === "board" ? -d.h / 2 + 15 : 0) },
},
}),
],
});
mount(chart.dom());
```
## Fixed containers
Leave `fit` off `layout.hierarchy.contain` and a container keeps the size it was given. Use this for regions that are part of the question: buckets, lanes, zones. Lock them with `lock` so only the cards move. Cards stay inside the bucket's padding, and a locked row stays where it is when nodes dodge. Add `layout.dodge()` to keep cards from overlapping, or `layout.column()` / `layout.grid()` to put them in slots.
The answer is the nesting table: one row per card, naming its bucket.
### Example: Sorting cards into buckets
No fit: each bucket keeps its size and its cards inside it; nesting records the sort.
Try: **Drag** each card into a bucket. A card released outside every bucket has no nesting row.
```javascript
const chart = Elicit({
width: 560, height: 340,
margins: { top: 20, right: 16, bottom: 16, left: 16 },
axes: false,
// The buckets are the question, so they stay where they are.
lock: (d, i, table) => table === "nodes" && d.kind === "bucket",
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["bucket", "card"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600] },
h: { type: "quantitative", domain: [0, 400] },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "must", label: "Must have", kind: "bucket", x: 18, y: 58, w: 150, h: 210 },
{ id: "should", label: "Should have", kind: "bucket", x: 50, y: 58, w: 150, h: 210 },
{ id: "wont", label: "Won't have", kind: "bucket", x: 82, y: 58, w: 150, h: 210 },
{ id: "c1", label: "Offline mode", kind: "card", x: 18, y: 6, w: 96, h: 26 },
{ id: "c2", label: "Dark theme", kind: "card", x: 39, y: 6, w: 96, h: 26 },
{ id: "c3", label: "Export PDF", kind: "card", x: 60, y: 6, w: 96, h: 26 },
{ id: "c4", label: "Comments", kind: "card", x: 81, y: 6, w: 96, h: 26 },
{ id: "c5", label: "Search", kind: "card", x: 18, y: 70, w: 96, h: 26 },
],
nesting: [{ child: "c5", parent: "must" }],
},
constraints: [
constraints.contain({ parent: (d) => d.kind === "bucket", child: (d) => d.kind === "card" }),
],
layout: [
// No `fit`: a bucket keeps the size it was given, and cards stay below its name.
layout.hierarchy.contain({ padding: { top: 26 } }),
layout.dodge(),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "bucket" ? "#EDF7F8" : "#B7DEE1") },
},
}),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
dy: { fn: (d) => (d.kind === "bucket" ? -d.h / 2 + 12 : 0) },
},
}),
],
});
mount(chart.dom());
```
## Other shapes
`point`, `ellipse`, `shape` and a `composite` hold other nodes the same way. A round mark fits the circle that encloses its contents. A `point` writes its fitted radius to `size`, and an `ellipse` writes to `rx` and `ry`.
### Example: Circles
contains: { where, padding: 8, fit: true } — a set's radius encloses its items.
Try: **Drag** Penguin into Birds. **Drag** an item towards a set’s edge and the set grows on release.
```javascript
const chart = Elicit({
width: 480, height: 340,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["set", "item"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
r: { type: "quantitative", domain: [0, 300], default: 40 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "s1", label: "Mammals", kind: "set", x: 30, y: 55, r: 40 },
{ id: "s2", label: "Birds", kind: "set", x: 72, y: 55, r: 40 },
{ id: "i1", label: "Otter", kind: "item", x: 24, y: 62, r: 16 },
{ id: "i2", label: "Bat", kind: "item", x: 36, y: 48, r: 16 },
{ id: "i3", label: "Owl", kind: "item", x: 72, y: 55, r: 16 },
{ id: "i4", label: "Penguin", kind: "item", x: 50, y: 12, r: 16 },
],
nesting: [
{ child: "i1", parent: "s1" },
{ child: "i2", parent: "s1" },
{ child: "i3", parent: "s2" },
],
},
layout: [layout.dodge()],
marks: [
point({
stroke: "#46596B",
// A set's radius encloses its items.
contains: { where: (d) => d.kind === "set", padding: 8, fit: true },
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
size: { field: "r", scale: null },
fill: { fn: (d) => (d.kind === "set" ? "#EDF7F8" : "#C3B9DF") },
},
}),
text({
fontSize: 10,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
dy: { fn: (d) => (d.kind === "set" ? -d.r - 8 : 0) },
},
}),
],
});
mount(chart.dom());
```
## Dragging in and out
Put `edit.hierarchy.nest()` on the mark you drag, beside `move({ mode: "relative" })`. The move carries the node. On release, the node joins the innermost container under the pointer. Released over no container, it leaves the one it was in.
While you drag, the chart shows what a release would do. The container the node would join is outlined and grows to hold it. The container it came from keeps its size while the pointer is inside it, and shrinks once the pointer leaves. Other nodes move out of the way when `layout.dodge()` or a slot layout is active. The data changes on release. Style the outline with the `target` state of `effects`.
A container stays where it is when you drag a node past it or out of it. Released against a container's edge, the node you dropped moves clear of it when `layout.dodge()` is active.
The layout eases to its new place. Nodes make room first and a container resizes after them. The node you drag stays on the pointer. Set the time with `motion: { duration }` on the spec, in milliseconds, or `motion: false` to draw each change at once. Motion is off when the reader's system asks for reduced motion.
The same `move` moves a container, and its contents travel with it.
Rules about which nodes may go where, maximum depth, or how many children a container may hold belong in `constraints.contain(...)` (or `constraints.custom` on `table: "nesting"`). A drop a rule refuses shows no outline and leaves the data unchanged.
### Example: A limit on each container
constraints.contain({ parent, child, maxChildren: 3 }) — three tasks per phase.
Try: **Drag** Review into Phase 1: it is full, so nothing lights up. **Drag** it into Phase 2 instead.
```javascript
const chart = Elicit({
width: 520, height: 340,
margins: { top: 20, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["phase", "task"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600], default: 130 },
h: { type: "quantitative", domain: [0, 400], default: 80 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "p1", label: "Phase 1 (max 3)", kind: "phase", x: 25, y: 58, w: 130, h: 80 },
{ id: "p2", label: "Phase 2 (max 3)", kind: "phase", x: 75, y: 58, w: 130, h: 80 },
{ id: "t1", label: "Scope", kind: "task", x: 18, y: 68, w: 70, h: 26 },
{ id: "t2", label: "Budget", kind: "task", x: 32, y: 56, w: 70, h: 26 },
{ id: "t3", label: "Hire", kind: "task", x: 20, y: 44, w: 70, h: 26 },
{ id: "t4", label: "Launch", kind: "task", x: 75, y: 58, w: 70, h: 26 },
{ id: "t5", label: "Review", kind: "task", x: 50, y: 12, w: 70, h: 26 },
],
nesting: [
{ child: "t1", parent: "p1" },
{ child: "t2", parent: "p1" },
{ child: "t3", parent: "p1" },
{ child: "t4", parent: "p2" },
],
},
constraints: [
// Only phases hold tasks, and each phase holds at most three.
constraints.contain({
parent: (d) => d.kind === "phase",
child: (d) => d.kind === "task",
maxChildren: 3,
}),
],
layout: [
layout.hierarchy.contain({ padding: 12, fit: true }),
layout.dodge(),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "phase" ? "#F9EEEC" : "#F6D5CB") },
},
}),
text({
fontSize: 11,
fill: "#9A3E27",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
dy: { fn: (d) => (d.kind === "phase" ? -d.h / 2 - 8 : 0) },
},
}),
],
});
mount(chart.dom());
```
## Nested and linked
Add a `links` table and the nodes can be connected as in a [network](https://elicitjs.github.io/marks/network.md). `link()` draws the links and meets a container at its edge. A `ports` channel and `edit.network.connect()` work on the same mark.
### Example: Systems and their parts
A hierarchy with a links table: parts link across group borders.
Try: **Hover** a box and **drag** from a dot to another box to link them. **Drag** Cache into Backend. **Alt-click** a link to delete it.
```javascript
const chart = Elicit({
width: 560, height: 360,
margins: { top: 20, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["system", "part"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600], default: 120 },
h: { type: "quantitative", domain: [0, 400], default: 80 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
links: {
directed: true,
fields: {
source: { type: "ref" },
target: { type: "ref" },
},
},
},
},
data: {
nodes: [
{ id: "front", label: "Frontend", kind: "system", x: 22, y: 55, w: 120, h: 80 },
{ id: "back", label: "Backend", kind: "system", x: 72, y: 55, w: 120, h: 80 },
{ id: "ui", label: "UI", kind: "part", x: 22, y: 68, w: 70, h: 26 },
{ id: "state", label: "State", kind: "part", x: 22, y: 42, w: 70, h: 26 },
{ id: "api", label: "API", kind: "part", x: 64, y: 68, w: 70, h: 26 },
{ id: "db", label: "Database", kind: "part", x: 82, y: 42, w: 70, h: 26 },
{ id: "cache", label: "Cache", kind: "part", x: 48, y: 12, w: 70, h: 26 },
],
nesting: [
{ child: "ui", parent: "front" },
{ child: "state", parent: "front" },
{ child: "api", parent: "back" },
{ child: "db", parent: "back" },
],
links: [
{ source: "ui", target: "state" },
{ source: "state", target: "api" },
{ source: "api", target: "db" },
{ source: "front", target: "back" },
],
},
constraints: [
constraints.contain({ parent: (d) => d.kind === "system" }),
],
layout: [
layout.hierarchy.contain({ padding: 16, fit: true }),
layout.dodge(),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "system" ? "#EDF7F8" : "#B2CEE6") },
// A dot on each edge while you hover: drag from one to another node.
ports: { value: true, edit: edit.network.connect() },
},
}),
link({ stroke: "#20555A", strokeWidth: 1.5, edits: [remove({ when: when.alt })] }),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
dy: { fn: (d) => (d.kind === "system" ? -d.h / 2 - 8 : 0) },
},
}),
],
});
mount(chart.dom());
```
## Reading and setting from outside
Containment is stored as rows, so your code reads and writes it like any other data. `getData()` returns the nesting rows and each container's fitted size.
`setData` takes the same shape. Change the nesting rows and every container re-fits. A node sent with no `x` and `y` is placed inside the container it joins, clear of the nodes already there. In an arranged container it takes the last slot.
```js
const data = chart.getData();
chart.setData({ ...data, nesting: [...data.nesting, { child: "n4", parent: "g2" }] });
```
### Example: Set from outside
Each button calls setData with new nesting rows; no sizes are sent.
Try: **Click** the buttons, then **drag** a note. Both write the same tables.
```javascript
const el = Elicit({
width: 520, height: 320,
margins: { top: 20, right: 16, bottom: 16, left: 16 },
axes: false,
schema: {
structure: "hierarchy",
tables: {
nodes: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["group", "note"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
w: { type: "quantitative", domain: [0, 600], default: 130 },
h: { type: "quantitative", domain: [0, 400], default: 80 },
},
nesting: {
child: { type: "ref" },
parent: { type: "ref" },
},
},
},
data: {
nodes: [
{ id: "g1", label: "Group A", kind: "group", x: 25, y: 55, w: 130, h: 80 },
{ id: "g2", label: "Group B", kind: "group", x: 75, y: 55, w: 130, h: 80 },
{ id: "n1", label: "One", kind: "note", x: 20, y: 62, w: 70, h: 26 },
{ id: "n2", label: "Two", kind: "note", x: 30, y: 46, w: 70, h: 26 },
],
nesting: [
{ child: "n1", parent: "g1" },
{ child: "n2", parent: "g1" },
],
},
constraints: [
constraints.contain({ parent: (d) => d.kind === "group" }),
],
layout: [
layout.hierarchy.contain({ padding: 12, fit: true }),
layout.dodge(),
],
marks: [
rect({
cornerRadius: 6,
stroke: "#46596B",
edits: [
move({ channels: ["x", "y"], mode: "relative" }),
edit.hierarchy.nest(),
],
channels: {
x: { field: "x" },
y: { field: "y" },
width: { field: "w", scale: null },
height: { field: "h", scale: null },
fill: { fn: (d) => (d.kind === "group" ? "#EDF7F8" : "#C2DEBA") },
},
}),
text({
fontSize: 11,
fill: "#20555A",
channels: {
x: { field: "x" },
y: { field: "y" },
text: { field: "label" },
dy: { fn: (d) => (d.kind === "group" ? -d.h / 2 - 8 : 0) },
},
}),
],
});
mount(el.dom());
// What a program (or a model) does: read the tables, write them back.
const button = (label, run) => {
const b = document.createElement("button");
b.textContent = label;
b.style.cssText = "margin: 0 6px 8px 0; padding: 4px 10px; font: 12px system-ui; cursor: pointer;";
b.onclick = run;
return b;
};
const toolbar = document.createElement("div");
let minted = 0;
toolbar.append(
// Re-parent by rewriting the nesting rows. No sizes or positions are sent.
button("Move everything to Group B", () => {
const data = el.getData();
el.setData({
...data,
nesting: data.nodes.filter((d) => d.kind === "note").map((d) => ({ child: d.id, parent: "g2" })),
});
}),
// A new node with no x/y: it is placed inside the group it joins.
button("Add a note to Group A", () => {
const data = el.getData();
const id = "new" + ++minted;
el.setData({
nodes: [...data.nodes, { id, label: "Added " + minted, kind: "note", x: null, y: null, w: 70, h: 26 }],
nesting: [...data.nesting, { child: id, parent: "g1" }],
});
}),
button("Ungroup all", () => el.setData({ ...el.getData(), nesting: [] })),
);
if (el.dom().parentNode) el.dom().parentNode.insertBefore(toolbar, el.dom());
```
---
# Axis, Grid & Rule
> Source: https://elicitjs.github.io/marks/axes/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
Axes and gridlines are **chart elements**: they draw a scale, not data. Configure them with the spec's `axes: {…}` option, or compose `elements.axisX` / `elements.gridY` yourself. `ruleY` is a data mark.
## API reference
### `axes (on Elicit)`
The implicit layer. Every key desugars into the `axis` and `grid` marks below, and an explicit one you compose yourself always wins over the injected one.
JSON keyword: `axis`
```ts
axes: false // no axes at all
axes: { x, y, count, origin } // per-channel config
axes: { y: { grid: true, ticks: 8 } } // any axis option
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `x / y` | `object \| false` | `{}` | Options for that channel’s axis — any option in the table below. `false` suppresses the channel. |
| `count` | `boolean \| object` | `false` | Draw the `count` axis of a counting mark ([waffle](https://elicitjs.github.io/marks/waffle.md), [dotStack](https://elicitjs.github.io/marks/dotstack.md)). It sits on whichever side that mark stacks along. Pass an object for the usual axis options. |
| `origin` | `boolean` | `auto` | Cross both axes at zero, instead of the left/bottom frame. Inferred `true` when a [trend](https://elicitjs.github.io/marks/trend.md) is present and you wrote no `axes` at all; state it either way to override. |
Returns / emits: The injected `axis` / `grid` marks, in the background layer.
### `axis · axisX · axisY`
A spine, ticks, labels and an optional title for one channel’s scale. Import `elements` from `elicitjs`, or reach it through the `axes` option above.
JSON keyword: `elements.axis`, `elements.axisX`, `elements.axisY`
```ts
axisX({ ticks, tickFormat, title, anchor, transform, grid, … }) → ChartElement
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channel` | `'x' \| 'y'` | `'x'` | Which scale to draw (pinned by axisX/axisY). |
| `anchor` | `'bottom'\|'top'\|'left'\|'right'` | `per axis` | Which side the axis sits on. |
| `transform` | `(ctx) => {x?,y?}` | | Override the base translate — cross at the origin, or a centred 1D axis. |
| `ticks` | `number` | `5` | Approximate tick count (linear scales). |
| `tickValues` | `any[]` | | Explicit tick values (overrides `ticks`). |
| `tickFormat` | `string \| fn` | `auto` | A d3-format string or a formatter function. A newline in a label breaks it onto a second line. |
| `tickSize` | `number \| (v, i) => number` | `theme (6)` | Tick mark length in pixels; 0 draws none. A function sets each tick's length. |
| `tickPadding` | `number` | `theme (3)` | Gap between a tick's end and its label, in pixels. |
| `labelAngle` | `number` | `theme (0)` | Tick-label rotation in degrees, counter-clockwise like a mark's angle. The axis reserves the room the turned labels need. |
| `title` | `string` | | Axis title, centred along the axis and pushed past the tick labels. A y title is rotated to run along its axis. |
| `titleAngle` | `number` | `90 left · -90 right` | Rotation of the title in degrees. 0 lays a y title flat. On an x axis the title is flat unless set. |
| `stroke / strokeWidth / line` | `style` | `theme (#6b7280 / 1 / true)` | Spine and tick colour and width; `line: false` drops the spine. `stroke` also takes `(v, i) => colour` per tick. |
| `fill / fontSize / fontFamily / fontWeight` | `style` | `theme (#374151 / 10)` | Label paint (labels are text nodes, so they take a `fill`). `fill` and `fontWeight` also take a per-tick function. |
| `titleFill / titleFontSize / titleFontWeight / titlePadding` | `style` | `theme (label fill / fontSize + 1 / — / 0)` | The title's paint, and extra pixels between the labels and the title. |
| `labelAlign / labelOffset` | `'start' \| 'middle' \| 'end' / number` | `theme (side's own / 0)` | A tick label's text-anchor, and pixels every label moves along the axis. With a negative tickPadding, labelAlign: 'start' on a left axis puts the labels inside the plot. |
| `titleAnchor` | `'start' \| 'middle' \| 'end'` | `theme ('middle')` | Where the title sits along the axis; 'end' is the right of x, the top of y. A flat y title at an end sits past it, over the plot: leave room in that margin. |
| `offset` | `number` | `0` | Move the axis this many pixels away from the plot. |
| `grid` | `boolean \| grid options` | `false` | In the global axes config, also add a matching grid. An object styles it (strokeDash, zero, …). |
| `edit / edits` | `Edit / Edit[]` | | An axis is inert until you give it one. `edit.axis.scale()` drags the domain; see [Editing the scale](https://elicitjs.github.io/editing/axis.md). |
| `field` | `string` | `the scale's first field` | Which column an edit on this axis writes, when the scale carries several. |
| `table` | `string` | `the primary table` | Which table that edit writes to, by name. |
| `handleColor / handleSize` | `string / number` | `theme / 5` | The grip an axis edit draws. Inert axes draw none. |
| `id` | `string` | | Stable identity, as on every mark. |
Returns / emits: A chart **element** emitting `line` + `text` nodes; redraws as the domain grows.
### `grid · gridX · gridY`
Full-span gridlines across the plot, one per tick.
JSON keyword: `elements.grid`, `elements.gridX`, `elements.gridY`
```ts
gridY({ ticks, tickValues, stroke, strokeWidth }) → ChartElement
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channel` | `'x' \| 'y'` | `'x'` | Which scale to draw lines for (pinned by gridX/gridY). |
| `ticks` | `number` | `5` | Approximate line count. |
| `tickValues` | `any[]` | | Explicit positions (overrides `ticks`). |
| `stroke / strokeWidth / strokeDash / opacity` | `style` | `theme (#e5e7eb / 1)` | Line paint. stroke, strokeWidth and strokeDash also take (v, i) => value per line. |
| `zero` | `boolean \| { stroke, strokeWidth, strokeDash }` | `theme (none)` | An emphasised line at 0 on a continuous scale. true takes the theme's grid.zero style. |
| `bandPosition` | `number` | `theme (0.5)` | On a band axis, where in each band a line sits: 0 its start edge, so the lines run between the categories. |
| `id` | `string` | | Stable identity, as on every mark. |
Returns / emits: A chart **element** emitting one full-span `line` per tick.
### `rule · ruleX · ruleY`
A straight reference line at a value on one axis — or, with a pair of endpoint channels, a **span** segment (a lollipop stem / error-bar whisker) at a category. An ordinary editable mark: put an `edit` on an endpoint channel and its cap becomes a handle. A rule with no edit is left `pointerEvents:"none"` by the engine, so an inert whisker never swallows a sibling handle’s drag.
JSON keyword: `plot.rule`, `plot.ruleX`, `plot.ruleY`
```ts
ruleY({ channels: { y: { datum: 50 } } }) → Mark // reference line at y = 50
ruleX({ channels: { x, y1, y2 } }) → Mark // span per datum
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `object` | `{}` | The value channel — `{ datum }` for a constant, `{ field }` for one rule per row. `y1/y2` or `x1/x2` switch to span mode. |
| `orientation` | `'vertical' \| 'horizontal'` | `auto` | Which axis carries the reference value (`'vertical'` = y). Inferred from the bound channel; `ruleY / ruleX` pin it. |
| `edits` | `Edit[]` | | As on any mark. A per-channel `edit` makes that endpoint draggable. |
| `discreteScale` | `'band' \| 'point'` | | Which variant of a categorical axis the rule sits on. Left unset so a composite can stamp its own. |
| `strokeDash` | `string` | | Dash pattern passthrough. |
| `stroke, strokeWidth, opacity` | `style` | `stroke:'black'` | Standard style surface. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `x / y` | `datum \| field` | The reference value axis. `{ datum: 50 }` is DATA space — it goes through the scale. (`{ value: 50 }` would be 50 pixels.) |
| `y1 / y2` | `linear` | Span endpoints (vertical). A lone endpoint spans from the value-axis baseline. |
| `x1 / x2` | `linear` | Span endpoints (horizontal). |
Returns / emits: A **mark** emitting one non-interactive `line` per rule (full-extent, or a span segment).
## Chart elements are not data marks
`axis`, `grid`, `legend` and `axisRadial` are members of `elements`. Pass them in `elements: […]` on the spec, or in `marks`. See [Mark & element contracts](https://elicitjs.github.io/concepts/contracts.md).
A data mark views the dataset's columns through a `channels` map. A chart element views **one scale**, named by a singular `channel` (`'x'`, `'fill'`, `'theta'`). It has no fields of its own. `axisRadial` is the exception: it can take `x`/`y` channels to place one ring per row.
An element's `stroke`, `fill` and `fontSize` paint its spine and labels, so they are plain options, not channels.
An edit on a data mark writes a **row**. An edit on a chart element writes the **domain** (`edit.axis.*`), so `create` doesn't apply to an element. The edit takes its field from the scale, which is how a legend picker knows what to write.
A legend reserves space on its side, and so do an axis title and turned or multi-line tick labels. The plot shrinks to fit.
Both halves have an implicit layer on the spec: `axes` for the positional scales, [`legends`](https://elicitjs.github.io/marks/legend.md#legends-key) for the rest.
## elements and ElicitSpec.elements
Compose axes with `elements.axisX`, `elements.axisY` and `elements.gridY`. Pass them in `elements: […]` on the spec, or in `marks`. A composed axis replaces that channel's implicit axis. A composed grid replaces only the implicit grid, so the axis still draws unless `axes` turns it off.
### Example: elements: […] with barY
axes: false, then explicit elements.axisX / axisY / gridY. The bar is the only data mark.
Try: **Drag** a bar — the elements stay scale chrome.
```javascript
// Chart elements via elicit.elements + ElicitSpec.elements (also still work in marks).
const chart = Elicit({
width: 420, height: 220,
margins: { top: 16, right: 16, bottom: 42, left: 52 },
schema: {
cat: { type: 'categorical', domain: ['A', 'B', 'C'] },
n: { type: 'quantitative', domain: [0, 100] },
},
data: [
{ cat: 'A', n: 40 },
{ cat: 'B', n: 70 },
{ cat: 'C', n: 55 },
],
axes: false,
elements: [
elements.axisX({ ticks: 3, title: 'category' }),
elements.axisY({ ticks: 4, title: 'n' }),
elements.gridY(),
],
marks: [
barY({
channels: {
x: { field: 'cat' },
y: { field: 'n', edit: move() },
},
}),
],
});
mount(chart.dom());
```
## The global axes:{} convenience
Pass a per-channel config to shape ticks, formats and titles, or a transform to reposition an axis. `axes: false` drops them entirely.
### Example: Gridlines, ticks, format & title
y gets a grid and percent formatting; x a tick count and a title.
```javascript
const chart = Elicit({
width: 380, height: 300,
margins: { top: 16, right: 16, bottom: 42, left: 62 },
axes: {
x: { ticks: 4, title: "Funnel step" },
y: { grid: true, tickFormat: ".0%", title: "Conversion" },
},
data: [
{ step: "Visit", rate: 1.0 }, { step: "Signup", rate: 0.62 },
{ step: "Active", rate: 0.41 }, { step: "Paid", rate: 0.18 },
],
schema: {
step: { type: "categorical", domain: ["Visit", "Signup", "Active", "Paid"] },
rate: { type: "quantitative", domain: [0, 1] },
},
marks: [
bar({
channels: {
x: { field: "step" },
y: { field: "rate" },
},
}),
],
});
mount(chart.dom());
```
`origin: true` crosses both axes at zero, in place of a `transform` on each channel. A chart with a [`trend`](https://elicitjs.github.io/marks/trend.md) mark gets this frame by default when `axes` is unset. `origin: false` forces the ordinary left/bottom frame. Use a per-channel `transform` to cross at a value other than zero, or on one axis only.
### Example: Origin-crossing axes
axes: { origin: true } crosses both scales at zero, without a hand-written transform.
```javascript
const chart = Elicit({
width: 360, height: 300,
margins: { top: 16, right: 16, bottom: 24, left: 28 },
axes: {
origin: true,
x: { ticks: 5 },
y: { ticks: 5 },
},
data: [
{ x: -8, y: 6 }, { x: 5, y: -3 }, { x: -4, y: -7 },
{ x: 9, y: 4 }, { x: 2, y: 8 }, { x: -6, y: 2 },
],
schema: {
x: { type: "quantitative", domain: [-10, 10] },
y: { type: "quantitative", domain: [-10, 10] },
},
marks: [
point({
size: 5, fill: "#50AEB7",
channels: {
x: { field: "x" },
y: { field: "y" },
},
}),
],
});
mount(chart.dom());
```
### Example: 1D centred slider axis
One point channel; the axis is pinned to the vertical center via transform, and y is dropped.
Try: **Drag** a dot along the axis.
```javascript
const chart = Elicit({
width: 360, height: 200,
margins: { top: 16, right: 20, bottom: 24, left: 20 },
axes: {
x: { transform: ({ height }) => ({ y: height / 2 }), ticks: 5, title: "Belief (0-100)" },
y: false, // drop the default y axis
},
data: [{ v: 20 }, { v: 55 }, { v: 80 }],
schema: {
v: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
size: 8, fill: "#1B3F60",
channels: {
x: { field: "v" },
},
edits: [ move({ channels: ["x"] }) ],
}),
],
});
mount(chart.dom());
```
## Axis titles and band order
`title` labels an axis. An x title sits centred below the tick labels. A y title runs along the axis, reading bottom to top on the left, and sits past the widest tick label, so it never crosses one. The plot shrinks to make room for it.
A band or point y axis lists `domain[0]` at the bottom, the same direction a value increases. Set `scale: { reverse: true }` on the channel to list the categories top-down, as Vega-Lite and Observable Plot do for a horizontal bar chart.
### Example: Titles along the axis
axes: { x: { title }, y: { title } }; scale: { reverse: true } on the band y lists Sleep first.
Try: **Drag** a bar to change its hours.
```javascript
const chart = Elicit({
width: 400, height: 240,
margins: { top: 12, right: 16, bottom: 40, left: 96 },
axes: {
x: { title: "Hours per week" },
// The y title runs along the axis, past the widest label.
y: { title: "Activity" },
},
data: [
{ activity: "Sleep", h: 52 }, { activity: "Work", h: 40 },
{ activity: "Screens", h: 24 }, { activity: "Exercise", h: 4 },
],
schema: {
activity: { type: "categorical", domain: ["Sleep", "Work", "Screens", "Exercise"] },
h: { type: "quantitative", domain: [0, 60] },
},
marks: [
barX({
fill: "#1B3F60",
channels: {
// A band y axis puts domain[0] at the bottom; reverse lists it top-down.
y: { field: "activity", scale: { reverse: true } },
x: { field: "h", edit: move() },
},
}),
],
});
mount(chart.dom());
```
`titleAngle` sets the title's rotation in degrees. `titleAngle: 0` lays a y title flat, for a short unit label.
### Example: A flat y title
axes: { y: { title: "°C", titleAngle: 0 } }
```javascript
const chart = Elicit({
width: 400, height: 220,
margins: { top: 14, right: 16, bottom: 28, left: 58 },
axes: { y: { title: "°C", titleAngle: 0 } },
data: [
{ m: 1, t: 4 }, { m: 2, t: 6 }, { m: 3, t: 10 }, { m: 4, t: 14 },
{ m: 5, t: 18 }, { m: 6, t: 22 },
],
schema: {
m: { type: "quantitative", domain: [1, 6] },
t: { type: "quantitative", domain: [0, 30] },
},
marks: [
lineY({
stroke: "#EE7B5E", strokeWidth: 2,
channels: { x: { field: "m" }, y: { field: "t", edit: move() } },
}),
],
});
mount(chart.dom());
```
## Styling an axis
Every axis option below defaults to the [theme's](https://elicitjs.github.io/theming.md#chrome) `axis` token of the same name, so set it once in a theme or here on one axis. `line: false` drops the spine and `tickSize: 0` the ticks. `tickPadding` sets the gap from tick to label, and `offset` moves the whole axis away from the plot. `labelAngle` turns the tick labels, and the axis reserves the room they need. A `\n` in a formatted label starts a second line.
### Example: Turned labels
axes: { x: { labelAngle: 40, tickSize: 0 }, y: { grid: { strokeDash: "2 3" } } }
Try: drag a bar.
```javascript
// Turned labels and two-line labels. `labelAngle` turns the tick labels (the
// axis makes room for them); a `\n` in a formatted label starts a second line.
const chart = Elicit({
width: 460, height: 280,
margins: { top: 16, right: 16, bottom: 20, left: 40 },
axes: {
x: { labelAngle: 40, tickSize: 0 },
y: { grid: { strokeDash: "2 3" } },
},
data: [
{ brand: "Northwind Traders", v: 42 }, { brand: "Contoso", v: 30 },
{ brand: "Fabrikam Fiber", v: 25 }, { brand: "Adventure Works", v: 18 },
{ brand: "Tailspin Toys", v: 12 },
],
schema: {
brand: { type: "categorical", domain: ["Northwind Traders", "Contoso", "Fabrikam Fiber", "Adventure Works", "Tailspin Toys"] },
v: { type: "quantitative", domain: [0, 50] },
},
marks: [barY({ channels: { x: { field: "brand" }, y: { field: "v", edit: move() } } })],
});
mount(chart.dom());
```
`tickSize`, `stroke`, `fill` and `fontWeight` also take a function of the tick's value and index, and so do a grid's `stroke`, `strokeWidth` and `strokeDash`. Use it to mark a period boundary.
### Example: Per-tick styling
Long ticks, bold two-line labels and solid gridlines on each January.
Try: drag a point on the line.
```javascript
// Per-tick styling: a long tick, a bold two-line label and a solid gridline on
// each January; short ticks and dashed lines elsewhere.
const months = d3.timeMonths(new Date(2006, 0, 1), new Date(2008, 0, 2));
const isJan = (d) => d.getMonth() === 0;
const chart = Elicit({
width: 520, height: 260,
margins: { top: 16, right: 20, bottom: 20, left: 40 },
axes: {
x: {
tickValues: months,
tickFormat: (d) => (isJan(d) ? d3.timeFormat("%b\n%Y")(d) : d3.timeFormat("%b")(d)[0]),
tickSize: (d) => (isJan(d) ? 14 : 4),
fontWeight: (d) => (isJan(d) ? "bold" : null),
line: false,
// The paired grid borrows the axis's tickValues; its dash is per line too.
grid: { strokeDash: (d) => (isJan(d) ? null : "2 3") },
},
},
data: months.map((date, i) => ({ date, price: 420 + 140 * Math.sin(i / 4) + i * 8 })),
schema: {
date: { type: "temporal", domain: [months[0], months[months.length - 1]] },
price: { type: "quantitative", domain: [200, 800] },
},
marks: [lineY({ channels: { x: { field: "date" }, y: { field: "price", edit: move() } }, handles: true })],
});
mount(chart.dom());
```
`labelAlign` sets a label's text-anchor and `labelOffset` moves every label along the axis. A negative `tickPadding` with `labelAlign: "start"` puts a y axis's labels inside the plot, and a grid's `bandPosition: 0` draws its lines between the categories. `titleAnchor` places the title along the axis; `"end"` with `titleAngle: 0` sets a y title at the top left, over the plot, so leave room in `margins.top`.
### Example: A space-saving axis
Labels above each bar, gridlines between the bands, the title at the top left.
Try: drag a bar.
```javascript
// A space-saving y axis: no spine or ticks, labels moved inside the plot above
// each bar, gridlines between the bands, and a flat title at the top left.
const chart = Elicit({
width: 420, height: 230,
margins: { top: 22, right: 12, bottom: 34, left: 6 },
data: [{ team: "Design", n: 12 }, { team: "Engineering", n: 31 }, { team: "Research", n: 8 }],
schema: {
team: { type: "categorical", domain: ["Research", "Engineering", "Design"] },
n: { type: "quantitative", domain: [0, 40] },
},
axes: {
x: { title: "Headcount" },
y: {
line: false, tickSize: 0,
tickPadding: -5, labelAlign: "start", labelOffset: -18,
title: "Team", titleAngle: 0, titleAnchor: "end",
grid: { bandPosition: 0 },
},
},
marks: [
rectX({ cornerRadius: 2, channels: {
y: { field: "team", scale: { padding: 0 } },
x: { field: "n", edit: move() },
height: { value: 22 },
} }),
],
});
mount(chart.dom());
```
## Axis, grid & rule as marks
Turn the global axes off (`axes: false`) and compose axes, grids and rules in `marks` yourself. They draw in the order you list them, interleaved with your data marks.
### Example: Explicit gridY + axisX/axisY + ruleY
A gridline layer under the dots, a dashed rule at y = 50, and two titled axes — all as marks.
```javascript
const chart = Elicit({
width: 380, height: 280,
margins: { top: 16, right: 16, bottom: 42, left: 50 },
axes: false, // no auto axes; we place our own
data: [{ x: 15, y: 30 }, { x: 40, y: 62 }, { x: 65, y: 44 }, { x: 88, y: 74 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
gridY({ ticks: 5 }),
// `datum` is a DATA-space constant: it goes through the y scale, so the
// line lands where y = 50 is. (`value` would mean 50 pixels.)
ruleY({ channels: { y: { datum: 50 } }, stroke: "#EE7B5E", strokeDash: "4 3" }),
point({
fill: "#50AEB7",
size: 8,
channels: {
x: { field: "x" },
y: { field: "y" },
},
}),
axisX({ title: "x", ticks: 5 }),
axisY({ title: "y", ticks: 5 }),
],
});
mount(chart.dom());
```
---
# Radial axis
> Source: https://elicitjs.github.io/marks/axis-radial/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`axisRadial()` draws the `theta` scale as a **radial axis**: an arc spine, ticks, labels, and optional coloured bands for categories. The arc spans the `theta` scale's `range`, by default `[180, 0]`: left to right through the top. `channel: 'radius'` draws the radius scale as concentric rings instead. The axis is inert; pair it with a `needle` to take an answer.
## API reference
### `axisRadial(options)`
Import `elements` from `elicitjs`. A curved axis for a polar scale: an arc spine with ticks and labels, and optional coloured bands behind it. It takes no edits: `edit`, `edits`, `field` and `table` warn.
JSON keyword: `elements.axisRadial`
```ts
axisRadial({ channel, outerRadius, bands, ticks, tickPadding, fill, … }) → ChartElement
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channel` | `'theta' \| 'radius'` | `'theta'` | Which scale to read. `'radius'` draws concentric rings at the radius scale’s ticks, the key for an arc with a `radius` channel. |
| `outerRadius` | `number` | `42% of min(w,h)` | Arc radius in px. The arc spans the `theta` scale’s `range`. Ignored with `channel: 'radius'`, whose rings sit at the scale’s own extent. |
| `bands` | `boolean` | `false` | Fill annular sectors for discrete domains (categorical gauge chrome). |
| `bandWidth` | `number` | `18` | Radial thickness of coloured bands when `innerRadius` is 0. |
| `innerRadius` | `number` | `0` | Inner radius of band rings (donut-style chrome). |
| `ticks / tickValues / tickFormat` | `…` | `5` | Same tick helpers as Cartesian axes. `ticks: 0` draws labels only; `tickFormat` takes a d3-format string or a function. |
| `tickSize / tickPadding` | `number` | `theme (6) / 14` | Tick length (px, inward) and label distance beyond the rim. |
| `fontSize / fill` | `…` | `theme (10 / '#374151')` | Tick-label size and colour. |
| `stroke / strokeWidth` | `…` | `theme ('#6b7280') / 1.25` | Spine and tick colour, and width. Unset options take the theme’s `axis` tokens, as on `axis`. |
| `title` | `string` | | A caption for the axis. |
| `channels` | `object` | `{}` | Placement only — `x`/`y` for one ring per row, and `fill` for band colour. An element views a scale, so this is chrome, not encoding. |
| `id` | `string` | | Stable identity, as on every mark. |
Channels:
| Channel | Type | Description |
| --- | --- | --- |
| `theta` | `linear \| point` | Usually shares the needle’s theta field + range. |
| `fill` | `ordinal` | Colours categorical bands when `bands: true`. Set a palette with `scale: { scheme: "…" }` (add `reverse: true` to flip) or `scale: { range: [...] }`. |
| `x / y` | `linear \| point` | Optional centre (default: plot centre). When bound to fields, one ring is drawn per row (small-multiple needles). |
Returns / emits: A chart **element** emitting background `path`/`line`/`text` nodes.
## Continuous radial ticks
A quantitative `theta` scale gets a spine and tick marks. `theta` is the polar angular position, which is what a needle encodes. `angle`, a mark's rotation in place, has no axis.
### Example: Semi-circle axis
No needle — just the chrome. 0 on the left, 100 on the right.
```javascript
const chart = Elicit({
width: 300, height: 180,
margins: { top: 28, right: 20, bottom: 20, left: 20 },
axes: false,
data: [{ n: 50 }],
schema: { n: { type: "quantitative", domain: [0, 100] } },
marks: [
axisRadial({
outerRadius: 90, ticks: 6, title: "score",
channels: { theta: { field: "n", scale: { range: [180, 0] } } },
}),
],
});
mount(chart.dom());
```
## Coloured categorical bands
A discrete domain gets one annular sector per category, coloured by an ordinal fill.
### Example: Banded likelihood arc
Seven categories across a top-facing semicircle, coloured by the reversed `dddiverging` scheme (blue→coral).
```javascript
const chart = Elicit({
width: 360, height: 210,
margins: { top: 36, right: 64, bottom: 16, left: 64 },
axes: false,
overflow: "visible", // long labels spill into the margin
data: [{ chance: "TOSSUP" }],
schema: {
chance: {
type: "ordinal",
domain: ["VERY LIKELY D", "LIKELY D", "LEANING D", "TOSSUP",
"LEANING R", "LIKELY R", "VERY LIKELY R"],
},
},
marks: [
axisRadial({
outerRadius: 110, bands: true, bandWidth: 28,
tickPadding: 16, fontSize: 8,
channels: {
theta: { field: "chance", scale: { range: [180, 0] } },
// RdBu is red→blue natively; reverse for the D→R (blue→red) reading.
fill: { field: "chance", scale: { scheme: "dddiverging", reverse: true } },
},
}),
],
});
mount(chart.dom());
```
## Tick + label customization
Ticks take the same options as Cartesian axes: `ticks` (a count), `tickValues` (explicit values), and `tickFormat` (a d3-format string or function). Style labels with `fontSize` and `fill`, and the spine with `stroke`, as on `axis`. Unset, they take the theme's axis tokens.
### Example: Percent ticks at chosen values
Explicit tickValues, a percent tickFormat, and a custom label colour.
```javascript
const chart = Elicit({
width: 300, height: 190,
margins: { top: 30, right: 24, bottom: 16, left: 24 },
axes: false,
overflow: "visible",
data: [{ p: 0.5 }],
schema: { p: { type: "quantitative", domain: [0, 1] } },
marks: [
axisRadial({
outerRadius: 95,
tickValues: [0, 0.25, 0.5, 0.75, 1],
tickFormat: ".0%",
fill: "#50AEB7", fontSize: 11,
stroke: "#B7DEE1", tickSize: 8,
channels: { theta: { field: "p", scale: { range: [180, 0] } } },
}),
],
});
mount(chart.dom());
```
## Rings for a radius scale
`axisRadial({ channel: 'radius' })` reads the `radius` scale instead of `theta`. It draws a concentric ring at each tick, labelled up the vertical. Use it to key an [arc](https://elicitjs.github.io/marks/arc.md#radius) whose slices take their rim from a `radius` field. The rings span the scale's own extent, from the arc's `innerRadius` to its `outerRadius`, so the axis's `outerRadius` option has no effect. `ticks`, `tickValues` and `tickFormat` work as on the angular axis.
### Example: Rings for a radius scale
axisRadial({ channel: "radius", ticks: 4 }) behind an arc with radius: { field: "n" }.
```javascript
const chart = Elicit({
width: 300, height: 280,
margins: { top: 16, right: 16, bottom: 16, left: 16 },
axes: false,
data: [
{ month: "Jan", n: 30 }, { month: "Feb", n: 45 }, { month: "Mar", n: 70 },
{ month: "Apr", n: 90 }, { month: "May", n: 60 }, { month: "Jun", n: 40 },
],
schema: {
month: { type: "categorical" },
n: { type: "quantitative", domain: [0, 100] },
},
elements: [
// Concentric rings at the radius scale's ticks, labelled up the vertical.
axisRadial({ channel: "radius", ticks: 4, tickFormat: "d" }),
],
marks: [
arc({
outerRadius: 110, padAngle: 1.5,
channels: {
theta: { value: 1 },
radius: { field: "n" },
fill: { field: "month" },
},
}),
],
});
mount(chart.dom());
```
---
# Legend
> Source: https://elicitjs.github.io/marks/legend/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A legend is a key for one **encoding**: a field on a non-positional channel such as `fill`, `size` or `symbol`. Declare it on the channel (`fill: { field, legend: true }`), or compose `legendColor()` / `legendSize()`. It reserves space on its side, so the plot shrinks and the legend never overlaps the marks. With an edit it becomes a picker: click a swatch to set a category, or drag a ramp handle to set a value.
## API reference
### `ChannelSpec.legend · legendColor · legendSize · legendSymbol`
A key for one **encoding** — a (channel, field) pair. Ask for it on the channel (`fill: { field, legend: true }`), chart-wide with `legends: true`, or by composing an element. The shape follows the channel: swatches, a colour ramp, graduated circles for `size`, a fan for `theta`, a weight stack for `strokeWidth`. It **reserves space** on its side, shrinking the plot so it never overlaps the marks. Import `elements` from `elicitjs`.
JSON keyword: `elements.legendColor`, `elements.legendSize`, `elements.legendSymbol`, `legend`
```ts
fill: { field, legend: true | { anchor, title, edit, … } | false }
legends: true · legends: { fill: { anchor: 'top' }, size: false }
legendColor({ field, anchor, … }) → ChartElement · legendSize · legendSymbol
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channel` | `'fill'\|'stroke'\|'size'\|'symbol'\|'opacity'\|'theta'\|'strokeWidth'\|'strokeDash'` | `'fill'` | Which channel’s scale to draw. legendSize and legendSymbol pin it; legendColor takes 'fill' (default) or 'stroke' and warns on any other. Implied when you declare the legend on the channel. Any other channel warns — an axis is the key for x/y. |
| `anchor` | `'right'\|'left'\|'top'\|'bottom'` | `'right'` | Which side to sit on. Left/right stack vertically; top/bottom lay out in a row. |
| `orientation` | `'vertical' \| 'horizontal'` | `from anchor` | Override the swatch/ramp direction independently of the side. |
| `edit / edits` | `Edit \| Edit[]` | | Opt-in interactivity: edit.legend.category() (click a swatch to set a category) or edit.legend.value() (drag the ramp handle to set a value). |
| `field` | `string` | `the channel's field` | WHICH ENCODING this legend is for. Implied when declared on a channel. On a hand-composed element it is only needed when the channel carries more than one encoding — with two and no field, the first is used and a warning names both. |
| `table` | `string` | `the primary table` | Which table that column is in, by name. Only meaningful on a multi-table schema. |
| `row` | `number \| (data, { selection }) => number` | `selection ?? (single row ? 0 : none)` | Which dataset row the picker writes into. Left unset it tracks the chart's selection (edit.select / chart.select), falling back to the sole row of a one-row belief. A number pins a fixed row; a function computes one. |
| `title` | `string \| false` | `the encoded field's name` | A caption above the legend. Defaults to the field it is a key for; false removes it. |
| `swatchSize / gap / labelWidth` | `number` | `14 / 6 / auto` | Discrete swatch geometry. labelWidth defaults to a per-label estimate. |
| `rampLength / rampThickness / ticks` | `number` | `140 / 12 / 4` | Continuous ramp geometry and its approximate tick count. |
| `tickFormat` | `string \| fn` | `auto` | Ramp tick labels: a d3-format string, or a formatter function. |
| `stroke / fill / fontSize` | `string / number` | `theme` | Chrome, defaulting to the theme’s legend/axis tokens (resolved at build time). |
| `handleColor / handleSize` | `string / number` | `theme / 5` | The ramp handle edit.legend.value() drags. A legend with no edit draws none. |
| `id` | `string` | | Stable identity, as on every mark. |
### `edit.legend.category · edit.legend.value`
The legend pickers, written back through the normal edit pipeline. `edit.legend.category()` is a category picker (a direct-pick click on a swatch, whose value it sets). `edit.legend.value()` is a continuous value picker (a direct-pick drag on the ramp handle). Pass one to a legend’s `edit` option — the legend injects its channel.
JSON keyword: `edit.legend.category`, `edit.legend.value`
```ts
edit.legend.category() → Edit (click a swatch; writes node.category)
edit.legend.value() → Edit (drag the handle; maps to [lo,hi])
```
Options:
| Option | Type | Description |
| --- | --- | --- |
| `—` | `EditOptions` | Neither picker names a column: a legend is a key for one encoding, so the column is the one that encoding uses. They take the universal edit options (name, stage, when, constrain). |
## The legends key
An encoding is a (channel, field) pair. A scale belongs to an encoding, and a legend belongs to a scale.
There are three ways to ask for one, most specific first:
1. **an element you compose** — `legendColor({ field: "group" })`
2. **the channel** — `fill: { field: "group", legend: { anchor: "bottom" } }`
3. **the spec** — `legends: true`
Each wins over the ones below it. `legends: { fill: false }` suppresses a channel; `legend: false` on a channel suppresses that one encoding.
`legends` defaults to off, unlike `axes`. A legend reserves layout space, so adding one shrinks the plot.
Two marks stating the same encoding share one scale and get one legend. Two marks with different fields on one channel are two encodings. They get two scales and two keys, in different colour families.
### Example: legends: true
One key per encoding, with no legend composed by hand.
```javascript
const chart = Elicit({
width: 420, height: 240,
margins: { top: 16, right: 16, bottom: 30, left: 34 },
data: [
{ cat: "A", n: 40, team: "north" },
{ cat: "B", n: 65, team: "south" },
{ cat: "C", n: 28, team: "north" },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C"] },
n: { type: "quantitative", domain: [0, 100] },
team: { type: "categorical", domain: ["north", "south"] },
},
// One legend per ENCODING — per (channel, field) pair, not per channel.
// For per-channel config: `legends: { fill: { anchor: "top" }, size: false }`.
legends: true,
marks: [
bar({
channels: {
x: { field: "cat" },
y: { field: "n", edit: move() },
fill: { field: "team" },
},
}),
],
});
mount(chart.dom());
```
## A discrete colour legend
`legendColor()` draws a swatch per category. Here it names no field: `fill` carries one encoding, so the legend binds to that scale. `anchor` sets which side it's on. The plot shrinks to leave room, so the legend never overlaps the marks.
The title defaults to the encoded field's name.
### Example: Swatches, reserving space
A categorical fill; the legend claims the right band and the bars shrink to fit.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 20, right: 16, bottom: 30, left: 40 },
data: [
{ group: "North", value: 12 },
{ group: "South", value: 8 },
{ group: "East", value: 15 },
{ group: "West", value: 6 },
],
schema: {
group: { type: "categorical", domain: ["North", "South", "East", "West"] },
value: { type: "quantitative", domain: [0, 16] },
},
marks: [
barY({
channels: {
x: { field: "group" },
y: { field: "value" },
fill: { field: "group" },
},
}),
// A legend for the fill channel, reserving space on the right so the bars
// shrink to make room instead of drawing under it.
legendColor({ anchor: "right" }),
],
});
mount(chart.dom());
```
## A continuous colour ramp
A quantitative `fill` resolves to a sequential colour scale, so the same `legendColor()` draws a gradient ramp with ticks.
### Example: Gradient ramp
fill: { field: 'temp' } over a quantitative field becomes a ramp.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 20, right: 16, bottom: 32, left: 44 },
data: [
{ hour: 0, temp: 4 }, { hour: 3, temp: 6 }, { hour: 6, temp: 9 },
{ hour: 9, temp: 16 }, { hour: 12, temp: 24 }, { hour: 15, temp: 27 },
{ hour: 18, temp: 19 }, { hour: 21, temp: 11 },
],
schema: {
hour: { type: "quantitative", domain: [0, 24] },
temp: { type: "quantitative", domain: [0, 30] },
},
marks: [
point({
size: 8,
channels: {
x: { field: "hour" },
y: { field: "temp" },
// A quantitative fill resolves to a SEQUENTIAL colour scale, so the
// legend draws a gradient ramp with ticks instead of swatches.
fill: { field: "temp" },
},
}),
legendColor({ anchor: "right" }),
],
});
mount(chart.dom());
```
## A size legend
`legendSize()` over a quantitative field draws graduated circles at tick values.
The radii come from the channel's scale. `size` defaults to a **linear radius**, so the same pointer movement makes the same change in value anywhere on the scale. Pass `scale: "sqrt"` on the channel for linear area instead, the convention for a static read. The legend follows either way.
```js
size: { field: "people", scale: "sqrt" }
```
### Example: Graduated circles
Nested circles at tick values, sized by the same scale as the dots.
```javascript
const rows = [
{ city: "A", x: 20, y: 70, people: 120 },
{ city: "B", x: 55, y: 40, people: 640 },
{ city: "C", x: 85, y: 76, people: 980 },
{ city: "D", x: 38, y: 22, people: 320 },
];
const chart = Elicit({
width: 400, height: 230,
margins: { top: 20, right: 20, bottom: 24, left: 24 },
axes: false,
data: rows,
schema: {
city: { type: "categorical", domain: ["A", "B", "C", "D"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
people: { type: "quantitative", domain: [0, 1000] },
},
marks: [
point({ fill: "#50AEB7", fillOpacity: 0.5, channels: {
x: { field: "x" }, y: { field: "y" }, size: { field: "people" },
} }),
legendSize({ anchor: "right" }),
],
});
mount(chart.dom());
```
A categorical `size` field gets swatches instead — one dot per category, at that category's radius.
## Theta and stroke width
Every legendable channel gets a key shaped like the channel. `theta` draws a fan of spokes at their encoded bearings. `strokeWidth` draws a stack of segments at their encoded thicknesses. Both read the scale, so the key matches the marks.
### Example: A fan and a weight stack
One needle mark encoding two channels; a key for each.
```javascript
const rows = [
{ site: "A", x: 60, bearing: 20, flow: 2 },
{ site: "B", x: 140, bearing: 75, flow: 6 },
{ site: "C", x: 220, bearing: 130, flow: 9 },
];
const chart = Elicit({
width: 460, height: 210,
margins: { top: 18, right: 18, bottom: 22, left: 22 },
axes: false,
data: rows,
schema: {
site: { type: "categorical", domain: ["A", "B", "C"] },
x: { type: "quantitative", domain: [0, 280] },
bearing: { type: "quantitative", domain: [0, 180] },
flow: { type: "quantitative", domain: [0, 10] },
},
marks: [
// A needle per site: its ANGLE reads bearing, its WIDTH reads flow.
needle({ channels: {
x: { field: "x" },
y: { value: 90 },
theta: { field: "bearing", legend: { anchor: "right" } },
strokeWidth: { field: "flow", legend: { anchor: "right" } },
} }),
],
});
mount(chart.dom());
```
Legendable channels are `fill`, `stroke`, `size`, `symbol`, `opacity`, `theta`, `strokeWidth` and `strokeDash`. A legend on any other channel draws nothing and logs a warning. For `x` and `y`, the axis is the key. `angle`, a mark's rotation in place, has no key.
## Any side
`anchor: 'bottom'` (or `'top'`) lays the swatches out in a row and reserves space on that side. The row sits past the axis, clear of the x-axis labels.
### Example: Legend on the bottom
A horizontal row below the x-axis; the plot height shrinks to fit.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 20, right: 20, bottom: 30, left: 40 },
data: [
{ x: 1, y: 3, group: "A" }, { x: 2, y: 5, group: "B" },
{ x: 3, y: 2, group: "C" }, { x: 4, y: 6, group: "A" },
{ x: 5, y: 4, group: "B" }, { x: 6, y: 7, group: "C" },
],
schema: {
x: { type: "quantitative", domain: [0, 7] },
y: { type: "quantitative", domain: [0, 8] },
group: { type: "categorical", domain: ["A", "B", "C"] },
},
marks: [
point({ size: 7, channels: { x: { field: "x" }, y: { field: "y" }, fill: { field: "group" } } }),
// anchor:'bottom' lays the swatches out in a row and reserves space below
// the x-axis (offset past the author's bottom margin, so it clears the axis).
legendColor({ anchor: "bottom" }),
],
});
mount(chart.dom());
```
## A category picker
Pass `edit: edit.legend.category()` to make each swatch a click target that sets the channel's field on the target row. The target is the legend's `row`, else the selection, else the sole row of a one-row table.
### Example: Click a swatch to pick
A one-row dataset whose category is set by clicking the legend.
Try: **Click** a swatch to set the group; the dot recolours.
```javascript
const chart = Elicit({
width: 320, height: 170,
margins: { top: 20, right: 16, bottom: 20, left: 20 },
data: [ { group: "A" } ],
schema: { group: { type: "categorical", domain: ["A", "B", "C", "D"] } },
axes: false,
marks: [
// A one-row belief. The dot's colour reflects the current category.
point({ size: 26, channels: { x: { value: 90 }, y: { value: 65 }, fill: { field: "group" } } }),
// edit.legend.category() makes each swatch a click target that sets `group`.
legendColor({ anchor: "right", edit: edit.legend.category() }),
],
});
mount(chart.dom());
```
## Two encodings on one channel
A scale belongs to one encoding, so two marks colouring by different fields get two scales. Each has its own domain, colour family and key, and each legend takes its column from the channel.
### Example: Two encodings on fill
Two scales, two keys, two colour families — and each picker writes its own column.
Try: **Click** a swatch in either legend — each writes only its own column.
```javascript
const chart = Elicit({
width: 340, height: 190,
margins: { top: 20, right: 16, bottom: 20, left: 20 },
data: [ { now: "low", goal: "mid" } ],
schema: {
now: { type: "categorical", domain: ["low", "mid", "high"] },
goal: { type: "categorical", domain: ["low", "mid", "high"] },
},
axes: false,
marks: [
// Two marks put DIFFERENT columns on `fill`. That is two encodings, so it
// is two scales — different colour families, not one shared vocabulary.
point({ size: 22, channels: { x: { value: 60 }, y: { value: 70 }, fill: { field: "now" } } }),
point({ size: 22, channels: { x: { value: 60 }, y: { value: 115 }, fill: { field: "goal" } } }),
text({ text: "now", channels: { x: { value: 95 }, y: { value: 74 } }, textAnchor: "start", fontSize: 12 }),
text({ text: "goal", channels: { x: { value: 95 }, y: { value: 119 } }, textAnchor: "start", fontSize: 12 }),
// `field` NAMES the encoding each legend is a key for — the one case where
// it is required, because the channel alone no longer identifies a scale.
// It doubles as the title, so neither legend restates anything.
legendColor({ anchor: "right", field: "now", edit: edit.legend.category() }),
legendColor({ anchor: "right", field: "goal", edit: edit.legend.category() }),
],
});
mount(chart.dom());
```
When you compose a legend **by hand** for a channel that carries two encodings, say which with `field`:
```js
legendColor({ field: "goal" })
```
With one encoding on the channel, leave `field` out. With two and no `field`, the legend takes the first and logs a warning naming both.
In a multi-table schema, `table` names which table the column is in. A hand-composed legend needs it when the encoding doesn't settle the table.
## Declaring it on the channel
Putting `legend:` on the channel is the shortest way to a correct legend. The channel already names the field and the mark names the table, so the legend restates neither.
```js
fill: { field: "group", legend: true }
fill: { field: "group", legend: { anchor: "bottom", title: "region" } }
fill: { field: "group", legend: false } // suppress under legends: true
```
A picker goes in the same place. The gesture happens on the legend, and the bars stay inert.
```js
fill: { field: "group", legend: { edit: edit.legend.category() } }
```
### Example: The picker on the fill channel
No legendColor() in the spec — the legend is built from the encoding.
Try: **Click** a bar to select it, then **click** a swatch to change its group.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 20, right: 16, bottom: 30, left: 40 },
data: [
{ name: "A", value: 12, group: "North" },
{ name: "B", value: 8, group: "South" },
{ name: "C", value: 15, group: "East" },
{ name: "D", value: 6, group: "West" },
],
schema: {
name: { type: "categorical", domain: ["A", "B", "C", "D"] },
group: { type: "categorical", domain: ["North", "South", "East", "West"] },
value: { type: "quantitative", domain: [0, 16] },
},
marks: [
barY({
channels: {
x: { field: "name" },
y: { field: "value" },
// The edit sits on the channel whose column it writes. There is no
// legendColor() in this spec — the legend is minted for `fill`.
fill: { field: "group", edit: edit.legend.category() },
},
edits: [ edit.select() ]
}),
],
});
mount(chart.dom());
```
Compose a `legendColor()` for the same encoding and it takes over that legend, edit included. The channel says what is edited, and the element sets how it looks:
```js
barY({ channels: { fill: { field: "group", legend: { edit: edit.legend.category() } } } }),
legendColor({ anchor: "bottom" }),
```
## Editing a selected item
Selection is interface state, kept outside the data. Give the bars an `edit.select()` and a click selects one, drawing a highlight outline. The legend's `row` defaults to the selection, so the swatch you click edits the bar you picked. See [Selection](https://elicitjs.github.io/editing/selection.md).
The swatch holding the target row's current value is ringed, so the legend shows what a click would replace. With nothing selected, a picker has no target and shows no ring. A one-row table is always the target.
Pin `row` to a number, an array of indices, or a `(data, { selection }) => index` function to override.
### Example: Pick a bar, then edit its group
The bars carry edit.select(); the legend edits the selected bar. Nothing about selection touches the data.
Try: **Click** a bar to select it, then **click** a legend swatch to change its group.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 20, right: 16, bottom: 30, left: 40 },
data: [
{ name: "A", value: 12, group: "North" },
{ name: "B", value: 8, group: "South" },
{ name: "C", value: 15, group: "East" },
{ name: "D", value: 6, group: "West" },
],
schema: {
name: { type: "categorical", domain: ["A", "B", "C", "D"] },
group: { type: "categorical", domain: ["North", "South", "East", "West"] },
value: { type: "quantitative", domain: [0, 16] },
},
marks: [
// Click a bar to SELECT it. Selection is pipeline state (no `selected` column);
// the selected bar gets the highlight outline automatically.
barY({
channels: {
x: { field: "name" },
y: { field: "value" },
fill: { field: "group" },
},
edits: [ edit.select() ]
}),
// The legend picker edits whichever row is currently selected — its `row`
// defaults to the chart's selection, so there is no findIndex to keep in sync.
legendColor({
anchor: "right",
edit: edit.legend.category(),
}),
],
});
mount(chart.dom());
```
## Editing several rows at once
`edit.select({ multi: true })` makes shift-click (or meta-click) add a row to the selection. Shift-click a selected row to take it back out. A plain click still replaces the selection.
A picker writes every selected row, so one swatch click recategorises the whole selection. Where the selected rows hold different values, each of those swatches is ringed.
### Example: Shift-click to select several bars
One swatch click sets the group on every selected bar.
Try: **Click** a bar, **shift-click** another, then **click** a swatch.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 20, right: 16, bottom: 30, left: 40 },
data: [
{ name: "A", value: 12, group: "North" },
{ name: "B", value: 8, group: "South" },
{ name: "C", value: 15, group: "East" },
{ name: "D", value: 6, group: "West" },
],
schema: {
name: { type: "categorical", domain: ["A", "B", "C", "D"] },
group: { type: "categorical", domain: ["North", "South", "East", "West"] },
value: { type: "quantitative", domain: [0, 16] },
},
marks: [
barY({
channels: {
x: { field: "name" },
y: { field: "value" },
// Shift-click adds a bar to the selection; a plain click replaces it.
fill: { field: "group", edit: edit.legend.category() },
},
edits: [ edit.select({ multi: true }) ]
}),
],
});
mount(chart.dom());
```
From your page code, `chart.select([0, 2])` replaces the selection with those rows, `chart.toggleSelection(i)` adds or removes one, `chart.selectAll()` takes every row, and `chart.selectWhere('group', 'North', { all: true })` takes a whole category. `chart.getSelectionAll()` reads them back.
## Editing the category list
The pickers above write a row. `edit.scale.categories()` writes the **domain**: the list of categories on the scale the legend draws. It needs no target row.
Double-click a swatch to rename its category, click the × to drop it, and double-click the + to add one. Renaming relabels every row carrying the old value, and removing deletes those rows, so the schema and the data stay in step.
### Example: Rename, remove, add
The domain and the rows move together.
Try: **Double-click** a swatch to rename · **click** a × to remove · **double-click** the + to add.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 20, right: 16, bottom: 30, left: 40 },
data: [
{ name: "A", value: 12, group: "North" },
{ name: "B", value: 8, group: "South" },
{ name: "C", value: 15, group: "North" },
{ name: "D", value: 6, group: "South" },
],
schema: {
name: { type: "categorical", domain: ["A", "B", "C", "D"] },
group: { type: "categorical", domain: ["North", "South"] },
value: { type: "quantitative", domain: [0, 16] },
},
marks: [
barY({ channels: {
x: { field: "name" },
y: { field: "value" },
fill: { field: "group" },
} }),
// The domain belongs to the scale, so the edit sits on the element drawing it.
legendColor({ anchor: "right", edit: edit.scale.categories() }),
],
});
mount(chart.dom());
```
The same edit works on an axis — `axisX({ edit: edit.scale.categories() })` — because both draw a scale.
Where one scale spans several columns, the edit writes all of them, including columns in different tables. A rename applies to every column that shares the category.
### Example: One vocabulary across two tables
`team` is declared on both nodes and links; renaming writes both schemas and both row sets.
Try: **Double-click** a swatch and rename it — the nodes and the ties move together.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
schema: {
structure: "network",
tables: {
people: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
// The SAME vocabulary is declared on both tables.
team: { type: "categorical", domain: ["#EE7B5E", "#50AEB7"] },
},
},
ties: {
role: "links",
fields: {
source: { type: "ref" },
target: { type: "ref" },
team: { type: "categorical", domain: ["#EE7B5E", "#50AEB7"] },
},
},
},
},
data: {
people: [
{ id: "a", x: 20, y: 75, team: "#EE7B5E" },
{ id: "b", x: 75, y: 78, team: "#50AEB7" },
{ id: "c", x: 48, y: 22, team: "#EE7B5E" },
],
ties: [
{ source: "a", target: "c", team: "#EE7B5E" },
{ source: "b", target: "c", team: "#50AEB7" },
],
},
marks: [
// One `stroke` scale spans BOTH tables' `team` columns.
link({ strokeWidth: 3, channels: { stroke: { field: "team" } } }),
point({ size: 12, fill: "#fff", channels: {
x: { field: "x" }, y: { field: "y" }, stroke: { field: "team" },
} }),
legendColor({ channel: "stroke", anchor: "right", edit: edit.scale.categories() }),
],
});
mount(chart.dom());
```
## A continuous value picker
Pass `edit: edit.legend.value()` to add a handle you drag along the ramp. The handle's position maps to a value in the field's domain, and the edit writes that value.
### Example: Drag the ramp to pick a value
Dragging the handle sets temp; the dot's colour tracks it.
Try: **Drag** the handle up and down the ramp to set the value.
```javascript
const chart = Elicit({
width: 320, height: 210,
margins: { top: 20, right: 16, bottom: 20, left: 20 },
data: [ { temp: 15 } ],
schema: { temp: { type: "quantitative", domain: [0, 30] } },
axes: false,
marks: [
// The dot's colour tracks the elicited value as you drag the ramp handle.
point({ size: 30, channels: { x: { value: 80 }, y: { value: 95 }, fill: { field: "temp" } } }),
// edit.legend.value() adds a handle you drag along the ramp to set `temp`.
// A colour scale isn't invertible, so the edit maps the drag to [0,30] by hand.
legendColor({ anchor: "right", edit: edit.legend.value() }),
],
});
mount(chart.dom());
```
---
# A face, a plant and an hourglass
> Source: https://elicitjs.github.io/case-studies/glyphs/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
Three elicitation interfaces built from existing marks and edits: a face whose colour you slide, a plant you grow, and an hourglass you fill. Each follows the same steps: declare the fields, draw the parts, then put an edit on each channel a gesture should write.
## The steps
1. **Declare the answer.** One field per thing you ask. The `schema` gives each field its type and domain.
2. **Draw the glyph.** A [`composite` in box mode](https://elicitjs.github.io/marks/composite.md#box) places every part in the glyph's own units: `x` and `y` from `-1` to `1`, y up. The composite's `size` sets the box's half-size, so the whole glyph scales with it.
3. **Bind the fields.** A channel with a `field` and a `frame: [lo, hi]` range maps the field's domain onto that slice of the box. Two parts that read the same field and range always line up.
4. **Add the gestures.** An edit on a channel writes that channel's field: `move` for a position, `slide` for a size, colour or angle. A drag passes through any part with no edit.
## A face that changes colour
[`face()`](https://elicitjs.github.io/marks/face.md) already draws a head, eyes, brows and a mouth. Its `fill` channel colours the head, so binding it to a field adds a question with no new parts.
`feeling` runs from `-1` (anger) to `1` (disgust). A diverging scale maps it from red through yellow to green. `slide({ axis: "x" })` on the head writes it, so you drag the head left for anger and right for disgust. `slide` works on a colour ramp because it moves along the field's domain. The mouth keeps its own `slide` on valence, so the two answers come from two different parts.
### Example: Anger or disgust
The emotion preset's mouth, plus a head colour bound to a field: red for anger, green for disgust.
Try: **Drag the head** left or right to colour it · **drag the mouth** up or down.
```javascript
const chart = Elicit({
width: 320, height: 320,
margins: { top: 12, right: 12, bottom: 28, left: 12 },
data: [{ valence: -0.4, feeling: 0 }],
schema: {
valence: { type: "quantitative", domain: [-1, 1] },
// -1 is anger, +1 is disgust, 0 is neither.
feeling: { type: "quantitative", domain: [-1, 1] },
},
marks: [
face({
channels: {
// The mouth bends with valence, as in the emotion preset.
mouthCurve: { field: "valence", edit: slide({ axis: "y", increase: "up" }) },
// The head's colour is a field too: a diverging scale runs red → yellow → green,
// and a sideways slide on the head writes it.
fill: {
field: "feeling",
scale: { type: "diverging", range: ["#d62728", "#ffd666", "#2ca02c"] },
edit: slide({ axis: "x", increase: "right" }),
},
},
}),
text({ channels: { x: { value: 20 }, y: { value: 304 }, text: { value: "← anger" }, textAnchor: { value: "start" }, fill: { value: "#d62728" } } }),
text({ channels: { x: { value: 288 }, y: { value: 304 }, text: { value: "disgust →" }, textAnchor: { value: "end" }, fill: { value: "#2ca02c" } } }),
],
});
mount(chart.dom());
```
## A plant that grows
Three answers about your week, one plant: `energy` is how tall it grows, `joy` how big it blooms, and `support` how full its leaves are.
The stem's top and the flower both read `energy` over the same range, `frame: [-0.15, 0.65]`, so the flower always sits on the stem. Drag the flower up or down: `move({ channels: ["y"] })` writes `energy`. Drag it sideways: a `slide` on its `size` writes `joy`. Each edit reads its own direction of the drag, so one drag can set both.
Each leaf's centre and width both read `support`. As the leaf widens, its centre moves out by the same amount, so its inner edge stays on the stem. Drag a leaf outward to make it fuller.
### Example: How is your week going?
A ruleX stem, two ellipse leaves, a rect pot and a point flower, each placed in the glyph's own units.
Try: **Drag the flower** up to grow the plant, sideways to open the bloom · **drag a leaf** outward.
```javascript
const chart = Elicit({
width: 320, height: 340,
margins: { top: 10, right: 10, bottom: 10, left: 10 },
// How is your week going? Three answers, one plant.
data: [{ energy: 0.5, joy: 0.4, support: 0.5 }],
schema: {
energy: { type: "quantitative", domain: [0, 1] }, // how tall it grows
joy: { type: "quantitative", domain: [0, 1] }, // how big it blooms
support: { type: "quantitative", domain: [0, 1] }, // how full its leaves are
},
marks: [
// Every part is placed in the glyph's own units: x and y run from -1 to 1, y up.
composite({
channels: { size: { value: 150 } },
parts: [
// The stem's top is `energy`; the flower below sits on the same field
// and range, so the two always meet.
ruleX({ channels: {
x: { frame: 0 }, y1: { frame: -0.55 },
y2: { field: "energy", frame: [-0.15, 0.65] },
stroke: { value: "#4d7c0f" }, strokeWidth: { value: 6 },
} }),
// Two leaves. A leaf's centre and its width both read `support`, so its
// inner edge stays on the stem as it grows.
ellipse({ channels: {
x: { field: "support", frame: [-0.08, -0.3] }, y: { frame: -0.3 },
rx: { field: "support", frame: [0.06, 0.28],
edit: slide({ axis: "x", increase: "left" }) },
ry: { frame: 0.07 }, angle: { value: -25 },
fill: { value: "#65a30d" },
} }),
ellipse({ channels: {
x: { field: "support", frame: [0.08, 0.3] }, y: { frame: -0.3 },
rx: { field: "support", frame: [0.06, 0.28],
edit: slide({ axis: "x", increase: "right" }) },
ry: { frame: 0.07 }, angle: { value: 25 },
fill: { value: "#65a30d" },
} }),
// The pot.
rect({ channels: {
x1: { frame: -0.3 }, x2: { frame: 0.3 }, y1: { frame: -0.95 }, y2: { frame: -0.55 },
fill: { value: "#b45309" },
} }),
// The flower: drag it up or down to set `energy`, sideways to set `joy`.
point({ channels: {
y: { field: "energy", frame: [-0.15, 0.65], edit: move({ channels: ["y"] }) },
size: { field: "joy", frame: [0.08, 0.3],
edit: slide({ axis: "x", increase: "right" }) },
fill: { value: "#db2777" },
} }),
point({ channels: {
y: { field: "energy", frame: [-0.15, 0.65] },
size: { field: "joy", frame: [0.03, 0.11] },
fill: { value: "#fde047" },
} }),
],
}),
],
});
mount(chart.dom());
```
## An hourglass you fill
How long will this work take? The timer holds 12 weeks of sand. The top bulb holds your estimate and the bottom holds the rest.
Each pile of sand is a `rect`, drawn as a plain bar. The top pile's upper edge, `y2`, reads `weeks` over `frame: [0, 0.8]`. The bottom pile reads the same field over the mirrored range, `[0, -0.8]`, so as the top drains the bottom fills. Both carry `move({ mode: "relative" })`, so you can drag either pile and its surface stays under the pointer. `snap({ step: 1 })` rounds the answer to whole weeks.
The glass is a [`shape`](https://elicitjs.github.io/marks/shape.md) drawn from an SVG path. A second `shape` is a mask: a box with the glass cut out of it, painted over the sand in the background colour. It trims each bar to the curve of its bulb. Neither shape carries an edit, so a drag passes through them to the sand.
### Example: How long will this take?
Two bars on one field with mirrored ranges, trimmed to the glass by a masking shape and snapped to whole weeks.
Try: **Drag either pile of sand** up or down: the other pile moves the opposite way.
```javascript
// The glass, as an SVG path in its own units (y down, as in SVG): two curved
// bulbs meeting at a narrow neck. `shape` scales a path to fit, so its half-height
// (0.8) is the `size` it is drawn at.
const GLASS = "M-0.42,-0.8 L0.42,-0.8 C0.42,-0.3 0.05,-0.12 0.05,0 C0.05,0.12 0.42,0.3 0.42,0.8 " +
"L-0.42,0.8 C-0.42,0.3 -0.05,0.12 -0.05,0 C-0.05,-0.12 -0.42,-0.3 -0.42,-0.8 Z";
// A mask: a box with the glass cut out of it. Painted over the sand in the
// background colour, it trims each bar to the shape of its bulb.
const MASK = "M-0.46,-0.82 L-0.46,0.82 L0.46,0.82 L0.46,-0.82 Z " + GLASS;
const chart = Elicit({
width: 320, height: 340,
margins: { top: 10, right: 10, bottom: 10, left: 10 },
// How long will this work take? The timer holds 12 weeks of sand; the top
// bulb holds your estimate and the rest has run through.
data: [{ weeks: 4 }],
schema: { weeks: { type: "quantitative", domain: [0, 12] } },
// Whole weeks only.
constraints: [snap({ step: 1 })],
marks: [
composite({
channels: { size: { value: 140 } },
parts: [
// Top sand: a bar from the neck up to `weeks`.
rect({ channels: {
x1: { frame: -0.42 }, x2: { frame: 0.42 }, y1: { frame: 0 },
y2: { field: "weeks", frame: [0, 0.8], edit: move({ mode: "relative" }) },
fill: { value: "#eab308" },
} }),
// Bottom sand: the same field over the mirrored range, so as the top
// drains the bottom fills. It is a handle too.
rect({ channels: {
x1: { frame: -0.42 }, x2: { frame: 0.42 }, y1: { frame: -0.8 },
y2: { field: "weeks", frame: [0, -0.8], edit: move({ mode: "relative" }) },
fill: { value: "#eab308" },
} }),
// The mask, then the glass outline over it.
shape({ symbol: MASK, channels: { size: { frame: 0.82 }, fill: { value: "#ffffff" }, stroke: { value: "none" } } }),
shape({ symbol: GLASS, channels: {
size: { frame: 0.8 }, fill: { value: "none" },
stroke: { value: "#64748b" }, strokeWidth: { value: 2.5 },
} }),
// The wooden caps.
rect({ channels: {
x1: { frame: -0.52 }, x2: { frame: 0.52 }, y1: { frame: 0.8 }, y2: { frame: 0.88 },
cornerRadius: { value: 4 }, fill: { value: "#78350f" },
} }),
rect({ channels: {
x1: { frame: -0.52 }, x2: { frame: 0.52 }, y1: { frame: -0.88 }, y2: { frame: -0.8 },
cornerRadius: { value: 4 }, fill: { value: "#78350f" },
} }),
// The answer, read off the same field.
text({ channels: {
y: { frame: 1 },
text: { fn: (d) => `${d.weeks} week${d.weeks === 1 ? "" : "s"}` },
fontSize: { value: 18 }, fill: { value: "#334155" },
} }),
],
}),
],
});
mount(chart.dom());
```
## Glyphs as points
A glyph's own `x` and `y` place it on the chart's scales, like a `point`. Give the composite a field for each, and you get one glyph per row: a scatter plot when both are quantitative, a grid when both are categories. The positions are data you already have, and the glyphs are the answers. Every part keeps its edit, so each glyph is answered on its own.
With `x` and `y` on band scales, each glyph fills its cell by default. On a continuous scale, set `size` to fix the box's half-size in pixels.
A `move` on the composite's `x` moves the whole glyph, writing both position fields. Its press would compete with the parts' edits, so `when` splits the gestures by modifier:
- `move({ channels: ["x", "y"], pick: "nearest", when: when.shift })` takes a Shift-drag and moves the nearest glyph.
- Every part's own edit takes `when: when.noShift`, so a plain drag still answers with the part you grab.
On a categorical axis the move snaps to the nearest category, so a plant dragged with Shift lands in another cell.
### Example: How does each person feel?
face() with x and y bound to fields: one face per person, placed by hours slept and worked. Shift-drag moves a face.
Try: **Drag a head** sideways to colour that face · **drag a mouth** up or down · **Shift-drag** a face to move it.
```javascript
const chart = Elicit({
width: 400, height: 340,
axes: { x: { title: "Hours slept" }, y: { title: "Hours worked" } },
// How does each person feel? Where each face sits is data you already have:
// hours slept against hours worked. The face is the answer.
data: [
{ name: "Ana", slept: 8, worked: 4, valence: 0.6, feeling: 0 },
{ name: "Ben", slept: 5, worked: 10, valence: -0.5, feeling: -0.6 },
{ name: "Cai", slept: 6.5, worked: 7, valence: 0, feeling: 0.3 },
{ name: "Dee", slept: 9, worked: 9, valence: 0.2, feeling: 0 },
{ name: "Eli", slept: 4.5, worked: 3, valence: -0.2, feeling: 0.7 },
],
schema: {
name: { type: "categorical" },
slept: { type: "quantitative", domain: [4, 10] },
worked: { type: "quantitative", domain: [0, 12] },
valence: { type: "quantitative", domain: [-1, 1] },
feeling: { type: "quantitative", domain: [-1, 1] },
},
marks: [
face({
channels: {
// Placed like a point: x and y are positions on the chart's scales.
// Shift-drag moves the nearest face; a plain drag answers with its parts.
x: { field: "slept", edit: move({ channels: ["x", "y"], pick: "nearest", when: when.shift }) },
y: { field: "worked" },
size: { value: 30 },
mouthCurve: { field: "valence", edit: slide({ axis: "y", increase: "up", when: when.noShift }) },
fill: {
field: "feeling",
scale: { type: "diverging", range: ["#d62728", "#ffd666", "#2ca02c"] },
edit: slide({ axis: "x", increase: "right", when: when.noShift }),
},
},
}),
],
});
mount(chart.dom());
```
### Example: A plant per person per week
The plant as a function of its channels, placed on an ordinal x and a categorical y.
Try: **Drag any flower** up or down to grow its plant · **Shift-drag** a plant to another cell.
```javascript
// The plant from above, as a function of where it goes.
const plant = (channels) => composite({
channels,
parts: [
ruleX({ channels: {
x: { frame: 0 }, y1: { frame: -0.55 },
y2: { field: "energy", frame: [-0.15, 0.65] },
stroke: { value: "#4d7c0f" }, strokeWidth: { value: 3 },
} }),
ellipse({ channels: {
x: { field: "support", frame: [-0.08, -0.3] }, y: { frame: -0.3 },
rx: { field: "support", frame: [0.06, 0.28], edit: slide({ axis: "x", increase: "left", when: when.noShift }) },
ry: { frame: 0.07 }, angle: { value: -25 }, fill: { value: "#65a30d" },
} }),
ellipse({ channels: {
x: { field: "support", frame: [0.08, 0.3] }, y: { frame: -0.3 },
rx: { field: "support", frame: [0.06, 0.28], edit: slide({ axis: "x", increase: "right", when: when.noShift }) },
ry: { frame: 0.07 }, angle: { value: 25 }, fill: { value: "#65a30d" },
} }),
rect({ channels: {
x1: { frame: -0.3 }, x2: { frame: 0.3 }, y1: { frame: -0.95 }, y2: { frame: -0.55 },
fill: { value: "#b45309" },
} }),
point({ channels: {
y: { field: "energy", frame: [-0.15, 0.65], edit: move({ channels: ["y"], when: when.noShift }) },
size: { field: "joy", frame: [0.08, 0.3], edit: slide({ axis: "x", increase: "right", when: when.noShift }) },
fill: { value: "#db2777" },
} }),
point({ channels: {
y: { field: "energy", frame: [-0.15, 0.65] },
size: { field: "joy", frame: [0.03, 0.11] },
fill: { value: "#fde047" },
} }),
],
});
const people = ["Ana", "Ben", "Cai"];
const weeks = ["Week 1", "Week 2", "Week 3"];
const chart = Elicit({
width: 400, height: 360,
// One plant per person per week: both positions are categories, so each
// plant fills its cell.
data: people.flatMap((person, p) => weeks.map((week, w) => ({
person, week, energy: 0.3 + 0.2 * w, joy: 0.3 + 0.1 * p, support: 0.5,
}))),
schema: {
person: { type: "categorical", domain: people },
week: { type: "ordinal", domain: weeks },
energy: { type: "quantitative", domain: [0, 1] },
joy: { type: "quantitative", domain: [0, 1] },
support: { type: "quantitative", domain: [0, 1] },
},
marks: [plant({
// Shift-drag moves the nearest plant to another cell; a plain drag answers.
x: { field: "week", edit: move({ channels: ["x", "y"], pick: "nearest", when: when.shift }) },
y: { field: "person" },
})],
});
mount(chart.dom());
```
### Example: An estimate per task
One hourglass per task, on an ordinal x and a quantitative y.
Try: **Drag the sand** in any hourglass to change that task's estimate · **Shift-drag** an hourglass to move it.
```javascript
// The hourglass from above, as a function of where it goes.
const GLASS = "M-0.42,-0.8 L0.42,-0.8 C0.42,-0.3 0.05,-0.12 0.05,0 C0.05,0.12 0.42,0.3 0.42,0.8 " +
"L-0.42,0.8 C-0.42,0.3 -0.05,0.12 -0.05,0 C-0.05,-0.12 -0.42,-0.3 -0.42,-0.8 Z";
const MASK = "M-0.46,-0.82 L-0.46,0.82 L0.46,0.82 L0.46,-0.82 Z " + GLASS;
const hourglass = (channels) => composite({
channels,
parts: [
rect({ channels: {
x1: { frame: -0.42 }, x2: { frame: 0.42 }, y1: { frame: 0 },
y2: { field: "weeks", frame: [0, 0.8], edit: move({ mode: "relative", when: when.noShift }) },
fill: { value: "#eab308" },
} }),
rect({ channels: {
x1: { frame: -0.42 }, x2: { frame: 0.42 }, y1: { frame: -0.8 },
y2: { field: "weeks", frame: [0, -0.8], edit: move({ mode: "relative", when: when.noShift }) },
fill: { value: "#eab308" },
} }),
shape({ symbol: MASK, channels: { size: { frame: 0.82 }, fill: { value: "#ffffff" }, stroke: { value: "none" } } }),
shape({ symbol: GLASS, channels: {
size: { frame: 0.8 }, fill: { value: "none" },
stroke: { value: "#64748b" }, strokeWidth: { value: 1.5 },
} }),
rect({ channels: {
x1: { frame: -0.52 }, x2: { frame: 0.52 }, y1: { frame: 0.8 }, y2: { frame: 0.88 },
fill: { value: "#78350f" },
} }),
rect({ channels: {
x1: { frame: -0.52 }, x2: { frame: 0.52 }, y1: { frame: -0.88 }, y2: { frame: -0.8 },
fill: { value: "#78350f" },
} }),
text({ channels: {
x: { frame: 0.62 },
text: { fn: (d) => `${d.weeks} wk` },
textAnchor: { value: "start" }, fontSize: { value: 11 }, fill: { value: "#334155" },
} }),
],
});
const chart = Elicit({
width: 400, height: 340,
axes: { y: { title: "Team size" } },
// How long will each task take? Tasks run along x, and the team on each sits
// on y. Each hourglass is one estimate.
data: [
{ task: "Design", team: 2, weeks: 3 },
{ task: "Build", team: 6, weeks: 8 },
{ task: "Test", team: 4, weeks: 4 },
{ task: "Launch", team: 3, weeks: 1 },
],
schema: {
task: { type: "ordinal", domain: ["Design", "Build", "Test", "Launch"] },
team: { type: "quantitative", domain: [0, 8] },
weeks: { type: "quantitative", domain: [0, 12] },
},
constraints: [snap({ step: 1, field: "weeks" })],
marks: [hourglass({
// Shift-drag moves the nearest hourglass; a plain drag on its sand answers.
x: { field: "task", edit: move({ channels: ["x", "y"], pick: "nearest", when: when.shift }) },
y: { field: "team" },
size: { value: 30 },
})],
});
mount(chart.dom());
```
---
# Du Bois's wrapped bars
> Source: https://elicitjs.github.io/case-studies/du-bois-wrapped/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
W. E. B. Du Bois's charts for the 1900 Paris Exposition fold a bar that is too long for the page back on itself, so a large value and a small one share one scale. This page builds the Du Bois wrapped bar chart step by step, then rebuilds two of his charts the same way: a [`track`](https://elicitjs.github.io/marks/track.md) draws each bar as a length along a route, and `move()` on its `length` writes the value. His coil and his spiral are on [the next page](https://elicitjs.github.io/case-studies/du-bois-spiral.md).
## Step by step: a wrapped bar chart
The Du Bois wrapped bar chart (Karduni et al., CHI 2020) turns his fold into a rule. A bar runs to a **threshold**, turns down, and runs back. Here every lane runs the full width, so each one holds the threshold.
**1. Declare the answer.** One row per bar. The `schema` gives `value` its type and domain.
```js
data: [{ name: "A", value: 3000 }, { name: "B", value: 1750 }, /* … */],
schema: {
name: { type: "categorical" },
value: { type: "quantitative", domain: [0, MAX] },
},
```
**2. Choose the threshold and the wrap.** The first lane holds `THRESH`. Each lane after it runs back to `WRAP * THRESH`, so it holds `LANE`. With `WRAP = 0` a lane runs back to zero and holds `THRESH`. A wrap steps down `STEP` of a row.
```js
const THRESH = 1500, WRAP = 0, MAX = 6000;
const LANE = (1 - WRAP) * THRESH; // 1,500
const STEP = 0.3;
```
**3. Map data units to pixels.** Two linear scales do it: `x` maps `[0, THRESH]` across the plot, and `y` gives each level one row. `x` is linear, so every lane has the same pixels per unit.
```js
const x = (v) => X0 + (v / THRESH) * W;
const y = (level) => TOP + level * ROW;
```
**4. Give each row its level.** A row starts below the rows before it, plus the steps their wraps take. The level reads the live rows, so when a bar wraps into another lane, the rows below it move down.
```js
const wraps = (v) => (v > THRESH ? Math.ceil((v - THRESH) / LANE - 1e-9) : 0);
const levelOf = (i, rows) =>
rows.slice(0, i).reduce((level, d) => level + 1 + STEP * wraps(d.value), 0);
```
**5. Write the route.** The **route** is the longest bar a row allows, as an SVG path. Each `M` starts a lane. The route runs right to `THRESH`, steps down, runs back to `WRAP * THRESH`, and repeats until it holds `MAX`. Only lanes hold value, so the steps between them count for nothing.
```js
function routeOf(i, rows) {
let level = levelOf(i, rows), from = 0, to = THRESH, held = THRESH;
let d = `M${x(from)},${y(level)}L${x(to)},${y(level)}`;
while (held < MAX) {
level += STEP;
[from, to] = [to, to === THRESH ? WRAP * THRESH : THRESH];
d += `M${x(from)},${y(level)}L${x(to)},${y(level)}`;
held += LANE;
}
return d;
}
```
**6. Draw the bar along the route.** A `track` takes the route as `path`. Its `length` channel binds `value`: the schema's domain spans the whole route, so 6,000 fills all four lanes and 750 half of the first. `join: "round"` draws each step down as a half circle that bulges outward. `stroke` colours the bar by its value, from teal to red.
```js
track({
path: (d, i, rows) => routeOf(i, rows),
join: "round",
channels: {
length: { field: "value", edit: move() },
stroke: { field: "value", scale: { range: ["teal", "red"] } },
strokeWidth: { value: 7 },
},
}),
```
**7. Drag the end of the bar.** `move()` on `length` puts the end of the bar at the point of the route nearest the pointer. It follows the route from where the bar ends, so drag round a turn to carry the bar into the next lane. You can press anywhere on a row's route, even where no bar is drawn, so a bar at zero can still be grabbed. Every redraw reads the new value, so the bar, its colour and the rows below follow it.
`constraints: [snap({ step: 1 })]` keeps each answer a whole number.
**8. Add the axis.** A `guides.custom` draws the x axis over `[0, THRESH]`.
### Example: A wrapped bar chart
Eight categories on one scale. A value over 1,500 turns down and runs back, and the rows below it move down.
Try: **Drag the end of a bar** along its row: round the right edge it turns down and the rows below move down · **press** further along a bar’s lane to jump its end there.
```javascript
// ── This chart's route: a bar that wraps at a threshold ─────────────────
// In data units, X is the value and Y is a level (one per row). A bar runs
// right to THRESH, steps down, runs back left to WRAP * THRESH, steps down,
// and so on. Each `M` starts a lane; the steps between lanes hold no value.
const THRESH = 1500, WRAP = 0, MAX = 6000;
const LANE = (1 - WRAP) * THRESH; // what each lane after the first holds
const STEP = 0.3; // how far down a wrap steps, in levels
// Two linear scales map the route to pixels: x from [0, THRESH], y one row per level.
const X0 = 70, W = 470, TOP = 30, ROW = 36;
const x = (v) => X0 + (v / THRESH) * W;
const y = (level) => TOP + level * ROW;
// How many times a value wraps, and so how many levels its row takes.
const wraps = (v) => (v > THRESH ? Math.ceil((v - THRESH) / LANE - 1e-9) : 0);
// The level a row starts on: the rows before it, plus their wraps. It changes
// as you drag, so the rows below a wrapping bar move down.
const levelOf = (i, rows) =>
rows.slice(0, i).reduce((level, d) => level + 1 + STEP * wraps(d.value), 0);
// The longest bar a row allows, as one lane per `M`. It holds MAX.
function routeOf(i, rows) {
let level = levelOf(i, rows), from = 0, to = THRESH, held = THRESH;
let d = `M${x(from)},${y(level)}L${x(to)},${y(level)}`;
while (held < MAX) {
level += STEP;
[from, to] = [to, to === THRESH ? WRAP * THRESH : THRESH];
d += `M${x(from)},${y(level)}L${x(to)},${y(level)}`;
held += LANE;
}
return d;
}
// The x axis over [0, THRESH].
const xAxis = guides.custom(() =>
[0, 250, 500, 750, 1000, 1250, 1500].flatMap((v) => [
{ type: "line", x1: x(v), x2: x(v), y1: TOP - 14, y2: 420, stroke: "#dddddd", strokeWidth: 0.75, background: true },
{ type: "text", x: x(v), y: 432, text: v.toLocaleString("en-US"), fontSize: 10, fill: "#555555", textAnchor: "middle" },
]),
);
const chart = Elicit({
width: 640, height: 450,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
data: [
{ name: "A", value: 3000 }, { name: "B", value: 1750 }, { name: "C", value: 500 },
{ name: "D", value: 2300 }, { name: "E", value: 300 }, { name: "F", value: 800 },
{ name: "G", value: 50 }, { name: "H", value: 150 },
],
schema: {
name: { type: "categorical" },
value: { type: "quantitative", domain: [0, MAX] },
},
constraints: [snap({ step: 1 })],
guides: [xAxis],
marks: [
track({
path: (d, i, rows) => routeOf(i, rows),
join: "round",
channels: {
length: { field: "value", edit: move() },
stroke: { field: "value", scale: { range: ["teal", "red"] } },
strokeWidth: { value: 7 },
},
}),
text({ channels: {
x: { value: X0 - 16 }, y: { fn: (d, i, rows) => y(levelOf(i, rows)) },
text: { field: "name" }, textAnchor: { value: "end" },
fontSize: { value: 13 }, fill: { value: "#333333" },
} }),
text({ channels: {
x: { value: X0 + W + 16 }, y: { fn: (d, i, rows) => y(levelOf(i, rows)) },
text: { fn: (d) => d.value.toLocaleString("en-US") }, textAnchor: { value: "start" },
fontSize: { value: 11 }, fill: { value: "#555555" },
} }),
],
});
mount(chart.dom());
```
## Du Bois's charts
The two charts below use the same `track` and the same `move()` on `length`. Drag the end of a bar along its route. Only the route changes. Both are wrapped bars in data units, with `WRAP = 0` and a row per level.
Every row's route holds the same length, so the rows share one scale.
## A bar that folds back and forth
A wrapped bar with a threshold of 900 students and three lanes. The bar runs right, turns down through a half circle, runs left, and turns again. The turns hold no students. Industrial, at 2,252, fills two lanes and part of a third.
### Example: Courses of study
Du Bois's count of Black students in each course of study in Georgia schools. A bar longer than one lane folds back.
Try: **Drag the end of Normal** right, round the turn and back · **drag the end of Industrial** back to unfold it.
```javascript
// ── This chart's route: lanes that fold back and forth ──────────────────
// In data units, X is students along a lane and Y is a level (one per row).
// A lane holds 900. Each `M` starts a lane; the turns hold no value.
const THRESH = 900, MAX = 2700;
const STEP = 0.35; // how far down a turn steps, in levels
// Two linear scales map the route to pixels: x from [0, THRESH], y one row per level.
const X0 = 190, W = 400, TOP = 28, ROW = 74;
const x = (v) => X0 + (v / THRESH) * W;
const y = (level) => TOP + level * ROW;
// The longest bar a row allows: three lanes, right, left, right.
function routeOf(i) {
let d = "";
for (let lane = 0; lane < MAX / THRESH; lane++) {
const [from, to] = lane % 2 === 0 ? [0, THRESH] : [THRESH, 0];
const level = i + lane * STEP;
d += `M${x(from)},${y(level)}L${x(to)},${y(level)}`;
}
return d;
}
const chart = Elicit({
width: 640, height: 470,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
theme: { background: "#ecdcc6" },
// Number of Black students taking each course of study in Georgia schools.
data: [
{ course: "Business", students: 12 },
{ course: "Classical", students: 98 },
{ course: "Professional", students: 152 },
{ course: "Scientific", students: 161 },
{ course: "Normal", students: 383 },
{ course: "Industrial", students: 2252 },
],
schema: {
course: { type: "categorical" },
students: { type: "quantitative", domain: [0, MAX] },
},
constraints: [snap({ step: 1 })],
marks: [
track({
path: (d, i) => routeOf(i),
join: "round",
channels: {
length: { field: "students", edit: move() },
stroke: { value: "#5c4a3d" }, strokeWidth: { value: 9 },
},
}),
text({ channels: {
x: { value: 20 }, y: { fn: (d, i) => y(i) },
text: { fn: (d) => d.course.toUpperCase() },
textAnchor: { value: "start" }, fontSize: { value: 12 }, fill: { value: "#3b2f27" },
} }),
text({ channels: {
x: { value: X0 - 14 }, y: { fn: (d, i) => y(i) },
text: { field: "students" },
textAnchor: { value: "end" }, fontSize: { value: 12 }, fill: { value: "#3b2f27" },
} }),
],
});
mount(chart.dom());
```
## A tight turn
The same route with two lanes. A lane holds 85,000 men, and the turn is 12px across, so the returning lane sits between two rows. Du Bois bracketed fifteen smaller trades together. The last row is their sum.
### Example: Occupations of Georgia men
Black men over ten in Georgia by occupation, 1890. Agricultural laborers run past the lane and turn back under it.
Try: **Drag the end of any bar** past 85,000 and round the turn to fold it back.
```javascript
// ── This chart's route: one lane, then a tight turn back ────────────────
// In data units, X is men along a lane and Y is a level (one per row). A lane
// holds 85,000. The bar turns down and runs back under itself.
const THRESH = 85000, MAX = 170000;
const STEP = 0.375; // how far down the turn steps, in levels
// Two linear scales map the route to pixels: x from [0, THRESH], y one row per level.
const X0 = 236, W = 380, TOP = 22, ROW = 32;
const x = (v) => X0 + (v / THRESH) * W;
const y = (level) => TOP + level * ROW;
// The longest bar a row allows: right, then back left one step down.
const routeOf = (i) =>
`M${x(0)},${y(i)}L${x(THRESH)},${y(i)}` +
`M${x(THRESH)},${y(i + STEP)}L${x(0)},${y(i + STEP)}`;
const chart = Elicit({
width: 640, height: 290,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
theme: { background: "#ecdcc6" },
// Occupations of Black men over ten in Georgia, 1890. The last row is the
// fifteen smaller trades Du Bois bracketed together, summed.
data: [
{ occupation: "Agricultural laborers", men: 98400 },
{ occupation: "Farmers and planters", men: 83012 },
{ occupation: "Laborers", men: 28723 },
{ occupation: "Steam railway employees", men: 7440 },
{ occupation: "Servants", men: 7000 },
{ occupation: "Draymen, hackmen", men: 4390 },
{ occupation: "Carpenters and joiners", men: 3761 },
{ occupation: "Fifteen other trades", men: 15897 },
],
schema: {
occupation: { type: "categorical" },
men: { type: "quantitative", domain: [0, MAX] },
},
constraints: [snap({ step: 1 })],
marks: [
track({
path: (d, i) => routeOf(i),
join: "round",
channels: {
length: { field: "men", edit: move() },
stroke: { value: "#d1213f" }, strokeWidth: { value: 7 },
},
}),
text({ channels: {
x: { value: 14 }, y: { fn: (d, i) => y(i) },
text: { fn: (d) => d.occupation.toUpperCase() },
textAnchor: { value: "start" }, fontSize: { value: 10 }, fill: { value: "#3b2f27" },
} }),
text({ channels: {
x: { value: X0 - 10 }, y: { fn: (d, i) => y(i) },
text: { fn: (d) => d.men.toLocaleString("en-US") },
textAnchor: { value: "end" }, fontSize: { value: 10 }, fill: { value: "#3b2f27" },
} }),
],
});
mount(chart.dom());
```
Du Bois's other charts wind in place of folding. [The next page](https://elicitjs.github.io/case-studies/du-bois-spiral.md) writes a coil and a spiral as routes in pixels.
---
# Du Bois's coil and spiral
> Source: https://elicitjs.github.io/case-studies/du-bois-spiral/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
Two of Du Bois's charts for the 1900 Paris Exposition do not fold a bar back and forth: they wind it, into a square coil and into a spiral. A coil and a spiral are geometry, so each route is written in pixels in place of data units. The chart is the same [`track`](https://elicitjs.github.io/marks/track.md) with `move()` on its `length` as on the [wrapped bars page](https://elicitjs.github.io/case-studies/du-bois-wrapped.md); only the route changes. Every row's route holds the same length, so the rows share one scale.
## A square coil
The route runs right along the bottom, up, back left and down, then turns inward one step and goes round again. Each side is one step shorter than the side before it on that axis. The route is one lane, so the corners hold value too, and every pixel of the coil holds about 1,750 people.
### Example: Religion of Black Americans
14,517 Catholics beside 2,659,460 Protestants. The Protestant bar coils inward to fit the page.
Try: **Drag the end of the green coil** to wind it further in · **drag the end of the red bar** along the coil to grow it.
```javascript
// ── This chart's route: a square coil ───────────────────────────────────
// Right along the bottom, up, back left, down, and inward, a step at a time.
// One lane: the corners are part of it, so every pixel of the coil holds value.
const START = 130, W = 440, H = 140, STEP = 30;
const baseY = (i) => 160 + i * 180;
function routeOf(i) {
const dirs = [[1, 0], [0, -1], [-1, 0], [0, 1]];
let [x, y] = [START, baseY(i)];
let d = `M${x},${y}`;
for (let k = 0; ; k++) {
const len = k % 2 === 0 ? W - (k / 2) * STEP : H - ((k - 1) / 2) * STEP;
if (len <= STEP) break;
x += dirs[k % 4][0] * len;
y += dirs[k % 4][1] * len;
d += `L${x},${y}`;
}
return d;
}
const COLOURS = ["#c8243b", "#1f7a45"];
const chart = Elicit({
width: 600, height: 370,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
theme: { background: "#ecdcc6" },
// Religion of Black Americans, from Du Bois's chart.
data: [
{ church: "Catholics", members: 14517 },
{ church: "Protestants", members: 2659460 },
],
schema: {
church: { type: "categorical" },
members: { type: "quantitative", domain: [0, 4000000] },
},
constraints: [snap({ step: 1 })],
marks: [
track({
path: (d, i) => routeOf(i),
channels: {
length: { field: "members", edit: move() },
stroke: { fn: (d, i) => COLOURS[i] }, strokeWidth: { value: 20 },
},
}),
text({ channels: {
x: { value: 14 }, y: { fn: (d, i) => baseY(i) },
text: { field: "church" },
textAnchor: { value: "start" }, fontSize: { value: 12 }, fill: { value: "#3b2f27" },
} }),
text({ channels: {
x: { value: START - 10 }, y: { fn: (d, i) => baseY(i) - 20 },
text: { fn: (d) => d.members.toLocaleString("en-US") },
textAnchor: { value: "end" }, fontSize: { value: 11 }, fill: { value: "#3b2f27" },
} }),
],
});
mount(chart.dom());
```
## A spiral
Each year starts at the top and runs clockwise. Its radius shrinks by six bands a turn, so the turns of all six years nest without touching. The value is the length of the spiral, so an outer turn holds more than an inner one. Each year's spiral is cut to the same length, which holds $1,600,000.
### Example: Furniture owned by Black Georgians
The assessed value of household and kitchen furniture, 1875 to 1899. Each year is a band of the spiral.
Try: **Drag the end of a band** to wind it further round · **drag the short pink band** at the top clockwise to grow 1875.
```javascript
// ── This chart's route: a spiral ────────────────────────────────────────
// Each year starts at the top and runs clockwise. Its radius shrinks by six
// bands a turn, so the turns of all six years nest without touching.
const CX = 330, CY = 290, R0 = 230, BAND = 12, PITCH = 6 * BAND;
// Every year's spiral is LENGTH px long, so the years share one scale.
const MAX = 1600000, LENGTH = 1227;
const radius = (i) => R0 - i * BAND;
function routeOf(i) {
let d = "", run = 0, prev = null;
for (let deg = 0; run < LENGTH; deg += 3) {
const t = (deg * Math.PI) / 180, r = radius(i) - (PITCH * deg) / 360;
const p = [CX + r * Math.sin(t), CY - r * Math.cos(t)];
if (prev) run += Math.hypot(p[0] - prev[0], p[1] - prev[1]);
d += `${prev ? "L" : "M"}${p[0].toFixed(1)},${p[1].toFixed(1)}`;
prev = p;
}
return d;
}
const COLOURS = ["#e8a2a2", "#8e9fd3", "#b39b7d", "#f0b02c", "#d6ccb8", "#dc1f45"];
const chart = Elicit({
width: 580, height: 540,
margins: { top: 0, right: 0, bottom: 0, left: 0 },
theme: { background: "#ecdcc6" },
// Assessed value of household and kitchen furniture owned by Black
// Georgians, in dollars.
data: [
{ year: 1875, value: 21186 },
{ year: 1880, value: 498532 },
{ year: 1885, value: 736170 },
{ year: 1890, value: 1173624 },
{ year: 1895, value: 1322694 },
{ year: 1899, value: 1434975 },
],
schema: {
year: { type: "ordinal" },
value: { type: "quantitative", domain: [0, MAX] },
},
constraints: [snap({ step: 1 })],
marks: [
track({
path: (d, i) => routeOf(i),
channels: {
length: { field: "value", edit: move() },
stroke: { fn: (d, i) => COLOURS[i] }, strokeWidth: { value: 9 },
},
}),
text({ channels: {
x: { value: CX - 12 }, y: { fn: (d, i) => CY - radius(i) },
text: { fn: (d) => `${d.year} — $${d.value.toLocaleString("en-US")}` },
textAnchor: { value: "end" }, fontSize: { value: 11 }, fill: { value: "#3b2f27" },
} }),
],
});
mount(chart.dom());
```
---
# Editing
> Source: https://elicitjs.github.io/editing/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
An edit writes a gesture back to the data, through the same scale that encodes it. It sets a `gesture` (`drag`, `click`, `dblclick`, `commit` or `wheel`), a `pick` such as `direct`, `nearest`, `plane`, `probe` or `sweep`, and optionally `when`, `constrain` and `guide`; its `apply` performs the inversion. Declare it on a channel (`channels.y.edit`), at mark level (`edits: [...]`), or on a [legend](https://elicitjs.github.io/editing/legend.md) or [axis](https://elicitjs.github.io/editing/axis.md).
## API reference
### `The Edit descriptor`
Every edit factory (`edit.*`) returns this shape, built by `makeEdit`. The named factories are presets over it: each fixes a `gesture` and an `apply` — the inversion that turns the gesture back into data. `apply(ctx)` is pure: given the context it returns a datum (direct edit), a full array (whole-dataset edit), or `undefined` (no-op).
JSON keyword: `edit`
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `gesture` | `'drag'\|'click'\|'dblclick'\|'commit'\|'wheel'` | `'drag'` | The raw gesture that triggers the edit. 'commit' is a value arriving from an inline editor or an external control. 'wheel' is a wheel tick over the plot. |
| `channels` | `string[] \| null` | `null` | Channel names it governs; `null` injects the channel it was placed on. |
| `when` | `(ctx) => boolean` | `null` | Arbitration — whether this edit claims the gesture (e.g. only on Shift). A drag is asked once, at the press, and keeps its answer until the release. See `edit.when`. |
| `pick` | `'direct'\|'nearest'\|'plane'\|'probe'\|'sweep'\|'draw'\|'brush'\|'brushRect'\|'moveSeries'\|'slide'\|'pan'\|string` | `'direct'` | How the gesture selects its target. Everything but `direct` and `plane` routes through a driver; register your own with `authoring.registerDriver` and name it here. Each edit takes the picks that fit it; another logs a warning and the edit keeps its default. |
| `threshold` | `number` | `40` | Proximity radius (px) for `nearest`-style picks. `edit.line.moveSeries` defaults to `6`, and an axis handle to `14`. |
| `scope` | `null \| 'line' \| 'stack' \| 'waffle' \| 'trend' \| 'network' \| 'geo' \| 'axis' \| 'legend' \| 'scale'` | `null` | The mark capability this edit needs. A mismatch warns instead of silently doing nothing. |
| `constrain` | `Constraint[]` | `[]` | Per-edit constraint sugar; the canonical home is the spec’s `constraints` (the dataset’s invariants). |
| `guide` | `boolean` | `null` | Self-draw this edit’s guide (constraint bounds + snap ring). |
| `name` | `string` | `null` | The handle an external control addresses this edit by — `chart.control(name)`. See [External controls](https://elicitjs.github.io/editing/external-controls.md). Unnamed edits stay pointer- and keyboard-driven. |
| `channel` | `string` | | The single-channel spelling of `channels`. Every factory takes either; the singular wins, so it overrides a factory’s own default. |
| `cursor` | `string` | `from the edit` | The CSS cursor over the edit’s marks. The default follows the edit: a drag along x shows `ew-resize`, along y `ns-resize`, on both `move`; a click shows `pointer`; a typed edit shows `text`. Set it to override, e.g. `move({ cursor: "grab" })`. |
| `stage` | `number` | `null` | Only active when the chart is on this stage. See [Stages](https://elicitjs.github.io/editing/probe.md#basics). |
| `advance` | `boolean` | `true` | Whether a settled `probe` click moves to the next stage. Set `false` to commit repeatedly within one stage. |
| `table` | `string` | `the mark's table` | Which table this edit writes to, by role (nodes, links, nesting) or by name, as a constraint's table. A name that matches no table warns, and the edit writes its mark's table. Only meaningful on a multi-table schema. |
| `target` | `'domain'` | | Write the **schema** rather than the dataset. Set by `edit.axis.*` and `edit.scale.*`; see [Editing the scale](https://elicitjs.github.io/editing/axis.md). |
| `type` | `string` | | The edit’s kind, as its dotted path (`move`, `line.draw`, `geo.brush`). Each factory sets its own. |
| `apply` | `(ctx) => datum \| data[] \| undefined` | | The edit itself — maps the gesture to data through the same scale. Never mutate `ctx.data`; return a new datum or array. |
Returns / emits: An **Edit**. The engine matches `gesture` + `pick`, builds an `EditContext`, then calls `apply(ctx)`. Three more keys — `cardinality`, `inverts` and `inline` — declare what a new edit does to the dataset; see [Authoring](https://elicitjs.github.io/authoring.md).
### `EditContext (ctx)`
The object handed to `apply(ctx)` and `when(ctx)` — and to `custom(fn)`'s one argument. It is the gesture already resolved into plot space plus the mark/scale state needed to invert it. Built once per edit invocation in the engine; read it, don’t mutate it.
Options:
| Option | Type | Description |
| --- | --- | --- |
| `pointer` | `{ x, y }` | Pointer position in **plot pixels** (origin at the plot’s top-left, inside the margins). Invert with `ctx.scales.y.invertValue(ctx.pointer.y)`. |
| `datum` | `object \| undefined` | The row being edited. Set for direct/nearest picks; absent for plane creates that append. |
| `index` | `number \| null` | Index of `datum` in `data`. Returning a plain object splices it back at this index. |
| `data` | `Datum[]` | The full current dataset (read-only). Return a new array from `apply` for whole-dataset edits (create/remove). |
| `scales` | `ScaleMap` | Live scales by channel name (`ctx.scales.x`, `.y`, …). Each has `invertValue(pixel)` / `encode(value)`. |
| `channels` | `ResolvedChannel[]` | This edit’s governed channels, each `{ name, field, scale }`. Empty when the edit named none (typical for bare `custom`). |
| `markChannels` | `object` | The mark’s full channel map (name → ChannelSpec). Use to look up a sibling field the edit didn’t declare. |
| `event` | `Event` | The raw DOM event (for modifiers like `shiftKey`). Prefer `edit.when` for arbitration when you can. |
| `node` | `FeatureNode \| null` | The scene node the edit acts on: the one under the pointer, or the one a nearest, sweep or probe pick chose. Null when the gesture names no row (plane). |
| `value` | `any` | Non-pixel gesture payload — e.g. the typed string from `editText`’s `commit`. Undefined for pointer gestures. |
| `schema, width, height` | | Dataset schema (for minting rows) and the plot’s inner pixel size (for plane-relative geometry like rotate). |
Returns / emits: A line-scoped or driver-backed edit sees more — `seriesKey`, `connect`, and the driver’s own `session`. The TypeScript definitions carry the full shape.
### `Edit catalogue`
Universal edits sit on `edit` itself (`edit.move`). A scoped family sits under the subject it is about, and that dotted path is also the edit’s `type`: `edit.line.draw()` is `{ type: "line.draw" }`.
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `move · moveSpan · brushSpan · brushRect` | `drag` | `gestures · handles` | Position. `move` inverts the pointer on each positional channel; the other three move or resize a two-endpoint span or a 2-D box. |
| `slide · resize · rotate` | `drag` | `gestures` | Magnitude and angle. The pointer’s axial distance (`slide`), radius (`resize`) or angle about a pivot (`rotate`) inverts to a value. |
| `cycle · toggle` | `click` | `gestures` | Discrete value. `cycle` advances a channel to its next domain value, and `toggle` flips a row in or out. |
| `set` | `commit` | `gestures · external controls` | Write a value into the channel’s field. Its input is the value itself, so an external control drives it. |
| `rank` | `drag` | `gestures` | Drag a row to a new place in the order. |
| `create · remove` | `click` | `existence` | Mint a datum from the pointer, or delete the target. |
| `editText` | `dblclick` | `sticker` | Open an inline editor over the mark and write the typed string back. |
| `select` | `click` | `selection` | Chart state, not a data row — which rows the chart considers selected. |
| `custom` | `drag` | `gestures` | An arbitrary `(ctx) => …` over the full EditContext, for anything the named edits do not cover. |
| `edit.line.*` | `line` | `sweep · existence` | `anchor`, `newSeries`, `draw`, `sweep`, `removeSeries`, `moveSeries` — author, reshape and move connected paths. Needs a series-grouping mark. |
| `edit.axis.scale` | `axis` | `axis` | Reshape a positional **domain** rather than the dataset: drag an axis end to rescale it. |
| `edit.view.zoom · pan` | `view` | `view` | Move the view rather than the dataset: zoom with the wheel, or drag the plot to pan. Declared in the spec’s `view`. See [Zoom & pan](https://elicitjs.github.io/editing/axis.md#wheel). |
| `edit.scale.categories` | `scale` | `axis · legend` | Add, rename and remove categories, on an axis or a legend. `categories()` returns three edits — spread it. |
| `edit.legend.category · edit.legend.value` | `legend` | `legend` | Turn a legend into an input: click a swatch, or drag the ramp handle. |
| `edit.stack.cut · edge · merge` | `stack` | `sweep · handles` | Divide a whole among rows: split a segment, move value across a boundary, fuse two back into one. |
| `edit.trend.*` | `trend` | `trend` | `intercept`, `slope`, `interceptSpread`, `slopeSpread` — edit a parametric line by its parameters. |
| `edit.waffle.fill` | `waffle` | `waffle` | Fill up to the exact cell under the pointer. |
| `edit.network.connect · rewire · reverse` | `network` | `network` | Build a network's topology. Nodes themselves are plain create / remove. |
| `edit.hierarchy.nest` | `drag` | `hierarchy` | Drag a node into a container, or out of one. It writes the nesting table. |
| `edit.geo.*` | `geo` | `geo` | `move`, `create`, `draw`, `moveSeries`, `brush`, `createRect` — the universal edits on a map’s `lon`/`lat` channels, placed through the chart’s projection. |
| `edit.when` | `predicate` | `gestures` | Not an edit — the arbitration predicates for an edit’s `when` (`when.shift`, `when.alt`, …). |
Returns / emits: See [Gestures](https://elicitjs.github.io/editing/gestures.md), [Sweep](https://elicitjs.github.io/editing/sweep.md), [Existence](https://elicitjs.github.io/editing/existence.md) and each mark’s page for a factory’s own options. There is no `edit.face.*`: a face is a composite of ordinary marks, so its parameters take the universal edits.
## Move a value
`move()` inverts the pointer on each positional channel it governs. On a bar's `y`, a drag rewrites the value.
### Example: Drag a value (bars)
y carries edit: move(). The gesture → data path mirrors the data → height encoding.
Try: **Drag** a bar up or down.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
bar({
fill: "#50AEB7",
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Pick — how an edit finds its target
`pick: "direct"` uses the mark under the pointer. `pick: "nearest"` takes the closest mark within a pixel threshold, so you can grab small marks from nearby empty space. `guide: true` draws the snap ring.
An edit acts on the same part of a mark whichever way it finds it: `edit.stack.edge()` drags a boundary handle, not the segment, under `direct` and `nearest` alike. Each edit takes the picks that fit what it writes:
- An edit that writes a row (`move`, `cycle`, `remove`, `edit.stack.*`, …) takes `direct`, `nearest` or `probe`. A drag that paints values (`move`, `slide`, `resize`) also takes `sweep`.
- An edit that places a new row (`create`, `toggle`, `edit.line.anchor()`) takes `plane` or `probe`.
- An edit served by one driver (`edit.line.draw()`, the brushes, `edit.network.connect()`, `edit.axis.*`, the legend edits) takes only its own pick.
Any other pick logs a warning, and the edit keeps its default. So does a drag `gesture` on a click edit such as `remove` or `cycle`.
### Example: Nearest pick from empty space
A 2D nearest drag: move near a dot to select it, drag from empty space to grab the closest.
Try: **Drag** from anywhere near a dot to grab it.
```javascript
const chart = Elicit({
width: 340, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: 25, y: 35 }, { x: 55, y: 68 }, { x: 78, y: 30 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#50AEB7",
size: 10,
channels: {
x: { field: "x" },
y: { field: "y" },
},
edits: [ move({ channels: ["x", "y"], pick: "nearest", threshold: 45, guide: true }) ],
}),
],
});
mount(chart.dom());
```
---
# Transforms & Modalities
> Source: https://elicitjs.github.io/editing/gestures/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A transform maps input to a channel's value through that channel's scale. `move` sets position, `resize` and `slide` set magnitude, `rotate` sets an angle, and `cycle` steps through categories. `toggle` adds or removes a row in a slot, `set` writes a value outright, `rank` reorders rows, and `custom` does anything else. A mark that takes a drag also takes the arrow keys, through the same edit and constraints.
## API reference
### `move(options)`
Position edit — inverts the pointer on each positional channel. On x+y a 2D move; on y alone a bar drag.
JSON keyword: `edit.move`
```ts
move({ channel, channels, mode, pick, threshold, when, guide, constrain }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channel` | `string` | `injected` | A single channel to govern (co-located edits inject their own). |
| `channels` | `string[]` | | Multiple channels for a joint move (e.g. `["x","y"]`). |
| `mode` | `'absolute'\|'relative'` | `'absolute'` | `absolute` puts the mark’s centre at the pointer. `relative` moves it by the drag distance instead, so the point you grabbed stays under the pointer — use it on anything with area, such as a `rect` or a [sticker](https://elicitjs.github.io/marks/sticker.md), where an absolute move snaps the mark as soon as you press it. Relative mode is direct-pick. |
| `pick` | `'direct'\|'nearest'\|'sweep'` | `'direct'` | Target selection; `nearest` grabs from anywhere within `threshold`. |
| `guide` | `boolean` | | Draw the constraint bounds + snap ring while dragging. |
| `when, threshold, constrain` | | | Shared Edit fields (see the Editing overview). |
Returns / emits: An **Edit**. `apply` returns the datum with each governed field rewritten from the pointer.
### `resize(options)`
Magnitude edit — the gesture radius from the mark centre inverts back to the channel value.
JSON keyword: `edit.resize`
```ts
resize({ channel }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channel` | `string` | `injected` | The magnitude channel, usually `size`. Its scale must be invertible. |
Returns / emits: An **Edit** returning the datum with the channel field set from the pointer radius.
### `slide(options)`
Magnitude edit — a linear drag along one axis maps onto the channel's domain. The linear alternative to resize (radial).
JSON keyword: `edit.slide`
```ts
slide({ axis, increase, extent, mode, channel }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `axis` | `'x' \| 'y'` | `'x'` | Which pointer coordinate drives the value. |
| `increase` | `'left'\|'right'\|'up'\|'down'` | `'right' / 'up'` | The direction that raises the value (left/right for axis x, up/down for axis y). |
| `extent` | `number` | `glyph radius, else 120` | Drag distance that sweeps the full domain. Inside a composite's local box it defaults to the glyph's radius, so the gesture scales with the glyph. |
| `mode` | `'absolute' \| 'relative'` | `'relative'` | `relative` — the value moves by the drag delta from the grab, so there is no jump. `absolute` — the value is read off the pointer's position on a fixed track centred on the mark; stateless, but it teleports unless the handle already sits at its value's place on that track. Both are direct-pick and coexist with a mark's other direct edits. |
Returns / emits: An **Edit** returning the datum with the channel field set from the pointer's position along the axis.
### `rotate(options)`
Angle edit — the pointer's angle about a pivot inverts back to the channel value (the scale's range is in degrees).
JSON keyword: `edit.rotate`
```ts
rotate({ pivot, fold, pick, relativeTo, channel }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `pivot` | `'plot' \| 'mark'` | `'plot'` | The centre the angle is measured about — the plot, or the hit mark. |
| `fold` | `boolean` | `true` | `true` folds into a direction-agnostic cone; `false` uses full-circle degrees (a gauge/dial). |
| `pick` | `'plane' \| 'direct'` | `'plane'` | How the gesture finds its row. A gesture on a row turns that row alone (`direct`, a needle handle); a `plane` drag with no row turns every row. |
| `relativeTo` | `string` | | Measure the absolute angular distance from another angular channel (the “open the cone” gesture). |
Returns / emits: An **Edit** with the channel field set from the pointer angle through the channel's scale.
### `cycle(options)`
Discrete edit — a click advances the channel to the next value in its domain. Needs a stable ordinal domain.
JSON keyword: `edit.cycle`
```ts
cycle({ channel }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channel` | `string` | `injected` | The ordinal channel to advance, usually `fill`. |
Returns / emits: An **Edit** (gesture `click`) returning the datum with the field stepped to the next domain entry.
### `toggle(options)`
Slot edit — `create` and `remove` folded into the one gesture a checkbox has. Click an empty slot to mint a datum there; click an occupied one to take it back.
JSON keyword: `edit.toggle`
```ts
toggle({ channels, pick, when, stage }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `string[]` | `injected` | The channels whose inverted values name a slot. One (`["x"]`) toggles an option on a scale; two (`["x","y"]`) toggle a cell of a grid. |
| `pick` | `'plane' \| 'probe'` | `'plane'` | `probe` previews the toggle on hover before the click commits it. |
Returns / emits: An **Edit** returning the full dataset. Pairs with `unique` for one pick per row and `count` for a cap.
### `set(options)`
Value edit — write a value straight into the channel’s field, whatever its type. Its input is the value itself, not a pixel, so it is the edit an [external control](https://elicitjs.github.io/editing/external-controls.md) drives.
JSON keyword: `edit.set`
```ts
set({ channel, channels, name, when, stage }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channel / channels` | `string / string[]` | `injected` | Which channel's field to write. |
| `name` | `string` | | Address it from outside with `chart.control(name).set(value)`. `accepts()` reports what the channel’s scale allows. |
Returns / emits: An **Edit** (gesture `commit`) returning the datum with that field set.
### `rank(options)`
Reorder by dragging along a rank axis. The pointer inverts to a rank slot, and the rows between the old slot and the new one **shift** by one place, so ranks stay unique. On a mark with `motion: true` the grabbed row follows the pointer and the others ease into place. See [Ranking](https://elicitjs.github.io/widgets.md#ranking).
JSON keyword: `edit.rank`
```ts
rank({ channel, channels, when, stage }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channel / channels` | `string / string[]` | `injected` | The rank axis — a band, point or quantitative scale. Place it on that channel: `y: { field: "rank", edit: rank() }`. |
Returns / emits: An **Edit** returning the full dataset, with the shifted rows rewritten.
### `custom(fn, options)`
An arbitrary edit. `fn` becomes the edit’s `apply`; the descriptor still declares which gesture fires it.
JSON keyword: `edit.custom`
```ts
custom((ctx) => datum | data[] | undefined, options?) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `fn` | `(ctx) => …` | | `datum` is `ctx.datum`, `event` is the raw DOM event (`ctx.event`), `ctx` is the full **EditContext** (see Editing overview). Return a new datum, a full dataset, or `undefined` to no-op — whatever fields you put on the datum become data. |
| `options.gesture` | `'drag'\|'click'\|…` | `'drag'` | Which gesture runs this edit. The engine matches `event.type` to this; `fn` itself does not choose the gesture. |
| `options.pick, when, …` | | | Any shared Edit fields (see the Editing overview). |
Returns / emits: An **Edit**. Default `gesture: "drag"`, `pick: "direct"`. Full `ctx` field list lives on the Editing overview under **EditContext**.
## Position — move
`move()` inverts the pointer on each positional channel it governs. On `x` and `y` together it is a 2D drag. On `y` alone it is a 1D bar drag.
By default, the mark's centre snaps to the pointer. On marks with area, such as `rect` or `sticker`, pass `mode: "relative"`: the mark moves by the drag distance and keeps its grab offset.
### Example: Move a point
edits: [move({ channels: ["x", "y"] })] — the pointer inverts onto both positional channels.
Try: **Drag** a dot anywhere.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: 20, y: 30 }, { x: 50, y: 62 }, { x: 78, y: 40 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#50AEB7", opacity: 0.85,
size: 9,
channels: {
x: { field: "x" },
y: { field: "y" },
},
// move() inverts the pointer on both positional channels — a 2D translate.
edits: [ move({ channels: ["x", "y"] }) ],
}),
],
});
mount(chart.dom());
```
## Keyboard modality — arrow key nudging
Press `Tab` to focus a mark, then press the **arrow keys** to nudge its value by 1% of the scale domain. `Shift`+arrow nudges by 10%.
A nudge runs through the same edit, clamping and constraints as a drag. It works for `move()`, `slide()` or `resize()` with a `direct`, `nearest` or `sweep` pick, for a `rotate()` about its own mark, for a stack's boundaries (`edit.stack.edge()`), and for the brush edits. Set `focusOutline: true` to show the browser's native focus ring.
### Example: Arrow keys move a point
A mark configured with move() accepts arrow keys automatically. Domain clamps hold for both modalities.
Try: **Tab** until a dot is focused, then use the **arrow keys** (or **Shift+arrow**) to nudge its position.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 16, right: 16, bottom: 32, left: 40 },
focusOutline: true,
schema: {
effort: { type: "quantitative", domain: [0, 100] },
value: { type: "quantitative", domain: [0, 100] },
},
data: [
{ effort: 25, value: 70 },
{ effort: 60, value: 45 },
],
constraints: [
clamp({ min: 0, max: 100, field: "effort" }),
clamp({ min: 0, max: 100, field: "value" }),
],
marks: [
point({
size: 8, fill: "#50AEB7",
channels: {
x: { field: "effort", edit: move() },
y: { field: "value", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Magnitude — resize (radial)
`resize()` inverts the pointer's distance from the mark's centre into the channel's value (`size: { edit: resize() }`). Stroke widths stay constant as the mark grows.
### Example: Drag outward to grow
resize() maps the gesture radius back to the size field.
Try: **Drag** a dot outward or inward to change its size.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 25, y: 50, mag: 3 }, { x: 55, y: 50, mag: 7 }, { x: 82, y: 50, mag: 11 },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
mag: { type: "quantitative", domain: [0, 14] },
},
constraints: [ clamp({ field: "mag", min: 1, max: 14 }) ],
marks: [
point({
fill: "#8A78C0",
channels: {
x: { field: "x" },
y: { field: "y" },
size: { field: "mag", edit: resize() },
},
}),
],
});
mount(chart.dom());
```
## Magnitude — slide (linear)
`slide()` is the linear counterpart to `resize`. It maps the pointer's travel along one **axis** onto the value's domain. Set `axis` to `'x'` or `'y'`, and `increase` to `'left'`, `'right'`, `'up'` or `'down'`.
The default `mode: "relative"` changes the value by the distance dragged since the press. `extent` sets the drag distance that covers the full domain.
### Example: Slide along an axis
size: { edit: slide({ axis: "x", increase: "left" }) } — dragging left increases the value.
Try: **Drag** the dot left to grow it, right to shrink it.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 50, y: 50, mag: 7 },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
mag: { type: "quantitative", domain: [0, 14] },
},
constraints: [ clamp({ field: "mag", min: 1, max: 14 }) ],
marks: [
point({
fill: "#50AEB7",
channels: {
x: { field: "x" },
y: { field: "y" },
size: { field: "mag", edit: slide({ axis: "x", increase: "left" }) },
},
}),
],
});
mount(chart.dom());
```
## Angle — rotate
`rotate()` inverts the pointer's angle about a pivot into degrees. Set `pivot: "mark"` to rotate about the mark's centre, or `pivot: "plot"` for the plot's centre. Set `fold: false` for a full 360° dial, or `fold: true` for a directional cone.
### Example: Rotate a box
Pointer angle inverts onto theta relative to the mark centre.
Try: **Drag** the box to spin it around its centre.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
theta: { type: "quantitative", domain: [0, 360] },
},
data: [ { x: 50, y: 50, theta: 20 } ],
marks: [
rect({
channels: {
x: { field: "x" },
y: { field: "y" },
width: { value: 110 },
height: { value: 70 },
fill: { value: "#50AEB7" },
stroke: { value: "#37919B" },
// rotate() inverts the pointer's angle about the mark centre onto theta.
angle: {
field: "theta",
scale: { range: [0, 360] },
edit: rotate({ pick: "direct", pivot: "mark", fold: false }),
},
},
}),
],
});
mount(chart.dom());
```
## Discrete — cycle, and combining gestures
`cycle()` steps an ordinal channel to the next value in its domain on a `click`. When several edits share a mark, `when` picks which one fires by modifier key. A drag is decided at the press: pressing or releasing Shift mid-drag does not switch edits.
### Example: Move · Shift-resize · click-cycle
when.noShift and when.shift split the drag; cycle() advances the fill category.
Try: **Drag** to move · **`Shift`+drag** to resize · **Click** to recolour.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 24, y: 70, mag: 5, team: "A" },
{ x: 55, y: 34, mag: 9, team: "B" },
{ x: 80, y: 60, mag: 12, team: "C" },
],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
mag: { type: "quantitative", domain: [0, 14] },
team: { type: "categorical", domain: ["A", "B", "C"] },
},
constraints: [ clamp({ field: "mag", min: 1, max: 14 }) ],
marks: [
point({
channels: {
x: { field: "x" },
y: { field: "y" },
size: { field: "mag" },
fill: { field: "team", edit: cycle() },
},
edits: [
move({ channels: ["x", "y"], when: when.noShift }), // plain drag = move
resize({ channel: "size", when: when.shift }), // shift-drag = resize
],
}),
],
});
mount(chart.dom());
```
## Custom transforms
`custom(fn)` sets `fn` as the edit's `apply`. It fires on a gesture (`drag` by default). `fn` receives an `EditContext` (`ctx.datum`, `ctx.event`, `ctx.pointer`, `ctx.scales`). Return a new datum, or an array of data; the fields you set are written back.
### Example: Invert y directly
ctx.pointer contains plot pixels; scales.y.invertValue maps them back to data.
Try: **Drag** a dot — y follows the pointer and the data panel reflects the updated field.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: 30, y: 30 }, { x: 70, y: 70 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#50AEB7",
size: 8,
channels: {
x: { field: "x" },
y: { field: "y" },
},
edits: [
// default gesture: "drag" — pass { gesture: "click" } to change it
custom((ctx) => ({
...ctx.datum,
y: ctx.scales.y.invertValue(ctx.pointer.y),
touched: true, // becomes data; omit if you only want to rewrite y
})),
],
}),
],
});
mount(chart.dom());
```
---
# Mark-specific & path edits
> Source: https://elicitjs.github.io/editing/sweep/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
Some edits work on a whole line or stack rather than one row. `edit.line.sweep()` repaints points across columns, and `edit.line.anchor()` builds connected paths. `edit.stack.edge()` and `edit.stack.cut()` reallocate slices in pies and stacked bars.
## API reference
### `edit.line.sweep(options)`
You-draw-it painting: a drag repaints the value of every point the pointer crosses. A `move` under the sweep driver, so it inverts the pointer through the same scale.
JSON keyword: `edit.line.sweep`
```ts
edit.line.sweep({ guide, when, stage }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `guide` | `boolean` | `true` | Draw tracking indicators along the swept column. |
| `mode` | `'absolute'` | `'absolute'` | A sweep paints the pointer's position, so 'relative' has no meaning here and warns. |
Returns / emits: An **Edit** scoped to `line`. It needs a mark that groups points into series.
### `edit.line.draw(options)`
Freehand path sampling, or a you-draw-it upsert on a line mark.
JSON keyword: `edit.line.draw`
```ts
edit.line.draw({ along, value, samples, minDist, series, threshold, into }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `along / value` | `'x' \| 'y'` | `'x' / 'y'` | The independent axis to draw along, and the dependent value axis. |
| `samples` | `number \| any[]` | `the scale's ticks` | Domain grid points the drawn value snaps to: a count, explicit positions, or a time interval. |
| `minDist` | `number` | `8` | How far the pointer must travel, in px, before another freehand point is sampled. |
| `series` | `string` | `the mark's series field` | The column that carries the series key. Override it when the drawn line groups by something other than the mark's own grouping channel. |
| `into` | `'nearest' \| 'new'` | `'nearest'` | Append to the nearest line, or start a fresh series. |
### `edit.line.anchor(options)`
Click to add anchor points to a line, one at a time.
JSON keyword: `edit.line.anchor`
```ts
edit.line.anchor({ into, series, gesture, when }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `into` | `'nearest' \| 'new'` | `'nearest'` | Add the point to the closest existing series, or start a new one. A click in empty space under 'nearest' also starts a fresh series. |
| `series` | `string` | `the mark's series field` | The column the new point's series key is written to. |
### `edit.line.newSeries(options)`
Seed a whole line at once — one anchor per sampled domain position, all at the pointer’s value. The draw-from-scratch primitive; pair it with `sweep` to shape the flat line it leaves.
JSON keyword: `edit.line.newSeries`
```ts
edit.line.newSeries({ along, value, samples, series }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `along / value` | `'x' \| 'y'` | `'x' / 'y'` | The axis the line runs along, and the axis it carries a value on. |
| `samples` | `number \| any[]` | `the scale's ticks` | Where the anchors go: a count, explicit domain positions, or a time interval. |
| `series` | `string` | `the mark's series field` | The column the new series key is written to. |
### `edit.line.removeSeries(options)`
Delete a whole line. Clicking any point on it reads that point’s series key and drops every row sharing it — the counterpart to `remove`, which drops one anchor.
JSON keyword: `edit.line.removeSeries`
```ts
edit.line.removeSeries({ series, gesture, when }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `series` | `string` | `the mark's series field` | The column that identifies the line. |
| `gesture / when` | `string / (ctx) => boolean` | `'click' / —` | Pair them with a `when` if another click edit shares the mark — removing one point against removing the whole line. |
### `edit.line.moveSeries(options)`
Drag a whole line. Press on a line, or inside a closed one, and every row of that series moves by the pointer’s travel. Each vertex stays inside its field’s domain. A press away from every line is left to the mark’s other edits, so it sits beside `move` on the handles and a `draw` with `when: when.far`.
JSON keyword: `edit.line.moveSeries`
```ts
edit.line.moveSeries({ channels, threshold, when }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `string[]` | `['x', 'y']` | The positional channels moved. |
| `threshold` | `number` | `6` | How near an open line counts as on it, in px. A closed line is also grabbed anywhere inside. |
### `edit.stack.cut(options)`
Click inside a stacked segment to divide it into two. The new segment's category goes in the mark's `stack` field, taken from its schema domain; a mark with no `stack` channel refuses the cut and logs a warning.
JSON keyword: `edit.stack.cut`
```ts
edit.stack.cut({ label, defaults, when }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `label` | `string` | | The placeholder name a new segment takes on an `open` domain, which has no next category to hand out. |
| `defaults` | `object` | `{}` | Extra fields to seed the new row with, over the schema's defaults. |
### `edit.stack.edge(options)`
Drag a boundary to move value between the two segments it separates. Only those two change — one grows by exactly what the other loses — so the group’s total is preserved by construction.
JSON keyword: `edit.stack.edge`
```ts
edit.stack.edge(options?) → Edit
```
Options:
| Option | Type | Description |
| --- | --- | --- |
| `—` | `EditOptions` | The universal edit options. The boundary it drags is resolved from the mark's own layout. |
### `edit.stack.merge(options)`
Double-click a boundary to fuse the two segments it separates back into one. The inverse of `cut`, preserving the same total: the lower row survives and takes the pair’s whole magnitude.
JSON keyword: `edit.stack.merge`
```ts
edit.stack.merge(options?) → Edit
```
Options:
| Option | Type | Description |
| --- | --- | --- |
| `—` | `EditOptions` | The universal edit options. It removes a row, not a category, so the domain is left alone and cutting brings that category back. |
## Line sweep (you-draw-it)
`edit.line.sweep()` sets each point's value as the pointer crosses its column. The `x` positions stay fixed and the curve follows the drag. It is shorthand for `move({ pick: "sweep", guide: true })` on a line, the form the first two examples use.
### Example: Sweep to shape a curve
edit: move({ pick: "sweep" }) on the y channel paints values as you drag horizontally.
Try: **Sweep** left-to-right across the chart.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 0, y: 50 }, { x: 1, y: 50 }, { x: 2, y: 50 }, { x: 3, y: 50 },
{ x: 4, y: 50 }, { x: 5, y: 50 }, { x: 6, y: 50 }, { x: 7, y: 50 },
],
schema: {
x: { type: "quantitative", domain: [0, 7] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
lineY({
stroke: "#50AEB7", strokeWidth: 3, curve: "catmullRom",
channels: {
x: { field: "x" },
y: { field: "y",
edit: move({ pick: "sweep", guide: true }) },
},
}),
],
});
mount(chart.dom());
```
## Series-scoped multi-line sweeps
When several lines share a plot, a sweep locks onto the nearest line when the drag starts and paints only that series. The other series stay as they are.
### Example: Two lines swept independently
The sweep locks onto the closest series at the start of the drag.
Try: **Sweep** over one line to reshape it; the other remains fixed.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ g: "plan", x: 0, y: 30 }, { g: "plan", x: 1, y: 45 }, { g: "plan", x: 2, y: 40 }, { g: "plan", x: 3, y: 60 },
{ g: "actual", x: 0, y: 70 }, { g: "actual", x: 1, y: 62 }, { g: "actual", x: 2, y: 75 }, { g: "actual", x: 3, y: 68 },
],
schema: {
x: { type: "quantitative", domain: [0, 3] },
y: { type: "quantitative", domain: [0, 100] },
g: { type: "categorical" }, // a group identifier, not an ordered scale
},
marks: [
lineY({
strokeWidth: 3, curve: "catmullRom",
channels: {
x: { field: "x" },
y: { field: "y",
edit: move({ pick: "sweep", guide: true }) },
stroke: { field: "g" },
},
}),
],
});
mount(chart.dom());
```
## Sweeping a band
Put `edit.line.sweep()` on both edges of an `areaY` band, `y1` and `y2`. A sweep locks onto the edge whose handle is nearest where the drag starts, and paints that edge alone. The other edge stays where it is. Dragging a single handle still moves just that point.
### Example: Sweep an uncertainty band
edit.line.sweep() on y1 and y2 — each sweep paints one edge; ordering keeps lo ≤ hi.
Try: **Sweep** starting near the upper edge to reshape it, then near the lower edge. Sweep the lower edge above the upper one and the upper edge is pushed along.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 0, lo: 40, hi: 60 }, { x: 1, lo: 38, hi: 62 }, { x: 2, lo: 35, hi: 66 },
{ x: 3, lo: 32, hi: 70 }, { x: 4, lo: 28, hi: 74 }, { x: 5, lo: 25, hi: 78 },
{ x: 6, lo: 22, hi: 82 }, { x: 7, lo: 20, hi: 85 },
],
schema: {
x: { type: "quantitative", domain: [0, 7] },
lo: { type: "quantitative", domain: [0, 100] },
hi: { type: "quantitative", domain: [0, 100] },
},
constraints: [ ordering({ field: ["lo", "hi"] }) ],
marks: [
areaY({
fill: "#2B5D87", curve: "catmullRom",
channels: {
x: { field: "x" },
// One sweep per edge: a drag paints the edge nearest where it starts.
y1: { field: "lo", edit: edit.line.sweep() },
y2: { field: "hi", edit: edit.line.sweep() },
},
}),
],
});
mount(chart.dom());
```
Place the sweep on the channel it paints. A mark-level `edits: [edit.line.sweep()]` names no channel, so it has nothing to write, and the chart warns. A sweep targets the mark's handles, so `handles: false` leaves it nothing to aim at (it warns too). Use `handles: 'hit'` to hide the handles and keep them targetable.
## Line anchors & freehand paths
`edit.line.anchor()` adds a point to the nearest line, or starts a new series in empty space. `edit.line.draw()` samples the pointer as you drag to record a freehand stroke.
### Example: Click to add an anchor
Clicking empty space appends the next anchor point to the line.
Try: **Drag** an existing point, or **click** empty space to append an anchor.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ step: 1, val: 20 },
{ step: 2, val: 50 },
{ step: 3, val: 35 },
],
schema: {
step: { type: "quantitative", domain: [1, 6] },
val: { type: "quantitative", domain: [0, 100] },
},
marks: [
line({
stroke: "#50AEB7",
channels: {
x: { field: "step" },
y: { field: "val", edit: move() },
},
edits: [
edit.line.anchor({ into: "nearest" }),
],
}),
],
});
mount(chart.dom());
```
## Arc slices & stacked bars
On a partition (a pie `arc`, a `donut` or a stacked `barY`), `edit.stack.edge()` and `edit.stack.cut()` change the proportions and keep the total constant.
`edit.stack.edge()` lets you drag the seams between segments. With `edit.stack.cut()`, click inside a segment to split it there. The new piece takes an unused category from the domain of the mark's `stack` field.
### Example: Cut a stack into categories
Click inside a 100% bar to cut it into categories; drag seams to adjust proportions.
Try: **Click** inside the bar to cut it into asset categories · **drag** seams to rebalance.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 16, right: 16, bottom: 28, left: 40 },
data: [
{ year: "2024", share: 100, asset: "Stocks" },
],
schema: {
year: { type: "categorical", domain: ["2024"] },
asset: { type: "categorical", domain: ["Stocks", "Bonds", "Cash", "Real Estate"] },
share: { type: "quantitative", domain: [0, 100] },
},
marks: [
barY({
channels: {
x: { field: "year" },
y: { field: "share" },
stack: { field: "asset" },
fill: { field: "asset" },
},
edits: [
edit.stack.cut(),
edit.stack.edge(),
],
}),
],
});
mount(chart.dom());
```
### Example: Pie slice boundary redistribution
edit.stack.edge() on a pie mark redistributes adjacent shares.
Try: **Drag** any slice seam to shift proportions between adjacent categories.
```javascript
const chart = Elicit({
width: 300, height: 260,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
data: [
{ cat: "A", val: 50 },
{ cat: "B", val: 30 },
{ cat: "C", val: 20 },
],
schema: {
cat: { type: "categorical" },
val: { type: "quantitative", domain: [0, 100] },
},
marks: [
arc({
outerRadius: 95,
edits: [edit.stack.edge()],
channels: {
theta: { field: "val" },
fill: { field: "cat" },
},
}),
],
});
mount(chart.dom());
```
---
# Handles & affordances
> Source: https://elicitjs.github.io/editing/handles/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
Handles are grab targets on continuous shapes: curves, envelopes, partition seams and interval spans. They can be visible grips, invisible hit targets (`handles: 'hit'`) or boundary seams. Every mark sizes, colours and hit-tests them the same way.
## API reference
### `handles`
The universal handle contract for continuous geometry — [line](https://elicitjs.github.io/marks/line.md), [area](https://elicitjs.github.io/marks/area.md), [curve](https://elicitjs.github.io/marks/curve.md), [arc](https://elicitjs.github.io/marks/arc.md), [trend](https://elicitjs.github.io/marks/trend.md), [needle](https://elicitjs.github.io/marks/needle.md), and a span. Every mark that draws a grip spells these the same way.
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `handles` | `boolean \| "hit"` | `true with an edit` | Unset, a handle draws where an edit reaches the row. true always draws it, as ink on a mark with no edit. "hit" keeps the enlarged grab target without drawing a circle. false is neither drawn nor grabbable, so a sweep or nearest pick on the mark has nothing to target (the chart warns). |
| `handleSize` | `number` | `5` | Radius in px of the grip and its pointer hitbox. |
| `handleColor` | `string` | `series colour · theme.handle` | Grip fill. On line and area a grip is filled with its row's resolved stroke, so each series' grips match its line; trend uses its own ink, and other marks use theme.handle. The ring is theme.handleStroke. Setting handleColor overrides both fills. |
Returns / emits: A grip is drawn only where an edit can use it. A mark with no edit on the channel draws none, whatever `handles` says.
### `moveSpan(options)`
Translate a two-endpoint span — both endpoints move together, so its width is preserved.
JSON keyword: `edit.moveSpan`
```ts
moveSpan({ channels, when, stage }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `[string, string]` | `injected` | The span pair to govern, e.g. ["x1", "x2"] or ["y1", "y2"]. |
### `brushSpan(options)`
The Gantt-bar interaction. Grabbing near one endpoint resizes that edge alone; grabbing the body translates both. The zone is resolved once, at the start of the drag.
JSON keyword: `edit.brushSpan`
```ts
brushSpan({ channels, edgeInset, guide, when }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `[string, string]` | `injected` | The span pair to govern, e.g. ["x1", "x2"] or ["y1", "y2"]. |
| `edgeInset` | `number` | `8` | Catchment width in px at each end: inside it the gesture resizes that edge, outside it moves the whole span. |
| `pick` | | `'brush'` | Fixed. brushSpan reads a zone only the brush driver sets, so it cannot be repointed at another pick. |
Returns / emits: An **Edit**. Dragging one edge past the other is allowed mid-gesture; the pair is put back in order once, when you let go.
### `brushRect(options)`
The 2-D counterpart: edges, corners and body of a rect, each live or not as you choose.
JSON keyword: `edit.brushRect`
```ts
brushRect({ resize, move, edgeInset, when }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `resize` | `'both' \| 'x' \| 'y' \| 'none'` | `'both'` | Which axes' edges and corners are live. 'none' leaves a pure 2-D move. |
| `move` | `boolean` | `true` | Whether a body drag translates the whole rect. false leaves a resize-only brush. |
| `edgeInset` | `number` | `8` | Catchment width in px along each edge. |
| `channels` | `string[]` | `['x1','x2','y1','y2']` | The two endpoint pairs it governs. |
Returns / emits: An **Edit**. A disabled zone degrades to the body, so `resize: 'x'` behaves like a per-axis `brushSpan`.
### `edit.stack.edge(options)`
Drag an interior boundary to move value between the two segments it separates. The group total is preserved by construction.
JSON keyword: `edit.stack.edge`
```ts
edit.stack.edge(options?) → Edit
```
Options:
| Option | Type | Description |
| --- | --- | --- |
| `—` | `EditOptions` | The universal edit options. You grab the boundary handle itself, so it reads no threshold and draws no guide. |
## Visible grips vs. invisible hit targets
A line or area has no separate node per point to grab. Handles supply one.
Unset, a mark draws its handles where an edit reaches the row. `handles: true` draws a circular grip on each vertex, as ink when nothing edits the mark. `handles: 'hit'` draws no circles but keeps the enlarged hit targets along the path, so the chart stays uncluttered and still easy to drag. `handles: false` draws no handles, so an edit that targets them, such as a sweep or a nearest pick, has nothing to grab, and the chart warns.
On a `line` or `area`, a grip is filled with the row's resolved `fill` when the mark encodes one, otherwise its `stroke`. It is ringed with the theme's `handleStroke`. On a multi-series chart, each line's grips match it. `handleColor` sets one fill for every grip.
### Example: Invisible hit targets (handles: 'hit')
handles: 'hit' leaves no visible dots, but lets you drag along the top edge.
Try: **Drag** along the top edge of the area to reshape the distribution.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [
{ t: 1, n: 20 }, { t: 2, n: 55 }, { t: 3, n: 35 },
{ t: 4, n: 70 }, { t: 5, n: 45 },
],
schema: {
t: { type: "quantitative", domain: [1, 5] },
n: { type: "quantitative", domain: [0, 100] },
},
marks: [
areaY({
handles: "hit",
fill: "#50AEB7",
opacity: 0.7,
channels: {
x: { field: "t" },
y: { field: "n", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Boundary seams (arcs & stacked bars)
On a partition, handles sit at the **interior boundaries** between adjacent slices. An *n*-slice pie or stacked bar has *n* − 1 boundary handles.
`edit.stack.edge()` lets you drag a boundary to move value between the two slices beside it. The total stays constant.
### Example: Drag slice boundaries
Each handle pair-shifts adjacent shares while preserving the 100% total.
Try: **Drag** any slice boundary to reallocate share between categories.
```javascript
const chart = Elicit({
width: 300, height: 260,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
data: [
{ source: "Solar", share: 45 },
{ source: "Wind", share: 35 },
{ source: "Hydro", share: 20 },
],
schema: {
source: { type: "categorical" },
share: { type: "quantitative", domain: [0, 100] },
},
marks: [
arc({
outerRadius: 95,
edits: [edit.stack.edge()],
channels: {
theta: { field: "share" },
fill: { field: "source" },
},
}),
],
});
mount(chart.dom());
```
## Span endpoints & body brushes
On a mark with a range (`x1`/`x2` or `y1`/`y2`), handles sit at the span's endpoints.
`brushSpan()` gives one mark two drags. Grab near an end to resize that bound, or grab the body to move the whole span. Drag the lower end past the upper one and the fields swap on release, so the order holds without a jump.
### Example: Resize edges or drag span body
Grab within edgeInset pixels to resize an endpoint; grab the centre to slide the task.
Try: **Drag** an end handle to resize · **drag** the bar body to move the whole range.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 14, right: 16, bottom: 26, left: 60 },
data: [
{ task: "Research", start: 2, end: 6 },
{ task: "Design", start: 4, end: 9 },
{ task: "Build", start: 7, end: 12 },
],
schema: {
task: { type: "categorical", domain: ["Research", "Design", "Build"] },
start: { type: "quantitative", domain: [0, 14] },
end: { type: "quantitative", domain: [0, 14] },
},
marks: [
barX({
fill: "#50AEB7",
channels: {
y: { field: "task" },
x1: { field: "start" },
x2: { field: "end" },
},
edits: [
brushSpan({
channels: ["x1", "x2"],
threshold: 30,
edgeInset: 12,
guide: true,
}),
],
}),
],
});
mount(chart.dom());
```
---
# Adding, removing & locking rows
> Source: https://elicitjs.github.io/editing/existence/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
These edits add and remove rows. `create()` inverts a click into a new row, and `remove()` deletes the clicked row. `lock` on the spec makes **given** rows read-only: the record so far, points already measured, last quarter’s actuals. No gesture can change or delete a locked row, and rows an edit *adds* stay editable. Locked rows are still part of `getData()`; to leave given rows out of the answer, mark them as [`context`](#context).
## API reference
### `create(options)`
A plane gesture that mints a datum — inverts pointer pixels through positional channels, populating defaults for the rest.
JSON keyword: `edit.create`
```ts
create({ channels, defaults, gesture }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `string[]` | `['x','y','xOffset','yOffset']` | Positional channels to place from the pointer. The mark's own channels decide which of them apply. |
| `defaults` | `object` | `{}` | Seed values for non-positional fields on newly minted rows. |
| `gesture` | `'click' \| 'dblclick'` | `'click'` | The plane gesture that triggers creation. |
### `remove(options)`
Deletes the targeted datum from the dataset.
JSON keyword: `edit.remove`
```ts
remove({ pick, threshold, when, gesture }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `when` | `(ctx) => boolean` | | Arbitration predicate (e.g. when.alt so Alt-click deletes while click recolours). |
| `gesture` | `string` | `'click'` | The gesture that removes the row. |
### `lock`
Which rows of the dataset are read-only. A lock is a property of the **data** — not of a mark or an edit — so it lives on the dataset spec beside `data` and `schema`, and holds for every edit from every mark in every chart.
JSON keyword: `spec`
```ts
lock: "seed" | true | ((datum, index) => boolean)
```
Options:
| Option | Type | Description |
| --- | --- | --- |
| `"seed" / true` | `string \| boolean` | The rows the chart was **seeded** with (its `data`) are fixed; anything an edit creates is free. `setData` re-seeds the chart, so it also re-takes the lock. |
| `(datum, index) => boolean` | `function` | Lock rows by what they **are** — `d => d.kind === "actual"`, `d => d.year <= 1990`. Re-evaluated every render, so a row can be locked by a field an edit writes. |
Returns / emits: Two things follow, and both are automatic. **Data:** a dataset invariant runs on every commit, *last*, so a lock outranks every other repair — a proposal that touched a locked row keeps its changes to the free rows and snaps the locked ones back (deleting one is rejected outright). **Pointer:** a locked row’s marks are not grabbable, show no editable cursor, and are skipped by proximity picking — so `nearest` / `sweep` / `draw` never even target one.
### `context`
Marks seeded rows as reference: drawn and read-only, and left out of getData(), onChange, and the selection and control indices.
JSON keyword: `spec`
```ts
context: true | ((datum, index, table) => boolean)
```
Options:
| Option | Type | Description |
| --- | --- | --- |
| `context: true` | `true` | Every row in data is context; rows you add are your answer. |
| `context: (d) => boolean` | `Function` | The seeded rows the predicate accepts are context. It runs once, over the rows in data. |
## What can — and cannot — be created
Creation writes dataset **rows**, so it goes on a data mark with an invertible positional axis. Elements and guides write no rows. `trend` draws one line from a row's `intercept` and `slope`, so it has no position to invert.
| Mark | Create? | How |
| --- | --- | --- |
| `point` · `shape` | ✓ | Invert pointer through x and y |
| `tick` · `bar` | ✓ | One axis inverts to a band slot, the other to value |
| `rule` | ✓ | Invert pointer on its value axis |
| `rect` | ✓ | Seed default extents (`x1`/`x2` or `y1`/`y2`) |
| `composite` (glyph) | ✓ | Create on one component mark; row renders across all |
| `line` · `path` | ✓ | Series-aware anchor and draw edits |
| Elements: `axisX` · `gridY` · `legendColor` | ✗ | Edit the scale's domain, not rows |
| Guides: `guides.*` | ✗ | Write nothing |
| `trend` | ✗ | A parametric line drawn from one row; no position to invert |
## Create — click to add
`create()` inverts a click on empty space into a new row and appends it. A constraint such as `count({ max })` caps the number of rows.
Declare a creator on one mark only. Each mark on the table that carries one appends a row on the same click.
### Example: Click to add a point
create({ defaults }) mints a datum at the pointer; count({ max: 8 }) caps the dataset.
Try: **Click** empty space to add a point · **drag** to move it.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: 30, y: 30, group: "a" }],
schema: {
// Declared so create() mints it on a new row — an undeclared column would be
// missing from every point the click adds.
group: { type: "categorical" },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
constraints: [ count({ max: 8 }) ], // dataset invariant: at most 8
marks: [
point({
fill: "#1B3F60",
size: 8,
channels: {
x: { field: "x", edit: move() },
y: { field: "y", edit: move() },
},
edits: [ create({ defaults: { group: "a" } }) ],
}),
],
});
mount(chart.dom());
```
## Create, move & remove arbitration
`remove()` fires on a plain click. When several edits share a mark, split their gestures with `when`: for example, double-click to add, drag to move and `Alt`+click to remove.
### Example: Create, move, and remove on one mark
Double-click adds, Alt-click deletes, and drag moves.
Try: **Double-click** to add · **`Alt`+click** to delete · **Drag** to move.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: 30, y: 40 }, { x: 65, y: 65 }],
schema: {
s: { type: "categorical" }, // the series key; declared so create() mints it
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#1B3F60",
size: 8,
channels: {
x: { field: "x" },
y: { field: "y" },
},
edits: [
move({ channels: ["x", "y"] }),
create({ gesture: "dblclick" }),
remove({ when: when.alt }),
],
}),
],
});
mount(chart.dom());
```
### Example: Arbitration between click actions
when.noAlt cycles color; when.alt removes the row.
Try: **Click** a dot to recolour · **`Alt`+click** to delete.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: 25, y: 40, group: "alpha" },
{ x: 55, y: 65, group: "beta" },
{ x: 80, y: 30, group: "gamma" },
],
schema: {
s: { type: "categorical" }, // the series key; declared so create() mints it
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
group: { type: "categorical", domain: ["alpha", "beta", "gamma"] },
},
marks: [
point({
size: 10,
channels: {
x: { field: "x", edit: move() },
y: { field: "y", edit: move() },
fill: { field: "group", edit: cycle({ when: when.noAlt }) },
},
edits: [ remove({ when: when.alt }) ],
}),
],
});
mount(chart.dom());
```
## Locked seed, free additions
`lock: "seed"` locks exactly the rows you passed as `data`. Rows a `create` mints afterwards are ordinary, editable data. One dataset can hold the observed points and your answer.
### Example: Scatter: observed points + yours
The five grey points are the seed — try to drag one and nothing happens. Click to add your own, and those you can move and delete.
Try: **Click** empty space to add a point · **drag** one of yours · **Alt-click** one of yours to remove it. The grey points never move.
```javascript
const chart = Elicit({
width: 400, height: 300,
margins: { top: 16, right: 16, bottom: 32, left: 40 },
schema: {
x: { type: "quantitative", domain: [0, 10] },
y: { type: "quantitative", domain: [0, 10] },
// A schema `default` populates a field on a row an edit MINTS — so every
// point you add is tagged "yours" without create() saying a word about it.
source: { type: "categorical", domain: ["observed", "yours"],
default: "yours" },
},
data: [
{ x: 1.2, y: 2.4, source: "observed" },
{ x: 2.6, y: 3.1, source: "observed" },
{ x: 3.4, y: 4.6, source: "observed" },
{ x: 4.1, y: 4.2, source: "observed" },
{ x: 5.3, y: 6.0, source: "observed" },
],
// The observed rows are given, not elicited.
lock: "seed",
axes: { x: { grid: true }, y: { grid: true } },
marks: [
point({
size: 7,
channels: {
x: { field: "x" },
y: { field: "y" },
fill: { field: "source",
scale: { range: ["#94A5B3", "#50AEB7"] } },
},
edits: [
create({ when: when.noAlt }), // click empty space -> add
move({ channels: ["x", "y"] }), // drag one of yours in 2D
remove({ when: when.alt }), // alt-click -> gone
],
}),
],
});
mount(chart.dom());
```
## Locking rows by what they are
Pass a predicate to lock rows by their fields. Here the quarters that already happened are actuals, and the rest are your forecast. Both live in one dataset and one bar mark.
### Example: Actuals + forecast
lock: (d) => d.kind === "actual". The two grey bars are reported; only the forecast bars take a drag.
Try: **Drag** Q3 / Q4 (blue). Q1 and Q2 are reported — they don’t budge.
```javascript
const chart = Elicit({
width: 400, height: 260,
margins: { top: 16, right: 16, bottom: 30, left: 44 },
schema: {
q: { type: "categorical", domain: ["Q1", "Q2", "Q3", "Q4"] },
n: { type: "quantitative", domain: [0, 100] },
kind: { type: "categorical", domain: ["actual", "forecast"] },
},
data: [
{ q: "Q1", n: 42, kind: "actual" },
{ q: "Q2", n: 55, kind: "actual" },
{ q: "Q3", n: 50, kind: "forecast" },
{ q: "Q4", n: 50, kind: "forecast" },
],
// The lock is a property of the row, so it reads straight off the data.
lock: (d) => d.kind === "actual",
marks: [
barY({
channels: {
x: { field: "q" },
y: { field: "n", edit: move({ guide: true }) },
fill: { field: "kind",
scale: { range: ["#94A5B3", "#50AEB7"] } },
},
}),
],
});
mount(chart.dom());
```
## Context rows
A locked row is still part of your answer: `getData()` returns it. When the given rows are only for reference, mark them as **context** instead. `context: true` makes every row in `data` context. A predicate picks the rows it accepts (`context: (d) => d.year <= 2020`).
Context rows belong to the same table, so they share its columns and schema. Every mark over the table draws them, and they are read-only, like locked rows. `getData()` and `onChange` leave them out, so a one-table chart still reports a bare array of your answers. The selection API and `control()` count reported rows only, so `getData()[i]` and `select(i)` name the same row.
The predicate runs once, over the rows in `data`. A row you add or drag later stays part of your answer, even when the predicate would accept it. `setData(rows)` replaces your answers and keeps the context rows. Constraints see context rows too, because they are rows of the table. `count` leaves them out: its `max` is the number of answer rows.
When the reference rows carry other columns (an observed `price` beside your `lo` and `hi`), declare all of them in the schema. Each row fills its own columns, and a mark skips a row whose value is missing. Reference data unrelated to the answer is a [guide](https://elicitjs.github.io/guides.md).
### Example: The record as context, the forecast as your answer
2010–2020 is context: drawn and read-only. getData() returns only the four forecast years.
Try: **Drag** a forecast point (2022–2030). The record does not move.
```javascript
const chart = Elicit({
width: 440, height: 260,
margins: { top: 16, right: 16, bottom: 32, left: 40 },
axes: { x: { tickFormat: "d" } },
schema: {
year: { type: "quantitative", domain: [2010, 2030] },
rate: { type: "quantitative", domain: [0, 10] },
},
// 2010–2020 is the record; 2022–2030 is your forecast.
data: [
{ year: 2010, rate: 4.2 }, { year: 2012, rate: 4.8 }, { year: 2014, rate: 5.1 },
{ year: 2016, rate: 4.6 }, { year: 2018, rate: 5.5 }, { year: 2020, rate: 6.1 },
{ year: 2022, rate: 6.1 }, { year: 2025, rate: 6.1 }, { year: 2028, rate: 6.1 },
{ year: 2030, rate: 6.1 },
],
// The record is context: drawn and read-only, but not part of your answer.
context: (d) => d.year <= 2020,
guides: [guides.region({ x: [2010, 2020], fill: "#94A5B3", opacity: 0.12 })],
marks: [
lineY({
stroke: "#50AEB7", strokeWidth: 2,
channels: {
x: { field: "year" },
y: { field: "rate", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## You draw it
This recreates the New York Times’ “You Draw It” (2017): the record runs to 1990 and you draw the rest. Both halves use the same dataset, line mark and `y` field; only the lock differs. Proximity picks skip locked rows, so a drag beside the record starts drawing instead of grabbing it.
`edit.line.draw({ stage: 0 })` draws the missing years in stage 0. `chart.nextStage()` moves to stage 1, which retires the edit and shows the answer key.
### Example: Draw the line for the missing years
edit.line.draw({ samples: years }) paints one point per year as the pointer crosses its column. Drag back over the record and it will not budge — the lock repairs those rows and keeps the rest of the stroke.
Try: **Drag** left-to-right across the empty half to draw 1991–2016, then **drag again** to refine it. Then press **Show me how I did**.
```javascript
// U.S. motor-vehicle deaths per year (NHTSA/FARS, rounded).
// 1968-1990 is the record; the rest is what you believe happened.
const record = [
[1968, 52725], [1969, 53543], [1970, 52627], [1971, 52542],
[1972, 54589], [1973, 54052], [1974, 45196], [1975, 44525],
[1976, 45523], [1977, 47878], [1978, 50331], [1979, 51093],
[1980, 51091], [1981, 49301], [1982, 43945], [1983, 42589],
[1984, 44257], [1985, 43825], [1986, 46087], [1987, 46390],
[1988, 47087], [1989, 45582], [1990, 44599],
].map(([year, deaths]) => ({ year, deaths }));
const truth = [
[1991, 41508], [1992, 39250], [1993, 40150], [1994, 40716],
[1995, 41817], [1996, 42065], [1997, 42013], [1998, 41501],
[1999, 41717], [2000, 41945], [2001, 42196], [2002, 43005],
[2003, 42884], [2004, 42836], [2005, 43510], [2006, 42708],
[2007, 41259], [2008, 37423], [2009, 33883], [2010, 32999],
[2011, 32479], [2012, 33782], [2013, 32893], [2014, 32744],
[2015, 35485], [2016, 37806],
].map(([year, deaths]) => ({ year, deaths }));
const chart = Elicit({
width: 560, height: 340,
margins: { top: 20, right: 24, bottom: 32, left: 56 },
schema: {
year: { type: "quantitative", domain: [1968, 2016] },
deaths: { type: "quantitative", domain: [0, 60000] },
},
data: record,
lock: "seed", // the record is fact: undraggable, unsweepable, unpickable
axes: {
x: { tickFormat: "d", grid: true },
y: { tickFormat: "~s", grid: true },
},
// Stage 0 = you draw. Stage 1 = the answer is on screen, drawing is over.
stageLabels: ["draw", "revealed"],
guides: [
// The years you were given (the NYT's grey box).
guides.region({ x: [1968, 1990], fill: "#94A5B3", opacity: 0.12 }),
// The endpoint readouts.
guides.custom(({ data, scales }) => [1968, 1990]
.map((y) => data.find((d) => d.year === y))
.filter(Boolean)
.map((d) => ({
type: "text", text: d3.format(",")(d.deaths),
x: scales.x.encode(d.year), y: scales.y.encode(d.deaths) - 12,
fontSize: 12, textAnchor: "middle", fill: "#20555A",
}))),
// The answer key. Not data — it is not elicited, so it is a guide, and it
// stays out of getData(). It appears when the chart advances to stage 1.
guides.custom(({ scales, stage }) => stage < 1 ? [] : [{
type: "path", fill: "none", stroke: "#F2B94B", strokeWidth: 2.5,
points: truth.map((d) => [scales.x.encode(d.year),
scales.y.encode(d.deaths)]),
}]),
],
marks: [
lineY({
stroke: "#50AEB7", strokeWidth: 3, curve: "catmullRom", handleSize: 3,
channels: {
x: { field: "year" },
y: { field: "deaths" },
},
// One drag per year column. `stage: 0` retires the edit once you've asked
// to see the answer.
edits: [ edit.line.draw({ samples: d3.range(1991, 2017), stage: 0 }) ],
}),
],
});
mount(chart.dom());
const btn = mount(document.createElement("button"));
btn.textContent = "Show me how I did.";
btn.onclick = () => chart.nextStage();
```
---
# Selection
> Source: https://elicitjs.github.io/editing/selection/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
The selection is the set of rows currently picked. It is **interface state**, kept beside the data. `edit.select()` makes a mark selectable, and selected rows get the `selected` effect. An edit that needs a row to write to, such as a legend picker or an external control, reads the selection. The answer data is unchanged.
## API reference
### `edit.select`
Makes a mark selectable. Selection is transient **pipeline state** — the chart remembers which rows are picked, and nothing is written to the data. That is the point: it replaces a `selected` column, so no `change` fires, nothing lands in undo, and the elicited dataset stays clean.
JSON keyword: `edit.select`
```ts
edit.select({ multi, exclusive, toggle }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `multi` | `boolean` | `false` | Shift- or meta-click adds to the selection; a plain click still replaces it. Shift-clicking a selected row removes it. Turning this on changes nothing about the gesture you already had. |
| `exclusive` | `boolean` | `true` | Selecting a row clears the rest. false makes every click additive, with no modifier — the flat override for a chart that is always multi. |
| `toggle` | `boolean` | `true` | Clicking an already-selected row deselects it. false never deselects. |
### `Selection API`
Selection has its own small API beside `getData`/`setData`, and its own `select` event. Every route — a mark click, an external control, the keyboard — goes through the same commit, so the selection is always in one shape. A row of the primary table is its index; a row of another table is `{ table, index }`. Indices count the rows `getData()` reports.
No JSON form: this is called in JavaScript.
```ts
chart.getSelection() → row | null · chart.getSelectionAll() → row[]
chart.select(row | row[] | null) → boolean // row: index | { table, index }
chart.toggleSelection(row) → boolean · chart.selectAll() → boolean
chart.selectWhere(field, value, { all }) → boolean
chart.clearSelection() → boolean · chart.on('select', (first, all) => …)
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `getSelection / getSelectionAll` | `() => row \| null / row[]` | | The primary selection, and every selected row. getSelectionAll lists the primary table's indices in ascending order, then each other table's rows as { table, index }. getSelection is the first of them: the lowest selected index. It stays scalar when several are selected. A row that was removed drops out. |
| `select` | `(row \| row[] \| null)` | | Replace the selection. An array selects exactly those rows in one commit; null, an empty array, or an out-of-range index clears. A table the dataset lacks warns. |
| `toggleSelection / selectAll` | `(row) / ()` | | Add or remove one row, leaving the rest alone (the external counterpart of a shift-click); or take every row. |
| `selectWhere` | `(field \| predicate, value?, { all }?)` | `all: false` | Select by category or predicate. The default takes the first match; { all: true } takes every one, which is what selecting a category usually means. |
| `clearSelection` | `()` | | Empty the selection. The same commit path, so the select event fires. |
| `on('select')` | `(first, all) => void` | | Fires whenever the selection moves, with getSelection() and getSelectionAll(). No data changed, so this is not a change event. |
## State, not data
The selection stays out of `getData()`, fires no `change` and takes no undo step. It survives edits and resets when you call `setData` or advance a stage. It reports through its own `select` event.
`edit.select()` is a direct-pick click. A plain click selects one row and clears the rest. Clicking the selected row again deselects it.
### Example: Click a bar to select it
The selected bar takes the highlight outline. getData() gains no column.
Try: **Click** a bar to select it, **click** it again to deselect · **drag** the top to change its value.
```javascript
const chart = Elicit({
width: 380, height: 210,
margins: { top: 20, right: 16, bottom: 30, left: 40 },
data: [
{ name: "A", value: 12 },
{ name: "B", value: 8 },
{ name: "C", value: 15 },
{ name: "D", value: 6 },
],
schema: {
name: { type: "categorical", domain: ["A", "B", "C", "D"] },
value: { type: "quantitative", domain: [0, 16] },
},
marks: [
barY({
fill: "#50AEB7",
channels: { x: { field: "name" }, y: { field: "value", edit: move() } },
edits: [ edit.select() ]
}),
],
});
mount(chart.dom());
```
## Seeing the selection
Selected rows get the `selected` [effect](https://elicitjs.github.io/effects.md). By default it traces each mark's edge in a deep shade of its own colour. It applies to every mark over that row, so selecting a bar also outlines its label. Restyle it on the spec:
```js
effects: { selected: { outline: { color: "#2563eb", width: 3 } } }
```
`selected` outranks `hovered`, and `grabbed` outranks `selected`, so a row you are dragging shows as grabbed.
## Selecting several rows
`edit.select({ multi: true })` makes shift-click (or meta-click) add to the selection. Shift-clicking a selected row removes it. A plain click still replaces the whole selection. Use `exclusive: false` to make every click add, with no modifier.
An edit that writes the selected row writes **all** selected rows, so one swatch click recategorises the whole selection.
### Example: Shift-click to build a selection
One swatch click sets the group on every selected bar.
Try: **Click** a bar, **shift-click** another, then **click** a legend swatch.
```javascript
const chart = Elicit({
width: 380, height: 210,
margins: { top: 20, right: 16, bottom: 30, left: 40 },
data: [
{ name: "A", value: 12, group: "North" },
{ name: "B", value: 8, group: "South" },
{ name: "C", value: 15, group: "East" },
{ name: "D", value: 6, group: "West" },
],
schema: {
name: { type: "categorical", domain: ["A", "B", "C", "D"] },
group: { type: "categorical", domain: ["North", "South", "East", "West"] },
value: { type: "quantitative", domain: [0, 16] },
},
marks: [
barY({
channels: {
x: { field: "name" },
y: { field: "value" },
fill: { field: "group", edit: edit.legend.category() },
},
edits: [ edit.select({ multi: true }) ]
}),
],
});
mount(chart.dom());
```
## Driving it from outside
An external call and a click set the selection the same way. The selection belongs to the dataset, so [charts that share a dataset](https://elicitjs.github.io/dataset.md#history) show one selection. See [External controls](https://elicitjs.github.io/editing/external-controls.md#selection) for the related API.
```js
chart.select(2); // replace with row 2
chart.select([0, 2]); // replace with rows 0 and 2
chart.toggleSelection(3); // add or remove row 3
chart.selectAll();
chart.selectWhere("group", "North", { all: true }); // a whole category
chart.clearSelection();
chart.getSelection(); // 0 (the lowest, or null)
chart.getSelectionAll(); // [0, 2]
chart.on("select", (first, all) => …);
```
A row of the primary table is its index. On a network or hierarchy, a row of another table is `{ table, index }`: `chart.select({ table: "links", index: 1 })`, and `getSelectionAll()` returns `[0, 2, { table: "links", index: 1 }]`.
`selectWhere` takes the first match by default. Pass `{ all: true }` for every row of a category, which is usually what a control that names a value wants.
## Edits that read the selection
A gesture that carries no row of its own reads the selection. A [legend](https://elicitjs.github.io/editing/legend.md) picker is the main case: a swatch names a *value*, so its `row` defaults to the selection.
The swatch that matches the selection is ringed. With nothing selected and more than one row, a picker has no target and no ring. In a one-row table, the picker writes that row. If nothing in the chart can select, a warning says the picker has no target.
---
# Probe & stages
> Source: https://elicitjs.github.io/editing/probe/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`pick: "probe"` previews an edit before it commits. Moving the pointer draws an uncommitted ghost, and `getData()` reports only the last settled answer. Stages split a question into steps: first do X, then do Y. Give an edit a numeric `stage` and it is active only in that stage; an edit with no `stage` is always active. Move between stages with `nextStage()`, `setStage(n)` and `getStage()`, and listen with `on("stage", cb)`. A staged probe edit advances to the next stage when it commits.
## API reference
### `anyEdit({ pick: "probe", stage, advance })`
Not a new edit — a **pick** you give an existing one. It runs that edit twice. On `hover` or `drag` the proposal is parked as a preview and drawn as an inert **ghost**; on `click` or `dragend` the same proposal is committed. The ghost is therefore exactly what a commit writes. Both gestures settle, so a knob can be dragged as well as clicked.
JSON keyword: `edit`
```ts
rotate({ pick: "probe", stage: 0 }) // line follows the pointer; click sets it
move({ pick: "probe", advance: false }) // a knob that tracks then settles
create({ pick: "probe", advance: false }) // a tentative dot, made real on click
toggle({ pick: "probe", channels: ["x","y"] }) // preview a cell being (un)picked
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `stage` | `number` | `null` | Active only in this stage. A click settling it advances the chart to the next stage, freezing the field. |
| `advance` | `boolean` | `true` | Set `false` so a click commits without advancing — the edit stays live for repeated answers. |
Returns / emits: Previews never reach `onChange`, `getData` or the belief store; leaving the plot discards the proposal. Constraints run on the preview too, so a rejected value never even previews.
### `edit({ stage }) · container.setStage / nextStage / getStage`
Add `stage` to any edit factory. The engine filters edits by the current stage in dispatch, cursor, plane-on-top, and guides — one gate everywhere.
No JSON form: this is called in JavaScript.
```ts
move({ stage: 1 }) // active only in stage 1
const chart = Elicit({ stage: 0, ... });
chart.getStage() → number
chart.setStage(n) // set, emit "stage", re-render
chart.nextStage() // setStage(current + 1), stopping at done: one past the last stage an edit declares
chart.on("stage", (n) => …) // subscribe; returns an unsubscribe fn
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `edit.stage` | `number` | `null` | The stage this edit is active in. Unset, it is active in every stage. |
| `spec.stage` | `number` | `0` | Which stage the chart starts on. |
| `spec.stageLabels` | `string[]` | `[]` | A caption per stage, read back with getStageLabel(). |
| `edit.advance` | `boolean` | `true` | Whether a settled [probe](#preview) click moves the chart on. Set `false` to answer repeatedly within one stage. |
Returns / emits: `setStage` and `nextStage` emit `stage` and re-render. The stage gates dispatch, the cursor, plane pick order, and guides, so an edit outside the current stage is inert everywhere at once.
## Ghost proposals
`pick: "probe"` splits an edit into preview and commit. As the pointer moves, the marks draw an inert **ghost** of what a commit would produce.
The proposal applies to the dataset, so every mark reading those rows shows the ghost. `getData()` and `onChange` stay unchanged until you commit.
### Example: Probe a single value
move({ pick: 'probe' }) displays a ghost knob that settles on click or drag release.
Try: Move across the track and click — or grab the knob and drag.
```javascript
const chart = Elicit({
width: 380, height: 130,
margins: { top: 20, right: 24, bottom: 34, left: 24 },
axes: { x: {}, y: false },
data: [{ v: 20 }],
schema: {
v: { type: "quantitative", domain: [0, 100] },
},
constraints: [ clamp({ min: 0, max: 100, field: "v" }) ],
marks: [
point({
id: "belief",
size: 9, fill: "#50AEB7",
channels: { x: { field: "v",
edit: move({ pick: "probe", advance: false }) },},
}),
],
});
mount(chart.dom());
const out = document.createElement("div");
out.style.cssText = "font:12px ui-monospace,monospace;color:#6F8294";
const show = () => { out.textContent = "committed: " + chart.getData()[0].v.toFixed(0); };
chart.on("change", show); show();
mount(out);
```
## Two ways to commit
A probe edit commits on either gesture:
1. **Move, then click**: move the pointer without pressing to place the ghost, then click to settle it.
2. **Grab and drag**: press on the mark, drag to the value, and release.
## Stages: place, then size
Stage 0 drags the point along `x` (where). Stage 1 resizes it (how confident). Only one edit is live at a time.
A staged probe edit advances the stage when it commits. Set `advance: false` on it to advance by hand instead.
### Example: Two-stage point
Same mark, two staged edits, a Next button.
Try: drag horizontally; press Next; drag outward to resize.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 16 },
axes: { x: {}, y: false },
stage: 0,
data: [{ x: 5, mag: 12 }],
onChange: (d) => console.log(d[0]),
schema: {
x: { type: "quantitative", domain: [0, 10] },
mag: { type: "quantitative", domain: [0, 14] },
},
marks: [
point({
channels: {
x: { field: "x", edit: move({ stage: 0 }) },
size: { field: "mag", edit: resize({ stage: 1 }) },
},
}),
],
});
mount(chart.dom());
const label = document.createElement("div");
const render = () => { label.textContent = "stage: " + chart.getStage(); };
chart.on("stage", render); render();
const btn = document.createElement("button");
btn.textContent = "Next";
btn.onclick = () => chart.nextStage();
const controls = document.createElement("div");
controls.style.cssText = "margin-top:8px;display:flex;gap:10px;align-items:center";
controls.append(btn, label);
mount(controls);
```
## Probe across stages
A probe edit with a `stage` advances to the next stage when it commits, unless it sets `advance: false`.
### Example: Two steps: slope, then spread
Stage 0 sets the trend slope; stage 1 opens the confidence cone.
Try: Move the pointer to aim the line and click; then move to open the confidence cone and click.
```javascript
const chart = Elicit({
width: 320, height: 320,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
data: [{ r: 0, spread: 0 }],
schema: {
x: { type: "quantitative", domain: [-1, 1] },
y: { type: "quantitative", domain: [-1, 1] },
r: { type: "quantitative", domain: [-1, 1] },
spread: { type: "quantitative", domain: [0, 1] },
},
marks: [
trendBand({
render: "samples", samples: 60,
channels: {
intercept: { datum: 0 },
slope: { field: "r" },
slopeSpread: { field: "spread" },
},
}),
trend({
id: "belief",
handles: false,
stroke: "#EE7B5E", strokeWidth: 3,
channels: {
intercept: { datum: 0 },
// Stage 0: no handle to grab, so the gesture takes the pointer's own x
// and the line simply follows the cursor. A click sets it and advances.
slope: { field: "r", edit: edit.trend.slope({ pick: "probe", stage: 0 }) },
// Stage 1: how far the line through the pointer tilts away from the
// committed one is the envelope half-width.
slopeSpread: { field: "spread", edit: edit.trend.slopeSpread({ pick: "probe", stage: 1 }) },
},
}),
],
});
mount(chart.dom());
const out = document.createElement("div");
out.style.cssText = "font:12px ui-monospace,monospace;margin-top:6px;color:#6F8294";
const show = () => {
const d = chart.getData()[0] || {};
out.textContent = "stage " + chart.getStage() +
" · committed r=" + (d.r ?? 0).toFixed(2) + " spread=" + (d.spread ?? 0).toFixed(2);
};
chart.on("change", show); chart.on("stage", show); show();
mount(out);
```
---
# Axes and view: rescale, zoom & pan
> Source: https://elicitjs.github.io/editing/axis/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
An axis with an `edit` rewrites the field's **domain** on the schema, where a mark edit rewrites a **datum**. Drag a numeric axis to change its range. A categorical axis gains controls to **add, rename and remove** categories. The chart's `view` takes the edits that move the whole plot: the wheel zooms it and a drag pans it. The grid, guides and marks follow the new domain, and `chart.setDomain(field, domain)` does the same from a button. Read it with `chart.getSchema()`. The dataset is unchanged, except that removing a category deletes its rows.
## API reference
### `edit.axis.scale(options)`
Numeric / temporal axis — drag an end-handle to rescale the range. Runs through the axisDrag driver (the plane owns the gesture); apply writes the new [min,max].
JSON keyword: `edit.axis.scale`
```ts
edit.axis.scale({ field, mode }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `field` | `string` | `all on axis` | The schema field whose domain to write. Defaults to every field unioned onto the axis (e.g. an error bar's mean/lo/hi). |
| `mode` | `'rescale'\|'grow'` | `'rescale'` | `rescale` keeps the chart size (marks compress); `grow` holds the data's pixels-per-unit and resizes the chart instead. |
Returns / emits: An **Edit** with `target: "domain"`. apply returns `{ domains, resize? }`; the engine writes the schema (and resizes in grow mode).
### `edit.scale.categories(options)`
Categorical / ordinal SCALE — add, rename and remove categories, from any element that draws it (an axis or a legend). Reuses the inline-typing lifecycle: double-click the "+" to add, double-click a label or swatch to rename, click its "×" to remove. Renaming and removing write every column on the scale, in every table it spans.
JSON keyword: `edit.scale.categories`
```ts
edit.scale.categories({ field, mode }) → Edit[]
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `field` | `string` | `every field on the axis` | The categorical field whose domain (and rows, on rename/remove) to edit. Unset, every field on the scale is written. |
| `mode` | `'rescale'\|'grow'` | `'rescale'` | `rescale` keeps the chart size (bands re-divide it — thinner as you add); `grow` keeps each band the same pixel size and grows/shrinks the chart by a step per category (e.g. a 5-point Likert extended to 7). |
Returns / emits: An **array of three Edits**, all `type: "scale.categories"` and `target: "domain"`. Each one’s `action` says which it is: `"add"`, `"rename"` or `"remove"`. Rename relabels matching rows; remove deletes them. In grow mode, add/remove also carry a chart `resize`.
### `view`
A spec option. Holds the edits on the view itself, the `x` and `y` domains as a window: `edit.view.zoom()` and `edit.view.pan()`. It needs no axis, so it works with `axes: false`. On a map it moves the `lon` and `lat` domains.
```ts
Elicit({ view: { edits: [edit.view.zoom(), edit.view.pan()] }, … })
```
Options:
| Option | Type | Description |
| --- | --- | --- |
| `edits` | `Edit[]` | The view's edits. A view edit placed on a mark or an axis warns and does nothing. |
### `edit.view.zoom(options)`
The wheel narrows or widens the view about the value under the pointer. It writes the schema’s domains, never the dataset. Place it in the view: `view: { edits: [edit.view.zoom()] }`.
JSON keyword: `edit.view.zoom`
```ts
edit.view.zoom({ channels, factor, limit, minSpan, min, max, mode, when }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `('x' \| 'y')[]` | `['x', 'y']` | The axes it zooms. With both, one factor scales them together. |
| `factor` | `number` | `1.2` | How much one wheel notch (100 px of wheel travel) scales the span. Scrolling up divides the span by it; scrolling down multiplies. |
| `limit` | `'declared' \| [lo, hi] \| false` | `'declared'` | The widest a domain may zoom out to: the field's domain as declared in the schema, an explicit range, or false for no limit. |
| `minSpan` | `number` | | The narrowest span a domain may zoom in to, in data units. Use it with one channel; with both, use max. |
| `min` | `number` | | The lowest zoom level, as a multiple of the declared view. 0.5 shows twice the declared span, which also needs limit: false. |
| `max` | `number` | | The highest zoom level, as a multiple of the declared view. 8 stops at eight times the declared size. |
| `mode` | `'domain' \| 'magnify'` | `'domain'` | `domain` moves positions and keeps every pixel size. `magnify` also scales sizes, text, strokes and layout gaps with the view. |
| `when` | `(ctx) => boolean` | | Gate the zoom on a modifier key. Two zooms, one per channel, with `when.alt` on one and `when.noAlt` on the other zoom the axes separately. |
Returns / emits: An **Edit** scoped to `view`. It acts on continuous scales (numeric or temporal). A burst of wheel ticks is one undo step.
### `edit.view.pan(options)`
Dragging the plot slides the view along. It writes the schema’s domains, never the dataset, and composes with `edit.view.zoom()`: `view: { edits: [edit.view.zoom(), edit.view.pan()] }`.
JSON keyword: `edit.view.pan`
```ts
edit.view.pan({ channels, limit, when }) → Edit
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `channels` | `('x' \| 'y')[]` | `['x', 'y']` | The axes it pans. |
| `limit` | `'declared' \| [lo, hi] \| false` | `'declared'` | How far it may pan: the field's domain as declared in the schema, an explicit range, or false for no limit. At the limit the view stops and keeps its span. |
| `when` | `(ctx) => boolean` | | Gate the pan on a modifier key, e.g. `when.shift` to pan only with Shift held. |
Returns / emits: An **Edit** scoped to `view`. It acts on continuous scales (numeric or temporal). A press on a mark with its own edit edits the mark. One drag is one undo step.
### `clip`
A spec option. Clips the marks to the plot area, axis to axis. Only the part of a mark inside the clip takes a press or shows a tip. Axes, legends, guides and marks with `clip: false` keep drawing in the margins.
```ts
Elicit({ clip: true | false, … })
Elicit({ clip: { padding: 6 }, … })
Elicit({ clip: { padding: { top: 4, bottom: 4 } }, … })
text({ clip: false, … }) // on a mark
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `clip` | `boolean \| { padding }` | `on with zoom or pan` | On by default when the view carries `edit.view.zoom()` or `edit.view.pan()`, off otherwise. The object form turns it on. |
| `padding` | `number \| { top, right, bottom, left }` | `0` | Pixels past the plot area the marks still draw: one number for every side, or a number per side. |
| `clip (on a mark)` | `boolean` | `follows the chart` | `false` draws the mark past the clip. On a `composite`, it applies to every part. |
### `chart.setDomain(field, domain, options)`
Write a field’s domain from outside the chart — a zoom button, a reset control. The same commit a wheel tick or a pan makes: undoable, notified through `change`, and every scale reflows.
No JSON form: this is called in JavaScript.
```ts
chart.setDomain("x", [20, 40]) // → true
chart.setDomain("x", null) // restore the declared domain
chart.setDomain("weight", [0, 5], { table: "links" })
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `field` | `string` | | The schema field to write. It writes that one field, as given. |
| `domain` | `any[] \| null` | | The new domain, or null for the domain declared in the schema. On a field declared with no domain, null takes a written domain away. |
| `options.table` | `string` | `the primary table` | The table that declares the field. |
Returns / emits: `true` when it wrote the domain. `false`, with a warning, when the table declares no such field, there is no domain to restore or take away, or the domain does not fit the field’s type: `[min, max]` for a numeric or temporal field, a list of distinct values for a categorical one.
## Drag a numeric axis to rescale
`axisX({ edit: edit.axis.scale() })` adds a draggable handle at each end of the axis. Drag a handle toward the middle to widen the range, so the data compresses into the same chart. Drag it outward to narrow the range. The opposite end stays fixed, and the dataset is unchanged.
### Example: Rescale in place
Dragging the end-handle rewrites x's schema domain; the grid follows.
Try: **Drag** the blue handle at either end of the x-axis.
```javascript
const chart = Elicit({
width: 420, height: 280,
margins: { top: 16, right: 18, bottom: 40, left: 44 },
data: [{ x: 20, y: 30 }, { x: 55, y: 65 }, { x: 90, y: 20 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
axes: false,
marks: [
gridX(), axisY(),
axisX({ title: "x", edit: edit.axis.scale() }),
point({ fill: "#8A78C0", size: 7,
channels: { x: { field: "x" }, y: { field: "y" } } }),
],
});
mount(chart.dom());
```
### Example: Grow the chart instead
mode: 'grow' holds the data's scale constant and resizes the chart.
Try: **Drag** the x-axis max handle — the chart itself grows/shrinks.
```javascript
const chart = Elicit({
width: 360, height: 260,
margins: { top: 16, right: 18, bottom: 40, left: 44 },
data: [{ x: 20, y: 30 }, { x: 90, y: 55 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
axes: false,
marks: [
axisY(),
axisX({ title: "x", edit: edit.axis.scale({ mode: "grow" }) }),
point({ fill: "#315228", size: 7,
channels: { x: { field: "x" }, y: { field: "y" } } }),
],
});
mount(chart.dom());
```
## Add, rename & remove categories
`axisX({ edit: edit.scale.categories() })` makes each category label a rename target (double-click to type). Each label gets an × to remove it, and a + at the end adds a new one. A rename relabels matching rows, and a removal deletes them, so the schema and data stay in step.
The domain belongs to the **scale**, so the same edit works on any element that draws it, including a [legend](https://elicitjs.github.io/editing/legend.md#domain-authoring). When one scale spans several columns or tables, it writes all of them.
### Example: Edit the category list
Double-click + to add · double-click a label to rename · click × to remove.
Try: **Double-click** + to add a bar · **double-click** a label to rename · **click** × to remove.
```javascript
const chart = Elicit({
width: 420, height: 280,
margins: { top: 16, right: 18, bottom: 48, left: 44 },
data: [
{ cat: "Apples", v: 6 },
{ cat: "Pears", v: 9 },
{ cat: "Plums", v: 4 },
],
schema: {
cat: { type: "categorical", domain: ["Apples", "Pears", "Plums"] },
v: { type: "quantitative", domain: [0, 12] },
},
axes: false,
marks: [
axisY(),
axisX({ edit: edit.scale.categories() }),
bar({ fill: "#50AEB7",
channels: { x: { field: "cat" }, y: { field: "v" } } }),
],
});
mount(chart.dom());
```
### Example: Grow a Likert scale
mode: 'grow' keeps each band the same width and grows the chart by a step per point added — extend a 5-point scale to 7 without cramming.
Try: **Double-click** + to add points — the chart widens instead of the bars shrinking · **click** × to shrink it back.
```javascript
const chart = Elicit({
width: 320, height: 240,
margins: { top: 16, right: 18, bottom: 46, left: 40 },
data: [
{ step: "1", n: 3 }, { step: "2", n: 6 }, { step: "3", n: 9 },
{ step: "4", n: 5 }, { step: "5", n: 2 },
],
schema: {
step: { type: "ordinal", domain: ["1", "2", "3", "4", "5"] },
n: { type: "quantitative", domain: [0, 12] },
},
axes: false,
marks: [
axisY(),
axisX({ edit: edit.scale.categories({ mode: "grow" }) }),
bar({ fill: "#2B5D87",
channels: { x: { field: "step" }, y: { field: "n" } } }),
],
});
mount(chart.dom());
```
## Zoom with the wheel
Put `edit.view.zoom()` in the spec's `view`: `view: { edits: [edit.view.zoom()] }`. Scroll up to zoom in and down to zoom out. The value under the pointer stays where it is.
It zooms `x` and `y` by one factor. Set `channels: ["x"]` or `channels: ["y"]` to zoom one axis and leave the other alone. The view needs no axis, so a chart with `axes: false` zooms the same way.
The declared domain is the zoom-out ceiling, so you can always scroll back to the full view and no further. Set `limit` to an explicit `[lo, hi]` for a different ceiling, or `false` for none. `min` and `max` set the zoom levels it stops at, as multiples of the declared view: `max: 8` stops at eight times the declared size.
A burst of wheel ticks is one step in [history](https://elicitjs.github.io/editing/history.md), so one undo restores the domain from before you scrolled. Each tick notifies `change`, and `chart.getSchema()` reads the current domain. The domain is the dataset's, so [charts that share a dataset](https://elicitjs.github.io/dataset.md) zoom together.
Zoom works on numeric and temporal axes, and on [a map](https://elicitjs.github.io/marks/geo.md#zoom-pan), where it moves the `lon` and `lat` domains. Mark edits keep working at every zoom level: drag a point and it inverts through the zoomed scale. The buttons call `chart.setDomain` for each axis (see [below](#set-domain)).
### Example: Zoom both axes
edit.view.zoom() in view, plus buttons that zoom about the centre.
Try: **Scroll** over the plot or **click** Zoom in · **drag** a point at any zoom level.
```javascript
const chart = Elicit({
width: 420, height: 280,
margins: { top: 16, right: 18, bottom: 32, left: 40 },
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
data: [
{ x: 12, y: 20 }, { x: 24, y: 42 }, { x: 38, y: 35 }, { x: 47, y: 58 },
{ x: 55, y: 51 }, { x: 63, y: 70 }, { x: 71, y: 64 }, { x: 86, y: 82 },
],
// The wheel zooms x and y by one factor, about the value under the pointer.
view: { edits: [edit.view.zoom()] },
marks: [
point({
fill: "#8A78C0", size: 6,
channels: { x: { field: "x" }, y: { field: "y" } },
edits: [move({ channels: ["x", "y"] })],
}),
],
});
mount(chart.dom());
// Buttons zoom both axes about the centre of the view, clamped to the
// declared domains.
const DECLARED = { x: [0, 100], y: [0, 100] };
const zoomBy = (k) => {
const schema = chart.getSchema();
for (const field of ["x", "y"]) {
const [lo, hi] = schema[field].domain;
const [LO, HI] = DECLARED[field];
const half = Math.min((hi - lo) * k, HI - LO) / 2;
const mid = Math.min(Math.max((lo + hi) / 2, LO + half), HI - half);
chart.setDomain(field, [mid - half, mid + half]);
}
};
const controls = document.createElement("div");
controls.style.cssText = "display:flex;gap:8px;margin-top:10px;font:12px system-ui";
const addButton = (label, onclick) => {
const b = document.createElement("button");
b.textContent = label;
b.onclick = onclick;
b.style.cssText = "padding:4px 10px;border:1px solid #BCC9D4;border-radius:6px;background:#fff;cursor:pointer";
controls.append(b);
};
addButton("Zoom in", () => zoomBy(0.5));
addButton("Zoom out", () => zoomBy(2));
addButton("Reset", () => { chart.setDomain("x", null); chart.setDomain("y", null); });
mount(controls);
```
## Pan by dragging
Add `edit.view.pan()` beside the zoom. Drag the plot and the view follows the pointer, on both axes. `channels: ["x"]` pans along `x` only.
A press on a mark with an edit of its own still edits that mark. A press anywhere else on the plot pans.
Pan stops at the declared domain, keeping the span. Set `limit` as on zoom. One drag is one undo step.
Zoom and pan write the same domains, so they combine. Each starts from where the other left it, and you can scroll to zoom in the middle of a drag.
### Example: Zoom and pan a year of data
edit.view.zoom() and edit.view.pan() with channels: ["x"]. The buttons zoom about the centre of the view.
Try: **Scroll** or **click** Zoom in · **drag** the plot to pan · **drag** a point to edit it.
```javascript
// A year of weekly rainfall. Zoom in, then drag the plot to pan along it.
const data = d3.range(53).map((week) => ({
week,
rain: Math.round(40 + 25 * Math.sin(week / 8) + 10 * Math.cos(week / 3)),
}));
const chart = Elicit({
width: 460, height: 260,
margins: { top: 16, right: 18, bottom: 32, left: 40 },
schema: {
week: { type: "quantitative", domain: [0, 52] },
rain: { type: "quantitative", domain: [0, 100] },
},
data,
// Zoom and pan both write the week domain, so each picks up where the
// other left off. `channels: ["x"]` leaves y alone.
view: {
edits: [
edit.view.zoom({ channels: ["x"], minSpan: 4 }),
edit.view.pan({ channels: ["x"] }),
],
},
marks: [
lineY({ stroke: "#2B5D87", strokeWidth: 2, channels: { x: { field: "week" }, y: { field: "rain" } } }),
point({
fill: "#2B5D87", size: 4,
channels: { x: { field: "week" }, y: { field: "rain", edit: move() } },
}),
],
});
mount(chart.dom());
const [LO, HI] = [0, 52]; // the declared week domain
const zoomBy = (k) => {
const [lo, hi] = chart.getSchema().week.domain;
const half = Math.max(2, Math.min((hi - lo) * k, HI - LO) / 2);
const mid = Math.min(Math.max((lo + hi) / 2, LO + half), HI - half);
chart.setDomain("week", [mid - half, mid + half]);
};
const controls = document.createElement("div");
controls.style.cssText = "display:flex;gap:8px;align-items:center;margin-top:10px;font:12px system-ui";
const addButton = (label, onclick) => {
const b = document.createElement("button");
b.textContent = label;
b.onclick = onclick;
b.style.cssText = "padding:4px 10px;border:1px solid #BCC9D4;border-radius:6px;background:#fff;cursor:pointer";
controls.append(b);
};
addButton("Zoom in", () => zoomBy(0.5));
addButton("Zoom out", () => zoomBy(2));
addButton("Reset", () => chart.setDomain("week", null));
const readout = document.createElement("span");
readout.style.color = "#6F8294";
controls.append(readout);
mount(controls);
const show = () => {
const [lo, hi] = chart.getSchema().week.domain;
readout.textContent = `weeks ${lo.toFixed(1)} – ${hi.toFixed(1)}`;
};
chart.on("change", show);
show();
```
## Zoom sizes and text
Zoom changes the domain, so by default only positions move with it. A `size`, `width`, `height` or font size in pixels stays the same on screen at every zoom level.
`edit.view.zoom({ mode: "magnify" })` scales every pixel length with the view. The sizes you write are the sizes at the declared domain. At twice the zoom a box, its text, its stroke and its corner radius all draw twice as large. Axes, legends and `ui` grips keep their size.
A size that is data stays data. Drag a grip at twice the zoom and 40 pixels of travel write 20 units, so the value you elicit is the same at any zoom level.
A [layout](https://elicitjs.github.io/layout.md) reads its `gap`, `rankGap` and `padding` at the declared size too. Zooming in spreads the rows and grows the gaps together, and the positions the layout wrote stay as they are.
Zoom both axes, as the default does. With `channels: ["x"]`, widths follow the zoom and heights keep their size, so shapes stretch.
### Example: Zoom a board of notes
mode: "magnify" on edit.view.zoom(), with axes: false and a layered layout.
Try: **Scroll** to zoom · **drag** the plot to pan · **drag** a note to move it, or a grip on its side to resize it.
```javascript
// Steps of a process. The layout places them; the links follow.
const chart = Elicit({
width: 520, height: 380,
margins: { top: 12, right: 12, bottom: 12, left: 12 },
axes: false,
schema: {
structure: "network",
tables: {
steps: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
w: { type: "quantitative", domain: [70, 220] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
flows: {
role: "links",
directed: true,
fields: { source: { type: "ref" }, target: { type: "ref" } },
},
},
},
data: {
steps: [
{ id: "ask", label: "Ask the question", w: 120 },
{ id: "draw", label: "Draw a first guess", w: 120 },
{ id: "show", label: "Show the data", w: 120 },
{ id: "revise", label: "Revise the guess", w: 120 },
{ id: "save", label: "Save both answers", w: 120 },
],
flows: [
{ source: "ask", target: "draw" },
{ source: "draw", target: "show" },
{ source: "draw", target: "save" },
{ source: "show", target: "revise" },
{ source: "revise", target: "save" },
],
},
// "magnify" scales boxes, text, strokes and the layout's gaps with the view.
// `max: 6` stops at six times the declared size.
view: {
edits: [edit.view.zoom({ mode: "magnify", max: 6 }), edit.view.pan()],
},
marks: [
link({ stroke: "#46596B", strokeWidth: 1.5, curve: "orthogonal" }),
sticker({
id: "step",
fill: "#ECF3F9", stroke: "#1D4467",
cornerRadius: 10, maxWidth: 220,
edits: [editText({ multiline: true })],
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
// The width is data. A grip writes the same value at any zoom.
width: { field: "w", scale: { range: [70, 220] } },
text: { field: "label" },
},
}),
],
layout: [layout.network.layered({ direction: "down", gap: 18, rankGap: 26 })],
});
mount(chart.dom());
ui.attach(chart, [ui.handles({ on: { mark: "step" } })]);
// A readout of the zoom level: the declared span over the current one.
const readout = document.createElement("div");
readout.style.cssText = "margin-top:8px;font:12px system-ui;color:#6F8294";
mount(readout);
const show = () => {
const [lo, hi] = chart.getSchema().tables.steps.fields.x.domain;
readout.textContent = `zoom ${Math.round(100 / (hi - lo) * 100)}%`;
};
chart.on("change", show);
show();
```
## Sizes in data units
This is a workaround for a chart that zooms in the default mode. It scales no size. It stores each shape's edges as data and draws the shape between them, and positions move with the zoom.
A `rect` with `x1`/`x2` and `y1`/`y2` spans those values on the zoomed scales, so it grows as you zoom in. A corner radius of at least half the side draws a circle. Give the plot the same pixels per unit on both axes, so a circle stays round. Text and strokes keep their pixel size.
Drag a shape with `move({ channels: ["x1", "x2", "y1", "y2"], mode: "relative" })`. It moves both edges by the same amount on each axis, so the shape keeps its size.
### Example: Boxes and circles in data units
rect with x1/x2 and y1/y2 from the data; zoom and pan on the view.
Try: **Scroll** to zoom · **drag** the plot to pan · **drag** a shape to move it.
```javascript
// A workaround, with no size scaling: each shape stores its edges as data,
// x0–x1 and y0–y1. The four edges are positions, so they move with the zoom
// and the shape grows between them.
const data = [
{ kind: "box", x0: 10, x1: 40, y0: 60, y1: 85 },
{ kind: "box", x0: 52, x1: 70, y0: 30, y1: 52 },
{ kind: "box", x0: 85, x1: 112, y0: 66, y1: 90 },
{ kind: "circle", x0: 20, x1: 36, y0: 18, y1: 34 },
{ kind: "circle", x0: 76, x1: 86, y0: 10, y1: 20 },
{ kind: "circle", x0: 94, x1: 114, y0: 24, y1: 44 },
];
const chart = Elicit({
// 360 × 300 px for 120 × 100 units: 3 px a unit on both axes, so a
// square in data units is square on screen.
width: 400, height: 340,
margins: { top: 12, right: 8, bottom: 28, left: 32 },
schema: {
kind: { type: "categorical", domain: ["box", "circle"] },
x0: { type: "quantitative", domain: [0, 120] },
x1: { type: "quantitative", domain: [0, 120] },
y0: { type: "quantitative", domain: [0, 100] },
y1: { type: "quantitative", domain: [0, 100] },
},
data,
view: { edits: [edit.view.zoom({ max: 8 }), edit.view.pan()] },
marks: [
rect({
channels: {
x1: { field: "x0" }, x2: { field: "x1" },
y1: { field: "y0" }, y2: { field: "y1" },
fill: { field: "kind", scale: { range: ["#E8D3A9", "#A9CFC4"] } },
// A corner radius of at least half the side draws a circle.
cornerRadius: { fn: (d) => (d.kind === "circle" ? 999 : 6) },
},
stroke: "#5E6E7C", strokeWidth: 1,
// Relative: the shape keeps its offset from where you grabbed it.
edits: [move({ channels: ["x1", "x2", "y1", "y2"], mode: "relative" })],
}),
],
});
mount(chart.dom());
```
## Clip to the plot
A zoomed or panned chart clips its marks to the plot area, axis to axis. A mark past an axis is hidden, and only the part inside the plot takes a press or shows a tip. Axes, legends and guides keep drawing in the margins.
Clipping is on by default whenever the view carries `edit.view.zoom()` or `edit.view.pan()`. Set `clip: false` on the spec to turn it off, or `clip: true` to clip a chart with neither.
`clip: { padding: 6 }` clips to the plot area grown by 6 pixels, so a point on the edge of the domain draws whole. Pass one number for every side, or `{ top, right, bottom, left }` for each side. A `padding` turns clipping on.
Set `clip: false` on a mark to draw it past the clip, such as a label in the margin. Its marks take a press and show a tip out there too. On a `composite`, it applies to every part.
### Example: Pad the clip, label in the margin
clip: { padding: 6 } on the spec and clip: false on the text mark.
Try: **Scroll** to zoom · **drag** the plot to pan · **drag** the last point and its label follows.
```javascript
// Daily highs that touch both ends of the scale. `padding` lets a point on the
// edge draw whole; `clip: false` keeps the latest reading's label in the margin.
const data = d3.range(30).map((day) => ({
day,
high: Math.max(0, Math.min(40, Math.round(20 + 18 * Math.sin(day / 3) + 6 * Math.cos(day)))),
}));
const W = 460, H = 260;
const margins = { top: 16, right: 72, bottom: 32, left: 40 };
const chart = Elicit({
width: W, height: H, margins,
schema: {
day: { type: "quantitative", domain: [0, 29] },
high: { type: "quantitative", domain: [0, 40] },
},
data,
// Clip to the plot, grown by 6 px on every side.
clip: { padding: 6 },
view: {
edits: [
edit.view.zoom({ channels: ["x"], minSpan: 5 }),
edit.view.pan({ channels: ["x"] }),
],
},
marks: [
lineY({ stroke: "#EE7B5E", strokeWidth: 2, channels: { x: { field: "day" }, y: { field: "high" } } }),
point({
fill: "#EE7B5E", size: 6,
channels: { x: { field: "day" }, y: { field: "high", edit: move() } },
}),
// Pinned 8 px past the plot's right edge, at the latest day's value.
// `clip: false` lets it draw in the margin.
text({
clip: false, textAnchor: "start", fontSize: 12, fill: "#B14A30",
channels: {
x: { value: W - margins.left - margins.right + 8 },
y: { field: "high" },
text: { fn: (d, i, rows) => (i === rows.length - 1 ? `${d.high}° today` : "") },
},
}),
],
});
mount(chart.dom());
```
## One axis at a time
A plain wheel runs every `edit.view.zoom()` in the view. Declare one per axis with `channels`, and give each a `when` to split them by modifier key: `when.noAlt` on one and `when.alt` on the other.
`minSpan` sets the narrowest the domain may zoom in to, in data units. Here time stops at three months and value at ten units.
### Example: Time with the wheel, value with Alt
Two zooms, one per channel: when.noAlt on x and when.alt on y; minSpan caps how far each zooms in.
Try: **Scroll** to zoom time · **Alt + scroll** to zoom value · **drag** a point on the line.
```javascript
// A forecast over 24 months. The plain wheel zooms time; Alt + wheel zooms the value.
const data = d3.range(25).map((m) => ({
month: m,
value: 50 + 20 * Math.sin(m / 4) + m * 0.8,
}));
const chart = Elicit({
width: 440, height: 260,
margins: { top: 16, right: 18, bottom: 32, left: 40 },
schema: {
month: { type: "quantitative", domain: [0, 24] },
value: { type: "quantitative", domain: [0, 100] },
},
data,
view: {
edits: [
edit.view.zoom({ channels: ["x"], when: when.noAlt, minSpan: 3 }),
edit.view.zoom({ channels: ["y"], when: when.alt, minSpan: 10 }),
],
},
marks: [
lineY({
stroke: "#1B3F60", strokeWidth: 2,
channels: {
x: { field: "month" },
y: { field: "value", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Set a domain from outside
`chart.setDomain(field, domain)` writes a field's domain. It takes the same path as a wheel tick or a pan: one undo step, a `change` notification, and every scale reflows. Pass `null` to restore the domain declared in the schema.
`setDomain` returns `false` and logs a warning when the table declares no such field, or when the domain doesn't fit the field's type. A numeric or temporal field takes `[min, max]`; a categorical or ordinal one takes a list of distinct values. Pass `{ table }` to name a field of a table other than the primary one.
It writes the domain as given. Clamp to the declared domain yourself when zooming out, as the buttons above do:
```js
const zoomBy = (k) => {
const [lo, hi] = chart.getSchema().week.domain;
const half = Math.min((hi - lo) * k, 52) / 2;
const mid = Math.min(Math.max((lo + hi) / 2, half), 52 - half);
chart.setDomain("week", [mid - half, mid + half]);
};
```
---
# Legend pickers & editing
> Source: https://elicitjs.github.io/editing/legend/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A legend can take input as well as label a scale. Click a swatch to set a categorical field, drag a ramp handle to set a continuous value, or double-click to edit the scale's domain. With more than one row, a picker writes to the selected rows.
## API reference
### `edit.legend.category()`
Turn legend swatches into click targets that set a categorical field on the legend’s target rows.
JSON keyword: `edit.legend.category`
```ts
edit.legend.category(options?)
```
Returns / emits: An **Edit** for a legend. It takes the universal edit options and none of its own. The legend’s [`row`](https://elicitjs.github.io/marks/legend.md#api) option names the rows a click writes. With no `row`, it writes the selection, or the sole row of a one-row table. With neither, a click writes nothing.
### `edit.legend.value()`
Add a draggable handle to a continuous gradient colour ramp.
JSON keyword: `edit.legend.value`
```ts
edit.legend.value(options?)
```
Returns / emits: An **Edit** for a legend. It takes the universal edit options and none of its own. The handle writes the same target rows as `edit.legend.category()`: the legend’s `row`, else the selection, else the sole row of a one-row table.
### `edit.scale.categories()`
Inline add, rename, and remove affordances for the scale domain.
JSON keyword: `edit.scale.categories`
```ts
edit.scale.categories(options?)
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `mode` | `"rescale" \| "grow"` | `"rescale"` | "rescale" compresses items to keep chart size fixed; "grow" widens the chart when categories are added. |
## Categorical swatch pickers
Pass `edit: edit.legend.category()` to make each swatch a click target. A click sets the channel's field on the target row and recolours the mark.
### Example: Click a swatch to set category
A one-row answer whose category is set from the legend.
Try: **Click** a swatch to change the status.
```javascript
const chart = Elicit({
width: 340, height: 200,
margins: { top: 20, right: 16, bottom: 20, left: 20 },
axes: false,
data: [ { status: "Active" } ],
schema: {
status: { type: "categorical", domain: ["Active", "Paused", "Archived"] },
},
marks: [
point({
size: 40,
channels: {
x: { value: 100 },
y: { value: 100 },
fill: { field: "status" },
},
}),
legendColor({
anchor: "right",
edit: edit.legend.category(),
}),
],
});
mount(chart.dom());
```
## Targeting selected rows
With several rows, a picker needs a row to write. Its `row` target **defaults to the selection**: click a mark, then a swatch, and that mark updates.
With `edit.select({ multi: true })`, one swatch click updates every selected row at once.
### Example: Select bars, then pick a group
Click a bar to select it (or Shift-click for multiple), then click a swatch to reassign its group.
Try: **Click** a bar, **Shift-click** another, then **click** a legend swatch.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 20, right: 16, bottom: 30, left: 40 },
data: [
{ name: "A", value: 12, group: "North" },
{ name: "B", value: 8, group: "South" },
{ name: "C", value: 15, group: "East" },
{ name: "D", value: 6, group: "West" },
],
schema: {
name: { type: "categorical", domain: ["A", "B", "C", "D"] },
group: { type: "categorical", domain: ["North", "South", "East", "West"] },
value: { type: "quantitative", domain: [0, 16] },
},
marks: [
barY({
channels: {
x: { field: "name" },
y: { field: "value" },
fill: { field: "group" },
},
edits: [edit.select({ multi: true })],
}),
legendColor({
anchor: "right",
edit: edit.legend.category(),
}),
],
});
mount(chart.dom());
```
## Continuous ramp sliders
For a continuous field, `edit: edit.legend.value()` adds a draggable handle to the colour ramp. Dragging it writes that value to the row.
### Example: Drag the gradient ramp
Dragging the ramp handle updates the numeric temperature value.
Try: **Drag** the handle up and down along the gradient ramp.
```javascript
const chart = Elicit({
width: 320, height: 210,
margins: { top: 20, right: 16, bottom: 20, left: 20 },
data: [ { temp: 18 } ],
schema: { temp: { type: "quantitative", domain: [0, 30] } },
axes: false,
marks: [
point({
size: 35,
channels: {
x: { value: 80 },
y: { value: 95 },
fill: { field: "temp" },
},
}),
legendColor({
anchor: "right",
edit: edit.legend.value(),
}),
],
});
mount(chart.dom());
```
## Authoring categories on the scale
A swatch picker writes to a row. `edit.scale.categories()` writes to the **scale's domain**.
It adds three controls to the legend: **double-click a swatch** to rename its category, **click the ×** to delete it, and **double-click the +** to add a category. A rename updates matching rows, and a delete removes them.
### Example: Rename, remove, and add categories
Double-click + to append · double-click a label to rename · click × to remove.
Try: **Double-click** the + icon to add a category · **double-click** a label to rename it.
```javascript
const chart = Elicit({
width: 380, height: 220,
margins: { top: 20, right: 16, bottom: 28, left: 40 },
data: [
{ cat: "Alpha", val: 30 },
{ cat: "Beta", val: 55 },
{ cat: "Gamma", val: 40 },
],
schema: {
cat: { type: "categorical", domain: ["Alpha", "Beta", "Gamma"] },
val: { type: "quantitative", domain: [0, 60] },
},
marks: [
barY({
channels: {
x: { field: "cat" },
y: { field: "val" },
fill: { field: "cat" },
},
}),
legendColor({
anchor: "right",
edit: edit.scale.categories(),
}),
],
});
mount(chart.dom());
```
---
# History & undo
> Source: https://elicitjs.github.io/editing/history/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`chart.undo()` and `chart.redo()` step back and forward one gesture at a time. Each step restores the data rows, the schema's domains and the chart size.
## API reference
### `chart.undo() · chart.redo()`
On the dataset, and on every chart through it. Snapshots, not inverse operations: an edit’s `apply()` is already a pure data → data function, so the state *before* it is the undo, and no edit ever has to describe how to reverse itself.
No JSON form: this is called in JavaScript.
```ts
chart.undo() → boolean
chart.redo() → boolean
chart.canUndo() → boolean
chart.canRedo() → boolean
```
Options:
| Option | Type | Description |
| --- | --- | --- |
| `the unit is a gesture` | | A drag commits on every pointermove, so a per-commit history would replay the drag backwards one pixel at a time. A transaction opens when a gesture starts and closes when it ends; the first commit inside it records the pre-gesture state, once. A click, a keyboard nudge, and a typed commit are each their own step. |
| `undo() / redo()` | `→ boolean` | Whether it actually moved — `false` at the end of the stack. Both fire the ordinary `change` notification: downstream, an undo is just the data changing. |
| `canUndo() / canRedo()` | `→ boolean` | For a button’s disabled state. Re-check them on `change`, which fires for edits, undo and redo alike. |
| `what a snapshot holds` | `data + schema + size` | Not just the rows. `edit.axis.*` writes the schema’s **domain** and can grow the chart, so undoing a category-add has to put the domain, the rows *and* the size back. |
| `a new edit drops the redo branch` | | The usual linear-history rule: undo twice, then edit, and the future you undid past is gone. |
| `setData() clears it` | | A reseed is a new starting point, not an edit — there is nothing sensible to undo back to, and undoing past it would resurrect rows the caller replaced, under a [lock](https://elicitjs.github.io/editing/existence.md#seed) that no longer covers them. |
| `depth` | `100 gestures` | The oldest step falls off the end. |
Returns / emits: History belongs to the **dataset**. Charts over one dataset share one history, so an undo steps back the last gesture in any of them; a chart’s size is put back on the chart that changed it. Charts over separate datasets each keep their own. See [Datasets & linked charts](https://elicitjs.github.io/dataset.md#history).
### `Keyboard editing`
Keyboard nudge is always on — there is no option to disable it. Any node carrying a direct edit is focusable (`tabindex=0`, `role="button"`), and an arrow key on it dispatches a **nudge** that goes through the edit’s own `apply()` — so the keyboard cannot drift from the pointer, because it isn’t a second path. The only chrome option is the browser focus ring below.
No JSON form: this is called in JavaScript.
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `Arrow keys` | | | Move the focused mark along whichever axis carries an edit. On a **continuous** scale a press is 1% of the domain; on a **band** or **point** scale it steps one category, so a ranking moves by rank rather than by pixels. |
| `Shift + arrow` | | | A coarse step — 10% of the domain. (No effect on a categorical axis, where one category is already the smallest move.) |
| `focusOutline` | `boolean` | `false` | The browser’s native focus ring (the blue box after a click or Tab). Off by default — Tab and arrow keys still work; only the outline is suppressed. Set `true` when you want the ring visible (e.g. teaching keyboard editing). SVG/D3 renderer only. |
| `Constraints & locks apply` | | | Same edit, same dataset invariants: a nudge is clamped, snapped and repaired exactly as the drag is, and a [locked](https://elicitjs.github.io/editing/existence.md#seed) row is not focusable at all. |
| `One nudge, one undo step` | | | A press has no dragstart/dragend to bracket, so it commits as its own transaction — arrow-arrow-arrow then undo three times. |
Returns / emits: A nudge steps the value once, as a short drag would. It works for a direct `move()`, `slide()` or `resize()`, for a `rotate()` about its own mark, and for the brush edits.
## Gesture-level undo & redo
A history transaction opens when a gesture starts and closes when it ends. A whole drag is one undo step.
`undo()` and `redo()` return a boolean: whether the history moved. Both fire the `change` event, so your listeners update.
### Example: Undo a whole drag
chart.undo() / chart.redo() step the answer. canUndo() / canRedo() drive the button states.
Try: **Drag** a bar, then press **Undo** — the bar resets in one step.
```javascript
const chart = Elicit({
width: 420, height: 240,
margins: { top: 16, right: 16, bottom: 30, left: 40 },
schema: {
q: { type: "categorical", domain: ["Q1", "Q2", "Q3", "Q4"] },
n: { type: "quantitative", domain: [0, 100] },
},
data: [
{ q: "Q1", n: 40 }, { q: "Q2", n: 55 },
{ q: "Q3", n: 35 }, { q: "Q4", n: 60 },
],
marks: [
barY({ channels: { x: { field: "q" },
y: { field: "n", edit: move() } } }),
],
});
mount(chart.dom());
// Nothing here is special to undo: it is the ordinary chart API.
const controls = document.createElement("div");
controls.style.cssText = "display:flex;gap:8px;margin-top:10px;font:12px system-ui";
const undo = document.createElement("button");
const redo = document.createElement("button");
undo.textContent = "↶ Undo";
redo.textContent = "↷ Redo";
undo.onclick = () => chart.undo();
redo.onclick = () => chart.redo();
// canUndo / canRedo drive the buttons. `change` fires for edits AND for undo and
// redo themselves — downstream, all three are just "the data changed".
const sync = () => {
undo.disabled = !chart.canUndo();
redo.disabled = !chart.canRedo();
};
chart.on("change", sync);
sync();
controls.append(undo, redo);
mount(controls);
```
## Transaction boundaries & snapshots
A snapshot holds the data rows, the schema's domains (added categories, rescaled axes) and the chart size.
- **Gesture unit**: a drag, a sweep, a category addition and a keyboard nudge are each one transaction.
- **Redo branch**: a new edit after an undo drops the redo branch.
- **Reseed**: `chart.setData()` sets a new baseline and clears the undo stack.
---
# External controls
> Source: https://elicitjs.github.io/editing/external-controls/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
Drive a chart from a control outside it: an input, a ``, a slider, a rotate icon or a plain function. `set(field, value, { index })` writes a value straight into the dataset. `chart.control(name).set(value)` replays a gesture through a named edit and the chart's scales. Both run constraints and undo, and fire `on("change")`.
## API reference
### `set(field, value, options?)`
A dataset method, carried by every chart: write one cell from outside any chart. It runs the dataset’s constraints, then the lock, as an edit does; an edit’s own `constrain` does not run. One undo step; fires `change` and redraws every chart on the dataset. See [Datasets & linked charts](https://elicitjs.github.io/dataset.md#set).
No JSON form: this is called in JavaScript.
```ts
chart.set("n", 62) // row 0 of the primary table
chart.set("n", "62", { index: 2 }) // stored as the number 62
ds.set("weight", 3, { index: 0, table: "links" })
```
Returns / emits: `true` when it commits. `false` when a constraint rejects it, the row is locked or the value is unchanged, and, with a warning, for an undeclared field, an index out of range or a value the field’s type can’t hold. Writes rows that exist; to add one, replay a `create` gesture with `chart.emit`, or call `setData`.
### `edit({ name }) · chart.control(name, target?)`
Give any edit a `name`, then replay its gesture from outside the chart with `chart.control(name)`. The control synthesizes the same events a pointer does on that chart and feeds them to the one dispatch — so constraints, the edit’s own `constrain`, undo, guides, and `on("change")` all run. A new input *source*, not a second interaction system.
No JSON form: this is called in JavaScript.
```ts
move({ name: "move", channels: ["x", "y"] }) // name an edit
const h = chart.control("move", 0); // handle bound to the edit + datum 0
h.set(value) // one-shot write (value edit) …
h.set({ x, y }) // … or a data value per channel (positional edit)
h.begin(); h.set(v); h.end(); // live drag → ONE undo entry
h.fire() // TRIGGER edit (cycle/remove/toggle) — fires its click gesture
h.emit(event) // raw event to this edit alone, on this row's node
h.cancel() // abandon an open stroke
chart.control("link", { index: 0, channel: "port", side: "right" }) // one handle of a row
h.accepts() // what the channel's scale allows
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `edit.name` | `string` | `null` | The handle this edit answers to. An edit with no name stays pointer- and keyboard-driven. |
| `control(name, target?)` | `→ EditControl` | `target: 0` | A handle bound to that edit and that row. `target` is a row index, or `{ index, channel, side }` to name one of the row’s handles: a port’s side, a link’s `"source"` or `"target"` end. The edit’s `when` is not asked. Ask for the handle again after the data changes; it resolves the edit on each call. |
| `h.set(value)` | `void` | | Write a **data** value. A scalar for a single-channel edit, or a map keyed by channel or field for a multi-channel one. Untouched axes hold their current position rather than teleporting. Drives a direct edit, or a `nearest` or `sweep` pick on the control's row. Other plane edits log a warning; use `chart.emit` for them. |
| `h.begin() / h.end()` | `void` | | Bracket a live drag, so many `set` ticks collapse into one [undo](https://elicitjs.github.io/editing/history.md) entry — exactly as a pointer drag does. `end()` releases where the stroke’s pointer last was, so a connect or a rewire lands there. `begin({ x, y })` presses at that plot pixel in place of the row’s own. |
| `h.cancel()` | `void` | | Abandon the stroke `begin()` opened, with no release. An edit that commits on release writes nothing; what earlier ticks wrote stays, as one undo entry. |
| `h.fire()` | `void` | | Trigger an edit that takes no value — `cycle`, `remove`, `toggle`. It dispatches the edit’s own gesture on the row. |
| `h.accepts()` | `→ object \| null` | | What the channel’s scale allows: `{ field, type, kind, temporal, invertible, domain, values, range }`. `values` is the accepted set on a discrete channel and `null` on a continuous one, where `domain` is the accepted range — so a picker or slider can offer only valid choices. |
| `h.emit(event)` | `void` | | A raw event to this edit alone, on its node for the row. A plane edit takes it at the event's x and y. The low-level route when you already hold pixels. |
Returns / emits: Every route runs the ordinary dispatch, so a constraint gates an external write exactly as it gates a drag. External control is not a bypass.
### `chart.transaction()`
A dataset method, carried by every chart: hold one undo entry open across any number of writes. Everything committed until you call the returned function undoes as one step. `change` still fires per write.
No JSON form: this is called in JavaScript.
```ts
const end = chart.transaction();
chart.set("w", 140, { index: 0 }); chart.set("x", 30, { index: 0 });
end();
```
Returns / emits: The closer. Undo, redo and `setData` close an open transaction; calling the closer twice does nothing.
### `chart.scene · hit · scale · edits · metrics`
Read the drawn chart, for UI placed over it. Every value is a copy of the current frame; read again on `on("render")`. Pixels are plot pixels.
No JSON form: this is called in JavaScript.
```ts
chart.scene({ mark: "note", index: 2 }) // the row's drawn pieces
chart.hit({ x, y }, { reach: 12 }) // the piece at, or nearest, a point
chart.scale("x", { mark: "note" }).invert(px)
chart.edits({ mark: "note", index: 2 }) // the edits that row answers to
chart.metrics() // { width, height, margins, innerWidth, innerHeight, scale }
chart.toInner({ x: e.clientX, y: e.clientY }) // page -> plot pixels; toClient is the inverse
chart.on("render", () => { … }) // after every frame
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `scene(query?)` | `→ SceneView[]` | `every piece` | One view per drawn piece, in paint order: `{ mark, table, index, type, channel, side, box, center, angle, datum, hovered, selected, grabbed, visible, editable, locked }`. `query` is `{ mark, table, index, channel, side }`. `index` counts the rows `getData()` reports. `visible` is `false` for a port or a link end the chart is hiding. |
| `hit(point, { reach }?)` | `→ SceneView \| null` | `reach: 0` | The topmost visible piece at a point, or the nearest within reach pixels. |
| `scale(channel, { mark, index }?)` | `→ object \| null` | `the chart's shared scale` | `{ channel, field, table, encode, invert, paired, domain, range, kind, temporal, invertible }`. `invert` is `null` on a scale that can’t be read back. `paired` names the partner axis of a map’s `lon` or `lat`, and is `null` on any other scale. `null` when nothing binds a field on the channel. |
| `edits(query?)` | `→ EditInfo[]` | `every edit` | `{ name, type, gesture, pick, channels, fields, mark, table, cardinality, action?, available }`. `available` is whether it can run now: its stage is current, the row is unlocked and, on a port, a link could land somewhere. `action` appears only on edits that share a type, such as the `'add'`, `'rename'` and `'remove'` of `scale.categories`. |
| `metrics()` | `→ object` | | The chart’s size and margins in chart pixels. `scale` is CSS pixels per chart pixel: 1 unless `responsive: "scale"` stretches the drawing. |
| `toInner(point) · toClient(point)` | `→ { x, y }` | | Convert between the page's viewport pixels and plot pixels. |
| `on("render", cb) · on("destroy", cb)` | `→ unsubscribe` | | After each frame the chart draws; once, when the chart is destroyed. |
| `chart.theme` | `Theme` | | A copy of the resolved theme. |
| `chart.destroyed` | `boolean` | `false` | `true` once `destroy()` has run. Read-only. UI built over a chart checks it before it attaches; `ui.attach` does. |
### `set(options?)`
The universal value edit: write a value into a channel's field — quantitative, colour, categorical, temporal. The `commit`-gesture counterpart to the positional edits, and what an external picker/slider drives via `control(name).set(value)`. (`editText` is its text specialization.)
No JSON form: this is called in JavaScript.
```ts
fill: { field: "group", edit: set({ name: "category" }) }
chart.control("category", i).set("B")
```
### `select() · chart.select · chart.selectWhere`
Selection is transient *pipeline* state, not a `selected` data column. Put `edit.select()` on a mark to select it by click; drive the same state from outside with `chart.select(index)` (a specific item) or `chart.selectWhere(field, value)` (a category — the first matching row). The selected row gets the highlight outline, and a legend picker's `row` defaults to it. A `select` event fires; `on("change")`/`getData` never do.
No JSON form: this is called in JavaScript.
```ts
edits: [ select() ] // click a mark to select it
chart.select(2) // select a SPECIFIC item by index
chart.selectWhere("group", "North") // select by CATEGORY (first match)
chart.getSelection() // → the lowest index | null
chart.clearSelection() // deselect all
chart.on("select", (i, all) => …) // selection changed (no data moved)
```
### `chart.setDomain(field, domain, options)`
Write a field’s **domain** from outside the chart — a zoom button, a reset control. The same commit a wheel zoom, a pan or an axis drag makes: one undo step, a `change` notification, and every scale reflows. Pass `null` to restore the declared domain. See [Zoom & pan](https://elicitjs.github.io/editing/axis.md#set-domain).
No JSON form: this is called in JavaScript.
```ts
chart.setDomain("x", [20, 40]) // → true
chart.setDomain("x", null) // restore the declared domain
chart.setDomain("weight", [0, 5], { table: "links" })
```
### `chart.emit(event)`
Low-level: inject a renderer-shaped gesture event directly. `x`/`y` are inner (margin-subtracted) pixels. Prefer `control`, which computes pixels from a data value for you. An event from `chart.emit` names no row, so it is a plane gesture: a click that a `create()` answers, a drag that a sweep answers. To aim at one row, use `control(name, index)`.
No JSON form: this is called in JavaScript.
```ts
chart.emit({ type: "click", x: 120, y: 80 }) // a plane gesture
chart.control(name, index).set(value) // a value, on one row
chart.control(name, index).emit({ type: "drag", x, y }) // a pointer event, on one row
```
## Write a value with set
`set(field, value, { index, table })` is a dataset method, and every chart carries it. It writes one cell, runs the dataset's constraints and then the lock, and is one undo step. `index` counts the rows `getData()` reports and defaults to 0. The value is stored as the field's type, so an input's `"62"` becomes the number `62`. No edit runs, so `set` works on any declared field, with or without a chart. See [Datasets & linked charts](https://elicitjs.github.io/dataset.md#set).
### Example: Type a value per bar
Each input calls chart.set("n", value, { index: i }). The clamp on the dataset caps a typed 95 at 80.
Try: **Type** a value under a quarter, or **drag** a bar.
```javascript
// `chart.set(field, value, { index })` writes one cell of the dataset. No edit
// is involved, so the bars need none for the inputs to work; `move()` is here so
// you can drag them too.
const quarters = ["Q1", "Q2", "Q3", "Q4"];
const chart = Elicit({
width: 380, height: 220,
margins: { top: 14, right: 16, bottom: 28, left: 36 },
schema: {
q: { type: "categorical", domain: quarters },
n: { type: "quantitative", domain: [0, 100] },
},
data: quarters.map((q) => ({ q, n: 40 })),
// The dataset's rules hold for a typed value as they do for a drag.
constraints: [clamp({ min: 0, max: 80, field: "n" })],
marks: [
barY({
fill: "#50AEB7",
channels: { x: { field: "q" }, y: { field: "n", edit: move() } },
}),
],
});
mount(chart.dom());
const row = document.createElement("div");
row.style.cssText = "display:flex;gap:10px;flex-wrap:wrap;margin-top:10px;font:13px system-ui";
const inputs = quarters.map((q, i) => {
const label = document.createElement("label");
label.style.cssText = "display:flex;flex-direction:column;gap:2px;color:#6F8294";
label.textContent = q;
const input = document.createElement("input");
input.type = "number"; input.min = 0; input.max = 100; input.style.width = "64px";
// The input's value is a string; `set` stores it as the field's type.
input.onchange = () => chart.set("n", input.value, { index: i });
label.append(input);
row.append(label);
return input;
});
const sync = () => chart.getData().forEach((d, i) => { inputs[i].value = Math.round(d.n); });
chart.on("change", sync);
sync();
mount(row);
```
## Name an edit, then drive it
Use `control` when the write should act like the gesture: an edit's own `constrain`, a click edit such as `cycle`, a rotate about the mark. Give the edit a `name`, then call `chart.control(name)`.
An edit maps a gesture to data by *inverting* a channel's scale. `control(name).set(value)` runs that scale *forward* to find the gesture, then runs the ordinary edit. A value edit (`set`, `editText`) takes the value directly, with no pixel step. A value outside a closed categorical domain is refused with a warning; one outside a numeric or temporal domain is clamped to it. `control(name).accepts()` reports what the channel's scale allows, so a picker or slider can offer only valid values.
A control names its edit, so the edit's `when` is not asked: `when` chooses between pointer gestures. Constraints, the lock and the edit's stage still apply. For an edit only a control should fire, give it `gesture: "commit"`, a gesture no pointer makes, and drive it with `.fire()`.
## A picker and a drag pad
The `` writes the point's category through a `set()` edit. Its options come from `control("category", 0).accepts().values`. The pad drives a two-axis `move` live, and `begin() … set({x,y}) … end()` is one undo entry. The `clamp` on `y` limits the pad exactly as it limits a mouse drag.
### Example: Scatter: category picker + drag pad
A sets the category; a draggable pad moves the point through the clamped drag edit.
Try: pick a category; drag the pad; the point obeys the y ≤ 80 clamp either way.
```javascript
// External controllers drive the SAME edits a pointer does. A `` sets the
// category (a value edit); a draggable pad moves the point (a positional edit).
// Both go through the normal pipeline — the clamp on y holds for the pad exactly
// as it would for a mouse drag.
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
group: { type: "categorical", domain: ["A", "B", "C"] },
},
data: [
{ x: 30, y: 40, group: "A" },
{ x: 62, y: 70, group: "B" },
{ x: 78, y: 25, group: "C" },
],
// A dataset invariant: y can never exceed 80. It gates EVERY edit, including the
// pad drag below — external control is not a bypass.
constraints: [ clamp({ field: "y", max: 80 }) ],
marks: [
point({
size: 7,
channels: {
x: { field: "x" },
y: { field: "y" },
fill: {
field: "group",
scale: { range: ["#50AEB7", "#315228", "#F2B94B"] },
// A universal value edit: an external picker writes the chosen category.
edit: set({ name: "category" }),
},
},
// One drag over BOTH axes, named so a controller can address it.
edits: [ move({ name: "move", channels: ["x", "y"] }) ],
}),
],
});
mount(chart.dom());
// We drive datum 0 (the first point). `.accepts()` reads what the channel allows.
const i = 0;
const cats = chart.control("category", i).accepts().values; // ["A","B","C"]
const [dx, dy] = [chart.getSchema().x.domain, chart.getSchema().y.domain];
const controls = document.createElement("div");
controls.style.cssText = "display:flex;gap:16px;align-items:center;margin-top:10px;font:12px system-ui";
// 1) Category picker — options come straight from the scale's accepted values.
const pick = document.createElement("select");
for (const c of cats) {
const o = document.createElement("option");
o.value = c; o.textContent = c; pick.append(o);
}
pick.value = chart.getData()[i].group;
pick.onchange = () => chart.control("category", i).set(pick.value);
const pickWrap = document.createElement("label");
pickWrap.style.cssText = "display:flex;gap:6px;align-items:center";
pickWrap.append("category", pick);
// 2) A draggable pad — the "UI element around the point". Dragging maps the pad's
// local position to data space and drives the `move` edit live: begin() … set() …
// end() collapse into ONE undo entry, just like a real drag.
const pad = document.createElement("div");
pad.style.cssText = "position:relative;width:120px;height:120px;border:1px solid #BCC9D4;border-radius:8px;background:#F6F9FB;touch-action:none;cursor:grab";
const knob = document.createElement("div");
knob.style.cssText = "position:absolute;width:14px;height:14px;margin:-7px 0 0 -7px;border-radius:50%;background:#14283A";
pad.append(knob);
const placeKnob = () => {
const d = chart.getData()[i];
knob.style.left = ((d.x - dx[0]) / (dx[1] - dx[0]) * 100) + "%";
knob.style.top = (100 - (d.y - dy[0]) / (dy[1] - dy[0]) * 100) + "%";
};
let handle = null;
const toData = (ev) => {
const r = pad.getBoundingClientRect();
const fx = Math.max(0, Math.min(1, (ev.clientX - r.left) / r.width));
const fy = Math.max(0, Math.min(1, (ev.clientY - r.top) / r.height));
return { x: dx[0] + fx * (dx[1] - dx[0]), y: dy[0] + (1 - fy) * (dy[1] - dy[0]) };
};
pad.addEventListener("pointerdown", (ev) => {
pad.setPointerCapture(ev.pointerId);
handle = chart.control("move", i);
handle.begin();
handle.set(toData(ev));
});
pad.addEventListener("pointermove", (ev) => { if (handle) handle.set(toData(ev)); });
const stop = () => { if (handle) { handle.end(); handle = null; } };
pad.addEventListener("pointerup", stop);
pad.addEventListener("pointercancel", stop);
const padWrap = document.createElement("div");
padWrap.style.cssText = "display:flex;flex-direction:column;gap:4px;align-items:center;color:#6F8294";
padWrap.append(pad, document.createTextNode("drag to move point 0"));
controls.append(pickWrap, padWrap);
mount(controls);
// Keep the picker + knob in sync with committed data (edits, undo, redo all fire).
chart.on("change", () => { pick.value = chart.getData()[i].group; placeKnob(); });
placeKnob();
```
## Pick vs. cycle: driving other gestures
`.set(value)` drives the value edits (`set`, `editText`) and the positional ones (`move`, `rotate`, `resize`). The click edits (`cycle`, `remove`, `toggle`) take no value. `.fire()` drives them by running the edit's own gesture on the row. One circle can offer a **picker** (`set`, to jump to a value) and a **cycle** (`fire`, to step to the next) on the same field, beside the native click.
### Example: A circle: pick or cycle its category
A dropdown sets the category (set); a button and the circle itself step it (cycle).
Try: choose from the dropdown, press ⟳, or click the circle — all change the same field.
```javascript
// Two ways to change one circle's category, both external. `cycle` is a CLICK edit
// that steps to the next value; a picker SETS a value directly. They coexist on the
// same `fill` field: click the circle (or the ⟳ button) to step, or choose from the
// dropdown to jump straight there.
const chart = Elicit({
width: 300, height: 190,
margins: { top: 10, right: 10, bottom: 10, left: 10 },
schema: {
kind: { type: "categorical", domain: ["low", "med", "high"] },
},
data: [ { kind: "low" } ],
marks: [
point({
size: 26,
channels: {
x: { value: 150 },
y: { value: 90 },
fill: {
field: "kind",
scale: { range: ["#B7DEE1", "#50AEB7", "#50AEB7"] },
// Direct choice — a picker writes exactly this value.
edit: set({ name: "pick" }),
},
},
// Step-at-a-time — a click (on the circle or a button) advances the category.
edits: [ cycle({ name: "step", channel: "fill" }) ],
}),
],
});
mount(chart.dom());
const controls = document.createElement("div");
controls.style.cssText = "display:flex;gap:12px;align-items:center;margin-top:10px;font:13px system-ui";
// A picker → `set`: options are exactly the values the fill scale accepts.
const pick = document.createElement("select");
for (const v of chart.control("pick", 0).accepts().values) {
const o = document.createElement("option");
o.value = v; o.textContent = v; pick.append(o);
}
pick.value = chart.getData()[0].kind;
pick.onchange = () => chart.control("pick", 0).set(pick.value);
const pickWrap = document.createElement("label");
pickWrap.style.cssText = "display:flex;gap:6px;align-items:center";
pickWrap.append("pick", pick);
// A button → `fire`: dispatches the cycle edit's own click gesture, no value.
const step = document.createElement("button");
step.textContent = "⟳ cycle";
step.onclick = () => chart.control("step", 0).fire();
controls.append(pickWrap, step);
mount(controls);
// Keep the picker in step whichever way the category changed.
chart.on("change", () => { pick.value = chart.getData()[0].kind; });
```
## Sliders for facial features
Each facial parameter is a channel. Bind it to a field with a named `set()` edit and a slider can write it. The face stays draggable: grab the mouth to pull a smile. Each slider's range comes from `control(field).accepts().domain`.
### Example: Face: parameter sliders
Three sliders drive three facial params; dragging the face keeps them in sync.
Try: move a slider, or drag the face directly — both write the same fields.
```javascript
// A face is a row of fields; each facial PARAM is a channel on one of the face's
// parts. Bind each to a field with a named `set()` edit and an external slider can
// write it. `.accepts()` reads the range off the very scale the part encodes
// through — including a group's per-datum FRAME scale — so the slider offers
// exactly the values the channel accepts. Add a `slide`/`rotate` alongside and the
// same field is drivable by pointer too: one dataset, two input sources.
const PARAMS = [
{ param: "mouthCurve", field: "smile", label: "smile" },
{ param: "eyeScale", field: "eyes", label: "eyes" },
{ param: "browTilt", field: "brow", label: "brow" },
];
const channels = {};
for (const { param, field } of PARAMS) {
channels[param] = { field, edit: set({ name: field }) };
}
const chart = Elicit({
width: 300, height: 300,
margins: { top: 12, right: 12, bottom: 12, left: 12 },
schema: {
smile: { type: "quantitative", domain: [0, 1] },
eyes: { type: "quantitative", domain: [0, 1] },
brow: { type: "quantitative", domain: [0, 1] },
},
data: [ { smile: 0.7, eyes: 0.5, brow: 0.4 } ],
marks: [ face({ channels }) ],
});
mount(chart.dom());
const controls = document.createElement("div");
controls.style.cssText = "display:flex;flex-direction:column;gap:8px;margin-top:10px;font:12px system-ui;max-width:300px";
const sliders = {};
for (const { field, label } of PARAMS) {
// `.accepts()` tells the UI the field's range (from the scale/schema), so the
// slider offers only values the channel accepts.
const [lo, hi] = chart.control(field).accepts().domain;
const row = document.createElement("label");
row.style.cssText = "display:grid;grid-template-columns:48px 1fr;gap:8px;align-items:center";
const s = document.createElement("input");
s.type = "range"; s.min = lo; s.max = hi; s.step = (hi - lo) / 100;
s.value = chart.getData()[0][field];
s.oninput = () => chart.control(field).set(+s.value);
sliders[field] = s;
row.append(label, s);
controls.append(row);
}
mount(controls);
// Dragging the face directly also fires `change` — keep the sliders in step.
chart.on("change", () => {
const d = chart.getData()[0];
for (const { field } of PARAMS) sliders[field].value = d[field];
});
```
## A rotate icon for a box
`rotate` reads a pointer angle about the mark. `control("spin", 0).set(deg)` encodes the angle to the pointer position that would produce it, then runs the ordinary rotate edit. The box also rotates by direct drag.
### Example: Rotate a box by an icon
Buttons step the angle in data space; the control encodes each angle for the rotate edit.
Try: press the rotate buttons, or drag the box itself.
```javascript
// A rotate icon spins a box. `rotate` is a positional edit — it reads a pointer
// angle about the mark. Driving it by a DATA value (degrees) is just the inverse:
// `.set(deg)` forward-encodes the angle to the pointer that would produce it, then
// runs the ordinary edit. The box is also directly rotatable by dragging it.
const chart = Elicit({
width: 300, height: 260,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
theta: { type: "quantitative", domain: [0, 360] },
},
data: [ { x: 50, y: 50, theta: 20 } ],
marks: [
rect({
channels: {
x: { field: "x" },
y: { field: "y" },
width: { value: 90 },
height: { value: 60 },
fill: { value: "#50AEB7" },
stroke: { value: "#37919B" },
angle: {
field: "theta",
scale: { range: [0, 360] },
edit: rotate({ name: "spin", pick: "direct", pivot: "mark", fold: false }),
},
},
}),
],
});
mount(chart.dom());
const controls = document.createElement("div");
controls.style.cssText = "display:flex;gap:8px;align-items:center;margin-top:10px;font:13px system-ui";
const spinBy = (delta) => {
const now = chart.getData()[0].theta;
const next = ((now + delta) % 360 + 360) % 360;
chart.control("spin", 0).set(next); // forward-encodes deg -> pointer -> rotate
};
const ccw = document.createElement("button");
ccw.textContent = "⟲ −15°";
ccw.onclick = () => spinBy(-15);
const cw = document.createElement("button");
cw.textContent = "⟳ +15°";
cw.onclick = () => spinBy(15);
const readout = document.createElement("span");
readout.style.cssText = "color:#6F8294";
const sync = () => { readout.textContent = Math.round(chart.getData()[0].theta) + "°"; };
chart.on("change", sync);
sync();
controls.append(ccw, cw, readout);
mount(controls);
```
## Sweep and nearest edits
`control(name, index)` names its row, so it also drives an edit whose pick only chooses a row: `nearest` and `sweep`. `.set(v)` writes row `index`, whichever row the pointer would have found. An edit that needs a pointer path or position, such as `edit.line.draw()`, a brush or `create()`, logs a warning on `.set()` and writes nothing. Drive those with `control(name).emit({ type, x, y })` in plot pixels, which runs that edit alone at the point.
```js
// create({ name: "add", gesture: "commit" }) on a mark: add a row at a plot pixel.
chart.control("add").emit({ type: "commit", x: 120, y: 80 });
```
### Example: Type or sweep a forecast
One move({ pick: "sweep", name: "forecast" }) edit takes both the sweep and the inputs.
Try: **Sweep** across the chart, or **type** a value under a year.
```javascript
// A you-draw-it line takes its answer two ways: sweep across the chart, or type
// a value per year. `move({ pick: "sweep" })` finds the row under the pointer;
// `control("forecast", i)` names the row itself, so `.set(v)` writes year i.
const years = [2024, 2025, 2026, 2027, 2028];
const chart = Elicit({
width: 420, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
axes: { x: { tickFormat: "d" } },
schema: {
year: { type: "quantitative", domain: [2024, 2028] },
v: { type: "quantitative", domain: [0, 100] },
},
data: years.map((year) => ({ year, v: 50 })),
marks: [
lineY({
stroke: "#50AEB7", strokeWidth: 2.5,
channels: {
x: { field: "year" },
y: { field: "v", edit: move({ pick: "sweep", name: "forecast" }) },
},
}),
],
});
mount(chart.dom());
const row = document.createElement("div");
row.style.cssText = "display:flex;gap:10px;flex-wrap:wrap;margin-top:10px;font:13px system-ui";
const inputs = years.map((year, i) => {
const label = document.createElement("label");
label.style.cssText = "display:flex;flex-direction:column;gap:2px;color:#6F8294";
label.textContent = year;
const input = document.createElement("input");
input.type = "number"; input.min = 0; input.max = 100; input.style.width = "64px";
input.onchange = () => chart.control("forecast", i).set(Number(input.value));
label.append(input);
row.append(label);
return input;
});
const sync = () => chart.getData().forEach((d, i) => { inputs[i].value = Math.round(d.v); });
chart.on("change", sync);
sync();
mount(row);
```
## One handle of a row
A row can draw several handles: a node's four ports, a link's two ends, an area's two edges. `control(name, { index, channel, side })` names one. `channel` is the channel the handle moves (`"port"`, a link's `"source"` or `"target"`), and `side` is where it sits.
An edit that commits on release, such as `edit.network.connect()`, takes a whole stroke. `begin()` presses on the handle, `emit({ type: "drag", x, y })` moves the pointer, and `end()` releases where the pointer last was. `cancel()` abandons the stroke, so a connect or a rewire writes nothing. `begin({ x, y })` presses at a plot pixel of your choosing: use it when the stroke follows a pointer that went down somewhere else, such as on an icon beside the mark, so a relative `move` travels as far as the pointer does.
```js
// A new link from the right port of node 0, dropped on a plot pixel.
const link = chart.control("link", { index: 0, channel: "port", side: "right" });
link.begin();
link.emit({ type: "drag", x: 300, y: 140 });
link.end(); // or link.cancel()
// Re-point the target end of link 2.
chart.control("rewire", { index: 2, channel: "target" });
```
A view from [`chart.scene()`](#reading) carries `index`, `channel` and `side`, so it can be passed as the target.
## Several writes, one undo step
`chart.transaction()` holds one undo entry open and returns the function that closes it. Everything committed in between, by `set`, a control or a gesture, undoes as one step. `change` still fires for each write.
```js
// Widen a box by 20 and keep its left edge still: two cells, one step.
const end = chart.transaction();
chart.set("w", row.w + 20, { index: i });
chart.set("x", row.x + 10, { index: i });
end();
```
Undo, redo and `setData` close an open transaction.
## Reading the chart
UI placed over a chart needs to know where things are. These methods report the drawn chart. Every value is a copy, and pixels are plot pixels: the space inside the margins that an edit's pointer uses.
- `chart.scene(query?)` lists the drawn pieces: each one's `mark`, `table`, row `index`, `box`, `center`, `datum` and state (`hovered`, `selected`, `grabbed`, `visible`). A row usually draws several pieces. `query` narrows them by `mark`, `table`, `index`, `channel` or `side`.
- `chart.hit(point, { reach })` returns the piece at a point, or with `reach` the nearest within that many pixels.
- `chart.scale(channel, { mark })` returns `encode`, `invert`, `domain`, `range` and the field behind the channel.
- `chart.edits(query?)` lists the declared edits with their `name`, `type` and whether each can run now.
- `chart.metrics()` gives the chart's size and margins. `chart.toInner(point)` and `chart.toClient(point)` convert between the page (a pointer event's `clientX`, `clientY`) and plot pixels.
- `chart.on("render", cb)` runs after every frame, including each step of an eased motion. Read `scene()` again there.
A mark's `id` names it in a query. A glyph's `id` covers all its parts: `"note"` matches a sticker's box `"note/body"`, its label and its ports.
### Example: A label that follows a point
An HTML label per dot, re-placed on every render from chart.scene() and chart.toClient().
Try: **Drag** a dot. Its label follows and reads the row.
```javascript
// A label of your own that follows a point: read the chart, never reach into it.
const chart = Elicit({
width: 420, height: 280,
margins: { top: 20, right: 20, bottom: 40, left: 44 },
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
data: [{ x: 30, y: 60 }, { x: 68, y: 35 }],
marks: [
point({
id: "dot",
size: 9,
channels: { x: { field: "x", edit: move({ channels: ["x", "y"] }) }, y: { field: "y" } },
}),
],
});
mount(chart.dom());
const labels = chart.getData().map(() => {
const el = document.createElement("div");
el.style.cssText = "position:absolute;left:0;top:0;pointer-events:none;font:12px system-ui;"
+ "padding:2px 6px;border-radius:4px;background:#14283A;color:#fff;white-space:nowrap";
return el;
});
// After every frame: where is each dot now, and what does its row hold?
chart.on("render", () => {
const host = chart.dom().getBoundingClientRect();
for (const view of chart.scene({ mark: "dot" })) {
const el = labels[view.index];
if (!el.isConnected) chart.dom().appendChild(el);
// Plot pixels -> the page -> the chart's own container.
const at = chart.toClient({ x: view.center.x, y: view.box.y });
el.style.transform = `translate(${at.x - host.left}px, ${at.y - host.top}px) translate(-50%, -130%)`;
el.textContent = `${Math.round(view.datum.x)}, ${Math.round(view.datum.y)}`;
}
});
```
The [UI layer](https://elicitjs.github.io/ui.md) is built on these methods and on `control`.
## Driving the selection
The selection is interface state, kept beside the data, so it has its own API and its own `select` event. `chart.select(index)` picks a **specific row**. `chart.selectWhere(field, value)` picks by **category**: the first matching row, or every match with `{ all: true }`. Both set the selection as a click with `edit.select()` does. The selected row gets the highlight outline, and a legend picker edits it. `on("select")` reports the change. `getData` and `on("change")` stay silent, because no answer data changed.
Pass an array to `chart.select` for several rows at once. See [Selection](https://elicitjs.github.io/editing/selection.md) for multi-select, the `selected` effect and the edits that read the selection.
### Example: Select an item, or a category
A dropdown selects a specific bar; a button selects the first bar in a group; the legend edits whichever is selected.
Try: pick an item or a group — or click a bar — then use the legend to change its group.
```javascript
// Selection is pipeline state, so it has its own external API beside the data —
// no `selected` column. `el.select(index)` picks a SPECIFIC ITEM; `el.selectWhere`
// picks by CATEGORY (the first row matching a field/value). Clicking a bar selects
// it too (edit.select), and `on("select")` reports whichever way it moved. The
// legend then edits the SELECTED bar's group.
const chart = Elicit({
width: 360, height: 210,
margins: { top: 16, right: 16, bottom: 28, left: 36 },
data: [
{ name: "A", value: 12, group: "North" },
{ name: "B", value: 8, group: "South" },
{ name: "C", value: 15, group: "North" },
{ name: "D", value: 6, group: "South" },
],
schema: {
name: { type: "categorical", domain: ["A", "B", "C", "D"] },
group: { type: "categorical", domain: ["North", "South"] },
value: { type: "quantitative", domain: [0, 16] },
},
marks: [
barY({
channels: {
x: { field: "name" },
y: { field: "value" },
fill: { field: "group" },
},
edits: [ select() ], // click a bar to select it
}),
legendColor({ anchor: "right", title: "group", edit: edit.legend.category() }),
],
});
mount(chart.dom());
const controls = document.createElement("div");
controls.style.cssText = "display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-top:10px;font:13px system-ui";
// Select a SPECIFIC ITEM by its name (→ el.selectWhere on the `name` field).
const item = document.createElement("select");
for (const d of chart.getData()) {
const o = document.createElement("option");
o.value = d.name; o.textContent = d.name; item.append(o);
}
item.onchange = () => chart.selectWhere("name", item.value);
const itemWrap = document.createElement("label");
itemWrap.style.cssText = "display:flex;gap:6px;align-items:center";
itemWrap.append("item", item);
// Select a CATEGORY — the first bar in a group (→ el.selectWhere on `group`).
const cat = document.createElement("select");
for (const g of ["North", "South"]) {
const o = document.createElement("option");
o.value = g; o.textContent = g; cat.append(o);
}
const catBtn = document.createElement("button");
catBtn.textContent = "select group";
catBtn.onclick = () => chart.selectWhere("group", cat.value);
const catWrap = document.createElement("label");
catWrap.style.cssText = "display:flex;gap:6px;align-items:center";
catWrap.append("group", cat, catBtn);
// Clear.
const clear = document.createElement("button");
clear.textContent = "clear";
clear.onclick = () => chart.clearSelection();
const readout = document.createElement("span");
readout.style.cssText = "margin-left:auto;color:#6F8294";
controls.append(itemWrap, catWrap, clear, readout);
mount(controls);
// on("select") hears selection changes — never `change`, since no data moved.
chart.on("select", (i) => {
const d = i == null ? null : chart.getData()[i];
readout.textContent = d ? `selected: ${d.name} (${d.group})` : "nothing selected";
if (d) item.value = d.name;
});
readout.textContent = "nothing selected";
```
## Driving a domain
`chart.setDomain(field, domain)` writes a field's domain from outside the chart, for a zoom button or a "reset view" control. It commits like [`edit.view.zoom()`](https://elicitjs.github.io/editing/axis.md#wheel) and `edit.view.pan()`: one undo step, a `change` notification, and every scale updates. Pass `null` to restore the domain declared in the schema.
```js
chart.setDomain("x", [20, 40]); // zoom to 20–40
chart.setDomain("x", null); // back to the declared domain
```
See [Zoom & pan](https://elicitjs.github.io/editing/axis.md#wheel) for buttons that zoom in, zoom out and reset.
---
# UI layer
> Source: https://elicitjs.github.io/ui/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`ui.attach(chart, parts)` lays menus, icon buttons and handles over a chart you have already made. Each part acts through [external control](https://elicitjs.github.io/editing/external-controls.md): it fires the edits your spec names and writes values with `set`, so constraints and undo apply. The layer is HTML over the drawing. It works the same on the SVG and canvas renderers, and it is not part of the spec.
## API reference
### `ui.attach(chart, parts, options?)`
Lay parts over a chart. The layer is one HTML element over the chart’s drawing, added once the chart has drawn. Parts act through [external control](https://elicitjs.github.io/editing/external-controls.md), so the spec stays the statement of what can change.
No JSON form: this is called in JavaScript.
```ts
const layer = ui.attach(chart, [ui.contextMenu(), ui.handles()]);
layer.detach();
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `chart` | `Chart` | | What `Elicit(spec)` or `dataset.chart(spec)` returns. |
| `parts` | `UiPart \| UiPart[]` | | The parts to mount. Nested arrays are flattened. |
| `options.motion` | `boolean \| { duration }` | `false` | Fade icons, handles and menus in as they appear, and icons and handles out as they go. `true` takes 150 ms. Off when the reader’s system asks for reduced motion. |
Returns / emits: `{ detach() }`. `chart.destroy()` detaches the layer too.
### `ui.contextMenu(options?)`
A menu on right-click, over a mark or over empty space. With no `items`, it offers what the spec’s named edits allow: add on empty space, a declared value edit’s choices and remove on a row.
No JSON form: this is called in JavaScript.
```ts
ui.contextMenu({ items: [{ edit: "add" }, { channel: "fill" }, { separator: true }, { edit: "delete" }] })
ui.contextMenu({ items: ({ view, point }) => [ … ] })
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `items` | `MenuEntry[] \| (target) => MenuEntry[]` | `from the named edits` | The entries, or a function of what was right-clicked: `{ view, point }`, where `view` is `null` over empty space. |
| `entry.edit` | `string` | | The name of a declared edit. Fires on the row under the pointer, or at the pointer for an edit that adds a row. |
| `entry.channel` | `string` | | A channel of the mark: one row per value, the current one checked. With `edit` naming an edit that adds a row, each value adds a row with that value. |
| `entry.mark` | `string` | `the mark under the pointer` | The `id` of the mark the channel is on. |
| `entry.values` | `any[]` | `the scale's domain` | The choices, for a channel whose scale lists none. |
| `entry.label` | `string \| false` | `by kind` | The row’s text, or the heading over a channel’s values. `false` drops the heading. |
| `entry.icon · entry.tone` | `icon · "danger"` | `by kind` | An icon before the label; the removing colour. |
| `entry.on` | `"plane" \| SceneQuery` | `where it applies` | Show the entry only over empty space, or only on the pieces a [scene query](https://elicitjs.github.io/editing/external-controls.md#reading) matches: `{ mark: "note" }`. |
| `entry.onSelect` | `(target) => void` | | A row of your own, with `label`. |
| `entry.separator · entry.heading` | `true · string` | | A rule between groups; a caption over the rows that follow. |
### `ui.actions(options?)`
Icon buttons beside the drawn piece the pointer is near. An item drives a named edit, or runs your own function.
No JSON form: this is called in JavaScript.
```ts
ui.actions({ on: { mark: "note" }, items: [{ edit: "delete", icon: "trash", label: "Remove", tone: "danger" }] })
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `on` | `{ mark?, table?, index?, channel?, side? }` | `every row's pieces` | Which drawn pieces get the icons. |
| `items` | `ActionItem[]` | `[]` | Each has `icon` and `label`, then `edit` (a named edit) or `onClick(view)`. `show(view)` leaves an icon out for some pieces; `tone: "danger"` marks one that removes. |
| `reach` | `number` | `24` | How near the pointer must come, in pixels. |
| `placement` | `"top-right" \| "top" \| "right" \| …` | `"top-right"` | The side or corner of the piece the icons sit on. |
Returns / emits: An item whose edit can’t run on that row (another stage, a locked row) is left out.
### `ui.handles(options?)`
Grips on a mark’s box: resize it along the sides it sizes from data, turn it, or move it. Each drag is one undo step.
No JSON form: this is called in JavaScript.
```ts
width: { field: "w", scale: { range: [70, 260] } } // on the mark
ui.handles({ on: { mark: "note" } })
ui.handles({ on: { mark: "note" }, rotate: true, move: true })
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `on` | `{ mark?, table?, index?, channel?, side? }` | `every row of the first mark that sizes from data` | Which mark and rows get grips, as a scene query. A row gets them when any piece of it matches; the grips sit on its body. |
| `resize` | `boolean` | `true` | Grips on the left and right where the mark binds `width`, on the top and bottom where it binds `height`. A grip moves its own side and holds the opposite one still. |
| `rotate` | `boolean` | `false` | A grip above the box that turns it about its centre, writing the mark’s `angle` field. Shift snaps to 15°. |
| `move` | `boolean` | `false` | A grip below the box that moves it, writing the mark’s `x` and `y` fields. |
Returns / emits: Where a row already has a handle in the middle of a side (a port), the grip sits at the corner after it.
### `ui.custom(mount)`
A part of your own. `mount(ctx)` builds it in the layer and may return a function that takes it down.
No JSON form: this is called in JavaScript.
```ts
ui.custom((ctx) => { … return () => { … }; })
```
Options:
| Option | Type | Description |
| --- | --- | --- |
| `ctx.chart` | `Chart` | The chart the layer is over. |
| `ctx.layer` | `HTMLElement` | The layer. It ignores the pointer; a control you add opts in with its own pointer-events. |
| `ctx.place(el, anchor, placement?)` | `→ () => void` | Keep `el` on an anchor: a point in plot pixels, a scene view, or a function read on each render. `placement` is `{ at, offset, dx, dy }`, or a function returning one. An anchor of `null` hides the element. Returns its removal. |
| `ctx.refresh()` | `void` | Re-place every element now, after you change what one is anchored to. |
| `ctx.button(options)` | `→ HTMLButtonElement` | An icon button: `{ icon, label, tone, onClick }`. `label` is its accessible name. |
| `ctx.menu(items, at)` | `→ { element, close() }` | Open a menu at a point in plot pixels. Rows are `{ label, icon, swatch, checked, disabled, tone, onSelect }`, `{ separator: true }` or `{ heading }`. |
| `ctx.icon(icon)` | `→ Element` | An icon element from a name, SVG markup or an element. |
| `ctx.onRender(cb)` | `→ () => void` | Run after each frame the chart draws. |
| `ctx.onPointer(cb)` | `→ () => void` | The pointer over the chart: `{ type, point, event }`. `type` is `"move"` (once per frame), `"leave"` or `"menu"` (a right-click; call `event.preventDefault()` to take it). `point` is in plot pixels. |
| `ctx.drag(el, handlers)` | `→ () => void` | Make a layer element a drag source: `start`, `move`, `end`, `cancel` (Escape) and `click` (a press that never moved). Each step carries `{ point, dx, dy, event }`. |
| `ctx.capture(handlers)` | `→ () => void` | Take the chart’s next press for the layer: `move`, `press`, `cancel`. Until you call the returned function, the chart’s own gestures stay out. |
### `theme.ui · authoring.registerIcon(name, path)`
The layer’s tokens, and a way to add an icon name. The tokens are set on the layer as CSS variables named `--elicit-ui-*`.
No JSON form: this is called in JavaScript.
```ts
theme: { ui: { accent: "#7c3aed", size: 26 } }
authoring.registerIcon("star", "M8 2l1.8 3.9 4.2.5-3.1 2.9.8 4.2L8 11.4l-3.7 2.1.8-4.2L2 6.4l4.2-.5z")
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `surface · ink · muted · border` | `colour` | `#ffffff · #1f2937 · #6b7280 · #d5dbe5` | A menu's and a button's background; labels and icons; a heading or an unavailable row; edges. |
| `accent · danger` | `colour` | `#2563eb · #dc2626` | Hover, focus and the active icon; an action that removes. |
| `shadow` | `colour` | `rgba(15, 23, 42, 0.18)` | Under a menu and a button. |
| `radius · size · gap · fontSize` | `px` | `8 · 22 · 6 · 12` | A menu's corner; an icon button's side; the space between a mark and its icons; a menu's text. |
## Attach and detach
Make the chart, then attach the parts you want. `ui.contextMenu`, `ui.actions` and `ui.handles` work on any chart. [`ui.network`](https://elicitjs.github.io/ui/network.md) is a preset for node-link charts. `ui.custom` is a part of your own.
```js
const chart = Elicit(spec);
const layer = ui.attach(chart, [ui.contextMenu(), ui.handles()]);
layer.detach(); // take the parts down; chart.destroy() does it too
```
The layer has no JSON form. A chart built with `compile(json)` takes the same `ui.attach` call.
## Fade in and out
Pass `{ motion: true }` to fade the parts in as they appear. Icons and handles fade out as they go, and menus fade in. `{ motion: { duration } }` sets the time in milliseconds (150 by default). With reduced motion turned on in the reader's system, they appear at once.
```js
ui.attach(chart, [ui.actions(), ui.handles()], { motion: true });
```
The chart's own feedback fades with `effects.motion`. See [Fade in and out](https://elicitjs.github.io/effects.md#motion).
## What a part can change
A part writes in two ways, and which one depends on what changes.
**A row or a link.** Adding or removing a row, connecting, re-pointing and dragging run an edit the spec declares. Give that edit a `name`: a part can only drive a named edit, and it logs a warning for one it needs that has none.
**A value in a row.** A category, a colour, a width or a position needs no edit. The part writes it with `chart.set`. Where the spec declares a `set()` edit on that channel, the part uses it, so the edit's own `constrain` applies.
Both routes run the dataset's constraints and the lock, and each action is one undo step.
An edit placed on a mark also answers the pointer. For an edit only the UI should fire, give it `gesture: "commit"`, which is a gesture no pointer makes:
```js
edits: [
create({ name: "add", gesture: "commit" }), // from a menu, never from a click
remove({ name: "delete", gesture: "commit" }),
]
```
A part names its edit, so the edit's `when` is not asked. `when` chooses between pointer gestures.
## Context menu
`ui.contextMenu({ items })` opens a menu on right-click, over a mark or over empty space. Each entry is one of four things:
- `{ edit }` fires a named edit: on the row under the pointer, or at the pointer for an edit that adds a row.
- `{ channel }` lists the values of a mark's channel, with the row's current value checked. Choosing one writes it.
- `{ edit, channel }` lists the same values over empty space. Choosing one adds a row there with that value, as one undo step.
- `{ label, onSelect }` is a row of your own. `onSelect` receives `{ view, point }`.
An entry shows only where it applies, so one list serves the plane and every mark. `on` narrows it further: `"plane"`, or a [scene query](https://elicitjs.github.io/editing/external-controls.md#reading) such as `{ mark: "note" }`. With no `items`, the menu offers what the spec's named edits allow.
Arrow keys move through the menu, Enter chooses and Escape closes it. The menu opens above the page, so a box around the chart that scrolls or clips its content does not cut it off. Scrolling the page closes it.
### Example: A menu on a scatter
Right-click empty space to add a point for a team; right-click a point to change its team or remove it.
Try: **Right-click** the plot, then a point. **Drag** a point as usual.
```javascript
const chart = Elicit({
width: 460, height: 300,
margins: { top: 20, right: 20, bottom: 40, left: 44 },
schema: {
cost: { type: "quantitative", domain: [0, 100] },
impact: { type: "quantitative", domain: [0, 100] },
team: { type: "categorical", domain: ["Design", "Research", "Build"] },
},
data: [
{ cost: 22, impact: 70, team: "Design" },
{ cost: 58, impact: 44, team: "Build" },
{ cost: 76, impact: 82, team: "Research" },
],
marks: [
point({
id: "idea",
size: 9,
edits: [
// gesture: "commit" is a gesture no pointer makes, so only the menu fires these.
create({ name: "add", gesture: "commit" }),
remove({ name: "delete", gesture: "commit" }),
],
channels: {
x: { field: "cost", edit: move({ channels: ["x", "y"] }) },
y: { field: "impact" },
fill: { field: "team" },
},
}),
],
legends: true,
});
mount(chart.dom());
ui.attach(chart, [
ui.contextMenu({
items: [
// On empty space: add a point of the chosen team, there.
{ edit: "add", channel: "fill", mark: "idea", label: "Add an idea for" },
// On a point: its team, then Remove.
{ channel: "fill", label: "Team" },
{ separator: true },
{ edit: "delete" },
],
}),
]);
```
## Several fields in one menu
Each `{ channel }` entry lists one channel's values, so one menu can set several fields of a row. On this flowchart a step's kind sets its shape, through `symbol`, and its status sets its colour, through `fill`. The menu lists both, with each one's current value checked. The same list holds the entries for empty space and for links: each shows only where it applies.
### Example: Shape and status on a flowchart
symbol reads the kind of step and fill reads its status. One menu sets either; Add a step places a new one of the chosen kind.
Try: **Right-click** a step to change its kind or status, a link to reverse it, or empty space to add a step. **Drag** from a port to link two steps.
```javascript
const chart = Elicit({
width: 560, height: 400,
margins: { top: 40, right: 40, bottom: 40, left: 40 },
axes: false,
schema: {
structure: "network",
tables: {
steps: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
// The kind of step sets its shape; its status sets its colour.
kind: { type: "categorical", domain: ["start", "process", "decision", "data"] },
status: { type: "categorical", domain: ["done", "in progress", "blocked", "not started"] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
flows: {
role: "links",
directed: true,
fields: { source: { type: "ref" }, target: { type: "ref" } },
},
},
},
data: {
steps: [
{ id: "a", label: "Start", kind: "start", status: "done", x: 4, y: 75 },
{ id: "b", label: "Survey", kind: "data", status: "done", x: 30, y: 75 },
{ id: "c", label: "Clean", kind: "process", status: "in progress", x: 56, y: 75 },
{ id: "d", label: "Enough?", kind: "decision", status: "not started", x: 56, y: 22 },
{ id: "e", label: "Recruit", kind: "process", status: "blocked", x: 26, y: 22 },
{ id: "f", label: "Report", kind: "process", status: "not started", x: 90, y: 22 },
],
flows: [
{ source: "a", target: "b" },
{ source: "b", target: "c" },
{ source: "c", target: "d" },
{ source: "d", target: "e" },
{ source: "e", target: "b" },
{ source: "d", target: "f" },
],
},
marks: [
link({
id: "flow",
stroke: "#94A5B3",
strokeWidth: 1.5,
curve: "orthogonal",
edits: [
edit.network.rewire({ name: "rewire" }),
edit.network.reverse({ name: "reverse", gesture: "commit" }),
remove({ name: "unlink", gesture: "commit" }),
],
}),
composite({
id: "step",
channels: { x: { field: "x" }, y: { field: "y" } },
parts: [
shape({
size: 30,
stroke: "rgba(70, 89, 107, 0.45)",
// The edits sit on the shape, so the label on top lets the pointer through.
edits: [
create({ name: "add", gesture: "commit", defaults: { label: "New step", status: "not started" } }),
remove({ name: "delete", gesture: "commit" }),
],
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
symbol: {
field: "kind",
// A parallelogram path for data, the named shapes for the rest.
scale: { range: ["circle", "square", "diamond", "M -1 1 L -0.6 -1 L 1 -1 L 0.6 1 Z"] },
},
fill: {
field: "status",
scale: { range: ["#B9E0AC", "#FBDDA0", "#F5B3AA", "#E3E8EC"] },
},
ports: { value: true, edit: edit.network.connect({ name: "link" }) },
},
}),
text({ fontSize: 11, channels: { text: { field: "label" } } }),
],
}),
],
// The keys sit below, so the chart keeps its width.
legends: { symbol: { anchor: "bottom" }, fill: { anchor: "bottom" } },
});
mount(chart.dom());
ui.attach(chart, [
// Icons at ports and on links; the menu below replaces the preset's own.
ui.network({ menu: false }),
ui.contextMenu({
items: [
// On empty space: add a step of the chosen kind, there.
{ edit: "add", channel: "symbol", mark: "step", label: "Add a step" },
// On a step: its shape and its status, from two fields.
{ channel: "symbol", label: "Kind" },
{ channel: "fill", label: "Status" },
{ separator: true },
// On a link: turn it round or take it out.
{ edit: "reverse", label: "Reverse", icon: "swap" },
{ edit: "unlink", label: "Remove link" },
{ edit: "delete" },
],
}),
]);
```
`ui.network({ menu: false })` leaves out the preset's own menu, so this one is the only menu on the chart. The port and link icons stay.
## Preset values and rows of your own
A channel with a continuous scale has no list of values, so give the entry `values`. A row of your own takes `onSelect`, which receives `{ view, point }`: `view` is the mark under the pointer, or `null` over empty space. `on` keeps a row to one place. Writes inside one `chart.transaction()` undo together.
### Example: Preset values and rows of your own
values lists hours to choose on a bar. The other two rows are the page's own, written with set.
Try: **Right-click** a bar, then empty space. **Drag** a bar as usual.
```javascript
const chart = Elicit({
width: 460, height: 280,
margins: { top: 20, right: 20, bottom: 40, left: 44 },
schema: {
task: { type: "categorical", domain: ["Reading", "Coding", "Meetings", "Email"] },
hours: { type: "quantitative", domain: [0, 20] },
},
data: [
{ task: "Reading", hours: 6 },
{ task: "Coding", hours: 14 },
{ task: "Meetings", hours: 9 },
{ task: "Email", hours: 4 },
],
marks: [
barY({ id: "bar", channels: { x: { field: "task" }, y: { field: "hours", edit: move() } } }),
],
});
mount(chart.dom());
const rows = () => chart.getData();
const mean = () => rows().reduce((sum, d) => sum + d.hours, 0) / rows().length;
ui.attach(chart, [
ui.contextMenu({
items: [
// A continuous channel lists no values of its own: give them.
{ channel: "y", values: [0, 5, 10, 15, 20], label: "Hours" },
{ separator: true },
// A row of your own. `on` keeps it to the bars.
{
on: { mark: "bar" },
label: "Match the average",
onSelect: ({ view }) => chart.set("hours", Math.round(mean()), { index: view.index }),
},
// On empty space only: several writes, one undo step.
{
on: "plane",
label: "Even them all out",
onSelect: () => {
const m = Math.round(mean());
const end = chart.transaction();
rows().forEach((_, index) => chart.set("hours", m, { index }));
end();
},
},
],
}),
]);
```
## Icons beside a mark
`ui.actions({ on, items })` shows icon buttons beside the drawn piece the pointer comes near. `on` says which pieces, as a [scene query](https://elicitjs.github.io/editing/external-controls.md#reading): `{ mark: "note" }`. `reach` is how near, in pixels (default 24), and `placement` is the corner or side the icons sit on.
The icons stay while the pointer travels to them, and for a moment after it leaves the piece. The piece is lit as the chart lights a hovered mark. A line's icons sit beside the point the pointer met it at.
An item with `edit` drives that edit on the row. A click edit fires at once. A drag edit is dragged from its button; a click on the button arms it, and the next click on the chart is the drop. Escape cancels. An item with `onClick` is a button of your own.
### Example: Move and remove icons on a note
The grip drives the note's move edit; the bin fires a remove that no click on the note reaches.
Try: Bring the pointer **near a note**. **Drag** the grip, or click it and then click a spot.
```javascript
const chart = Elicit({
width: 460, height: 280,
margins: { top: 24, right: 24, bottom: 24, left: 24 },
axes: false,
schema: {
note: { type: "categorical", open: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
data: [
{ note: "Come near me for my icons.", x: 28, y: 66 },
{ note: "Drag the grip to move me.", x: 70, y: 34 },
],
marks: [
sticker({
id: "note",
fill: "#EBD6AD",
stroke: "rgba(70, 89, 107, 0.13)",
maxWidth: 150,
edits: [remove({ name: "delete", gesture: "commit" })],
channels: {
x: { field: "x", edit: move({ name: "drag", channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "note" },
},
}),
],
});
mount(chart.dom());
ui.attach(chart, [
ui.actions({
on: { mark: "note" },
placement: "top-right",
items: [
// A drag edit: drag the button, or click it and then click where to drop.
{ edit: "drag", icon: "grip", label: "Move" },
// A commit edit: one click fires it on the note.
{ edit: "delete", icon: "trash", label: "Remove", tone: "danger" },
],
}),
], { motion: true }); // the icons fade in and out
```
## Handles
`ui.handles({ on })` puts a grip on each side a mark sizes from data: left and right where it binds `width` to a field, top and bottom where it binds `height`. Dragging a grip moves that side and holds the opposite side still. The width and the position change together as one undo step. Escape during the drag puts the box back, and the arrow keys step a focused grip. `on` is a scene query, as in `ui.actions`: `{ mark: "note" }` names the mark, and `{ mark: "note", index: 0 }` keeps the grips to one row.
The size channel needs a continuous scale with a pixel `range`, which also sets the smallest and largest size.
### Example: Resize a note from either side
The note binds width to a field. No edit is declared on it: the grips write the width and the centre with set.
Try: Bring the pointer **near a note** and **drag** a grip on its side.
```javascript
const chart = Elicit({
width: 460, height: 300,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
schema: {
note: { type: "categorical", open: true },
w: { type: "quantitative", domain: [70, 260] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
data: [
{ note: "Drag a grip on my side. The text re-wraps to the width I end up.", w: 170, x: 32, y: 62 },
{ note: "Narrow notes get taller.", w: 100, x: 72, y: 28 },
],
marks: [
sticker({
id: "note",
fill: "#EBD6AD",
stroke: "rgba(70, 89, 107, 0.13)",
maxWidth: 260,
edits: [editText({ multiline: true })],
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
// The width is data, so there is a side to drag. No edit is declared on it.
width: { field: "w", scale: { range: [70, 260] } },
text: { field: "note" },
},
}),
],
});
mount(chart.dom());
ui.attach(chart, [ui.handles({ on: { mark: "note" } })]);
```
`rotate: true` adds a grip above the box that turns it about its centre. It writes the mark's `angle` field, through the `angle` scale when there is one. Hold Shift to turn in steps of 15°. `move: true` adds a grip below the box that moves it, writing its `x` and `y` fields. Both grips turn with the box, and the arrow keys step a focused grip.
### Example: Turn and move a note
The note binds its tilt to a field. The grips write the tilt and the position with set.
Try: Bring the pointer **near a note**. **Drag** the grip above it to turn it, and the grip below it to move it. Hold **Shift** while turning to snap to 15°.
```javascript
const chart = Elicit({
width: 460, height: 300,
margins: { top: 20, right: 20, bottom: 20, left: 20 },
axes: false,
schema: {
note: { type: "categorical", open: true },
tilt: { type: "quantitative", domain: [-180, 180] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
data: [
{ note: "Turn me with the grip above.", tilt: 8, x: 30, y: 62 },
{ note: "Move me with the grip below.", tilt: -6, x: 70, y: 34 },
],
marks: [
sticker({
id: "note",
fill: "#EBD6AD",
stroke: "rgba(70, 89, 107, 0.13)",
maxWidth: 150,
channels: {
x: { field: "x" },
y: { field: "y" },
// The tilt is data, in degrees counter-clockwise, so there is something to turn.
angle: { field: "tilt", scale: { range: [-180, 180] } },
text: { field: "note" },
},
}),
],
});
mount(chart.dom());
ui.attach(chart, [ui.handles({ on: { mark: "note" }, rotate: true, move: true })]);
```
## A part of your own
`ui.custom(mount)` is a part you write. `mount(ctx)` builds it and may return a teardown. `ctx.chart` is the chart, read through [`scene`, `hit`, `scale` and `edits`](https://elicitjs.github.io/editing/external-controls.md#reading). `ctx.layer` is the element everything goes in. The helpers on `ctx` release what they register when the layer detaches:
- `ctx.place(el, anchor, placement)` keeps an element on a point or a drawn piece, on every render.
- `ctx.button(options)`, `ctx.menu(items, at)` and `ctx.icon(icon)` build the layer's own controls.
- `ctx.onPointer(cb)` reports the pointer in plot pixels, and a right-click as `"menu"`.
- `ctx.drag(el, handlers)` makes an element a drag source.
- `ctx.capture(handlers)` takes the chart's next press, for a two-step action.
The built-in parts use only this context and the chart's public methods.
### Example: A stepper over the hovered bar
A custom part: two buttons that follow the bar under the pointer and write its value with set.
Try: Move over a bar and press **−** or **+**. **Drag** a bar as usual.
```javascript
const chart = Elicit({
width: 440, height: 280,
margins: { top: 30, right: 20, bottom: 40, left: 44 },
schema: {
quarter: { type: "categorical", domain: ["Q1", "Q2", "Q3", "Q4"] },
n: { type: "quantitative", domain: [0, 100] },
},
data: [
{ quarter: "Q1", n: 40 }, { quarter: "Q2", n: 62 },
{ quarter: "Q3", n: 55 }, { quarter: "Q4", n: 71 },
],
constraints: [clamp({ field: "n", min: 0, max: 100 })],
marks: [
barY({ id: "bar", channels: { x: { field: "quarter" }, y: { field: "n", edit: move() } } }),
],
});
mount(chart.dom());
// A part of your own: a stepper over the bar the pointer is on.
const stepper = ui.custom((ctx) => {
const { chart } = ctx;
const box = document.createElement("div");
box.style.cssText = "display:flex;gap:4px;pointer-events:none";
let row = null;
const step = (by) => () => {
if (row == null) return;
// No edit needed for a value: set runs the clamp and is one undo step.
chart.set("n", chart.getData()[row].n + by, { index: row });
};
const minus = ctx.button({ icon: " ", label: "Five fewer", onClick: step(-5) });
const plus = ctx.button({ icon: "plus", label: "Five more", onClick: step(5) });
box.append(minus, plus);
// Keep the box above the bar's top. scene() is read again on every render.
ctx.place(box, () => (row == null ? null : chart.scene({ mark: "bar", index: row })[0]), { at: "top", offset: 6 });
ctx.onPointer((e) => {
if (e.type === "leave") row = null;
if (e.type === "move") {
const view = chart.hit(e.point, { reach: 30 });
row = view && view.mark === "bar" ? view.index : null;
}
ctx.refresh();
});
});
ui.attach(chart, [stepper]);
```
## Theme, icons and CSS
The layer takes its colours and sizes from `theme.ui`: `surface`, `ink`, `muted`, `border`, `accent`, `danger`, `shadow`, `radius`, `size`, `gap` and `fontSize`. Set them in [`spec.theme`](https://elicitjs.github.io/theming.md) like any other token.
```js
Elicit({ ...spec, theme: { ui: { accent: "#7c3aed", size: 26 } } });
```
The tokens reach the page as CSS variables on the layer (`--elicit-ui-accent`, `--elicit-ui-size`, …), and every control has a class: `elicit-ui-button`, `elicit-ui-menu`, `elicit-ui-item`, `elicit-ui-handle`. Override either from your own stylesheet.
An `icon` is a built-in name (`plus`, `link`, `unlink`, `trash`, `swap`, `palette`, `grip`, `check`), SVG markup or an element. `authoring.registerIcon(name, path)` adds a name, from path data on a 16 × 16 grid.
---
# Network UI
> Source: https://elicitjs.github.io/ui/network/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
`ui.network()` is the [UI layer](https://elicitjs.github.io/ui.md) for a node-link chart. Beside a port, **+** adds a linked node and two more icons connect and detach. A link carries icons to reverse it, put a node on it, and remove it. A right-click menu covers the plane, the nodes and the links, and a node that sizes from data gets resize grips. Each piece appears where the spec names the edit behind it.
## API reference
### `ui.network(options?)`
The UI a node-link chart needs, built from the edits its spec names. It works on a dataset with `structure: "network"`; any other logs a warning.
No JSON form: this is called in JavaScript.
```ts
ui.attach(chart, [ui.network()])
ui.network({ links: false, menu: { channel: "stroke" } })
ui.network({ edits: { unlink: "cut" } })
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `ports` | `boolean` | `true` | Icons beside a port: + adds a node on that side, linked from this one; the link icon connects to a node already there; detach shows where a link is docked. |
| `links` | `boolean` | `true` | Icons beside a link, where the pointer meets it: reverse, + to put a new node on it there, and remove. |
| `menu` | `boolean \| { channel }` | `true` | The right-click menu. `channel` names the node channel its categories come from; the default is a categorical `fill`. |
| `resize` | `boolean` | `true` | Grips on a node mark that binds `width` or `height` to a field. |
| `edits` | `{ connect?, rewire?, reverse?, unlink?, remove?, create? }` | `found by what each edit does` | The edit behind each action, by `name`. `unlink` removes a link, `remove` a node and `create` adds a node. |
## A flowchart with its UI
The spec below is an ordinary [network](https://elicitjs.github.io/marks/network.md) of [stickers](https://elicitjs.github.io/marks/sticker.md) with [ports](https://elicitjs.github.io/marks/network.md#ports). Every edit the UI drives has a `name`. `ui.attach(chart, [ui.network()])` finds them by what they do.
### Example: Notes, links and their icons
Grow the board from a port's +, link and detach with the icons beside it, reverse a link, put a node on it or remove it from its icons, add and recolour notes from the menu, resize a note by its grips.
Try: Bring the pointer to the **edge of a note**. **Right-click** the board, a note or a link.
```javascript
const chart = Elicit({
width: 540, height: 380,
margins: { top: 28, right: 28, bottom: 28, left: 28 },
axes: false,
schema: {
structure: "network",
tables: {
steps: {
role: "nodes",
fields: {
id: { type: "categorical", key: true, open: true },
label: { type: "categorical", open: true },
kind: { type: "categorical", domain: ["idea", "task", "risk"] },
w: { type: "quantitative", domain: [80, 240] },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
},
flows: {
role: "links",
directed: true,
fields: {
source: { type: "ref" },
target: { type: "ref" },
fromSide: { type: "categorical", domain: ["top", "right", "bottom", "left"] },
toSide: { type: "categorical", domain: ["top", "right", "bottom", "left"] },
},
},
},
},
data: {
steps: [
{ id: "s1", label: "Draft the question", kind: "idea", w: 130, x: 22, y: 80 },
{ id: "s2", label: "Pilot it with five readers", kind: "task", w: 130, x: 74, y: 58 },
{ id: "s3", label: "Nobody answers", kind: "risk", w: 110, x: 30, y: 20 },
],
flows: [{ source: "s1", target: "s2", fromSide: "right", toSide: "left" }],
},
marks: [
link({
id: "flow",
stroke: "#94A5B3",
strokeWidth: 1.5,
channels: { sourceSide: { field: "fromSide" }, targetSide: { field: "toSide" } },
edits: [
edit.network.rewire({ name: "rewire" }),
// gesture: "commit" is a gesture no pointer makes: only the UI fires these.
edit.network.reverse({ name: "reverse", gesture: "commit" }),
remove({ name: "unlink", gesture: "commit" }),
],
}),
sticker({
id: "note",
stroke: "rgba(70, 89, 107, 0.25)",
cornerRadius: 8,
edits: [
editText({ multiline: true }),
create({ name: "add", gesture: "commit", defaults: { label: "New note", w: 110 } }),
remove({ name: "delete", gesture: "commit" }),
],
channels: {
x: { field: "x", edit: move({ channels: ["x", "y"], mode: "relative" }) },
y: { field: "y" },
text: { field: "label" },
fill: { field: "kind", scale: { range: ["#FBE6B0", "#C9E4F6", "#F8CCC6"] } },
width: { field: "w", scale: { range: [80, 240] } },
ports: { value: true, edit: edit.network.connect({ name: "link" }) },
},
}),
],
});
mount(chart.dom());
ui.attach(chart, [ui.network()]);
```
## Add, link and detach at a port
Bring the pointer to a port and up to three icons appear outside the node, on that side. The port they belong to is lit, with the rest of the node's ports.
**+** adds a node on that side and links this port to it. The new node takes this node's category and size, and sits one gap out from the side. Where another node is in the way, or the plot ends, it steps along the side to the nearest free spot. The node and its link are one undo step. Drag the **+** to draw the link yourself: drop it on a node to link to that node, or on empty space to make the new node there.
The **link** icon connects to a node that is already on the board. Drag it to the node, or click it and then click the node. The link follows the pointer until that second click, and Escape cancels. The icon shows only where a new link could land.
At a port that holds a link, the **detach** icon takes it off. Drag the icon to re-point that end of the link to another node. Click it to remove the link. With several links at the port, the click lists them and you choose one.
## Reverse, split and remove a link
Bring the pointer to a link and its icons appear beside it, where the pointer met it. The link's ends are lit. Reverse swaps the link's direction, and each node keeps the port the link meets it at. **+** puts a new node on the link where the pointer met it: the link now ends at the new node, and a new link runs on to where the old one went, at the same port. The new node takes the category and size of the node the link comes from, and the change is one undo step. The bin removes the link. The right-click menu on a link offers reverse and remove.
## Reaching the icons
Icons stay while the pointer travels to them, and for a moment after it leaves what they belong to. One set shows at a time: near a port, the port's icons replace a link's.
## Add, recategorise and remove from the menu
Right-click empty space to add a node there. When the node mark binds `fill` to a categorical field, the menu lists the categories, and the new node takes the one you choose as a single undo step. Right-click a node to change its category or remove it. Removing a node removes its links.
`menu: { channel }` names another channel for the categories, and `menu: false` leaves the menu out.
## Resize a node
A node mark that binds `width` or `height` to a field gets [resize grips](https://elicitjs.github.io/ui.md#handles). A port sits in the middle of each side, so the grips take the corners below it.
## What the spec declares
Each action needs one named edit. An action whose edit is missing is left out; an edit that is there with no `name` logs a warning.
| Action | Edit | Where it goes | | --- | --- | --- | | **+** beside a port | `edit.network.connect({ name })` and `create({ name })` | the `ports` channel; the node mark | | Link icon beside a port | `edit.network.connect({ name })` | the node mark's `ports` channel | | Detach by dragging | `edit.network.rewire({ name })` | the `link` mark | | Detach by clicking, remove a link | `remove({ name })` | the `link` mark | | Reverse a link | `edit.network.reverse({ name })` | the `link` mark | | **+** on a link | `create({ name })`, `edit.network.connect({ name })` and `edit.network.rewire({ name })` | the node mark, its `ports` channel, the `link` mark | | Add a node | `create({ name })` | the node mark | | Remove a node | `remove({ name })` | the node mark | | A node's category | none | a categorical `fill` on the node mark | | Resize a node | none | a field on `width` or `height` |
`gesture: "commit"` on `create`, `remove` and `reverse` keeps them for the UI, so a plain click on the board adds and removes nothing. `ui.network({ edits: { connect, rewire, reverse, unlink, remove, create } })` names an edit yourself where the chart has several of a kind.
---
# Theming & style
> Source: https://elicitjs.github.io/theming/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
The **theme** holds every default colour, font and affordance token. Pass a partial `theme` on `Elicit` or on any widget. It deep-merges over the built-in defaults, so you name only what you change. A per-datum paint channel (`fill`, `stroke`) wins over any theme token. A theme can also set [effects](https://elicitjs.github.io/effects.md) defaults, and `effects` on the spec overrides them. Twenty [named themes](https://elicitjs.github.io/theming/themes.md) ship with the library: `theme: "nyt"` restyles a whole chart from one word.
## API reference
### `theme (on Elicit)`
The style layer, passed as `theme` on `Elicit` (or on any widget). A partial, deep-merged over the built-in `DEFAULT_THEME` — you name only the tokens you change. Precedence, most specific first: a per-datum channel/option `>` `theme.marks[name]` `>` the theme token `>` the renderer default.
```ts
theme: { extends, ink, accent, muted, handle, handleStroke, background, palette, ramp, diverging,
font, title, subtitle, caption, axis, grid, panel, bandPadding, guide, constraint,
effects, ghost, widget, marks }
theme: "nyt" // a named theme — see /theming/themes
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `ink` | `string` | `steelblue` | The primary mark colour — every mark that has no explicit paint channel reads it (bar, point, line, area, rect, …). |
| `accent` | `string` | `#2563eb` | Interactive emphasis: draggable handles, a committed survey answer, an editable-axis handle. |
| `muted` | `string` | `#9ca3af` | Secondary ink — a de-emphasised mark, a supporting label. |
| `handle / handleStroke` | `string` | `#2563eb / #fff` | Grip fill and rim. A `line` or `area` fills its grips with the series’ own colour instead, keeping `handleStroke` as the rim. A mark’s own `handleColor` still wins. |
| `background` | `string \| null` | `null` | The chart backdrop, applied as the svg/canvas CSS background (margin band included). `null` is transparent (the host page shows through); set it for a self-contained dark-mode chart — see `themes.dark`. |
| `palette / ramp / diverging` | `string[]` | `Tableau10 · blues · RdBu` | Colour-scale defaults for a `fill`/`stroke` channel that names no explicit range or scheme. |
| `font` | `{ family, size, labelSize, titleSize }` | `family: null` | Typography. A non-null `family` is emitted on the root svg (and used by the canvas renderer) so every label inherits it; the default null inherits the host page's font. |
| `extends` | `theme name` | | Start from a [named theme](https://elicitjs.github.io/theming/themes.md); the rest of the object deep-merges over it. A bare string (`theme: "nyt"`) is the same as `{ extends: "nyt" }`. |
| `axis` | `{ stroke, strokeWidth, line, tickSize, tickPadding, labelFill, fontSize, fontFamily, fontWeight, labelAngle, labelAlign, labelOffset, titleFill, titleFontSize, titleFontWeight, titlePadding, titleAnchor, handle, discrete, continuous }` | `grey spine, 6px ticks` | Axis chrome. Each token is also an [`axis()` option](https://elicitjs.github.io/marks/axes.md#styling) of the same name, and the option wins. `line: false` drops the spine; `tickSize: 0` the ticks. `discrete` and `continuous` override any token for axes of that kind — `{ continuous: { line: false } }` drops the value-axis spine and keeps the category one. |
| `grid` | `{ stroke, strokeWidth, strokeDash, opacity, show, zero, bandPosition }` | `show: "none"` | Gridline paint, and which implicit axes get a grid you did not ask for: `"none"`, `"value"` (the axis the value runs along), `"continuous"` or `"all"`. `zero` draws an emphasised line at 0, `{ stroke, strokeWidth, strokeDash }`. |
| `panel` | `{ fill, stroke, strokeWidth }` | `none` | The plot area’s own surface, under the grid, and a frame around it. `background` covers the margins too. |
| `bandPadding` | `number` | `0.1` | The gap between bars on a band axis, as a fraction of the step. A channel’s `scale: { padding }` wins. |
| `guide` | `{ rule, region, legend, bounds, catchment, track }` | `neutral greys` | Guide paint. A dash pattern is spelled `strokeDash`, e.g. `guide: { rule: { strokeDash: "5 4" } }`. `legend` also takes `swatchSize`, `gap`, `swatchRadius` (half the size for round chips) and `titleFontWeight`. |
| `title / subtitle / caption` | `{ fill, fontSize, fontWeight, fontFamily, fontStyle }` | `fontSize 16 (weight 600) / 12 / 11` | Text style of the spec’s [`title`, `subtitle` and `caption`](#titles). A null `fill` (the default) takes `axis.labelFill`. |
| `constraint` | `{ color }` | `#e4572e` | The colour an edit’s [guide](https://elicitjs.github.io/guides.md) draws its bounds, catchment and track in. |
| `effects` | `object` | `outline + dim` | Theme-level defaults for the [effects](https://elicitjs.github.io/effects.md) layer. A chart’s own `effects` option layers over it. |
| `ghost` | `{ opacity, fill, stroke, strokeDash }` | `opacity: 0.45` | How a [probe](https://elicitjs.github.io/editing/probe.md) preview is dimmed: a ghost multiplies its opacity by this, and a non-null fill/stroke/dash overrides the committed paint. |
| `widget` | `object` | `survey tokens` | The widget tokens: `design` names how the [widgets](https://elicitjs.github.io/widgets.md#designs) are drawn, and the rest are the colours and sizes that design reads. See [Widgets](https://elicitjs.github.io/widgets.md) for the full list. |
| `marks` | `Record` | `{}` | Sparse per-mark default overrides, keyed by mark name — e.g. `{ bar: { fill: "crimson" } }`. Beyond paint, `bar.cornerRadius` and `rect.cornerRadius` set a corner radius and `point.size` a radius. |
### `themes`
The twenty [named themes](https://elicitjs.github.io/theming/themes.md): `default`, `survey`, `surveyBlocks`, `surveyLines`, `dark` and `dd`, plus fourteen house styles from [Flint](https://github.com/microsoft/flint-chart). Each is a partial — pass it (or its name) as `theme`, or start from one with `extends`.
```ts
themes.default · survey · dark
themes.nyt · economist · bbc · datawrapper
themes.swiss · nature · deStijl
themes.mckinsey · powerbi · powerbiLight
themes.apple · material · pop · cartoon
```
### `setTheme(partial)`
Set the application-wide default theme. Every chart created afterwards inherits it unless it passes its own `theme`, which layers on top. Pass `null` to reset.
No JSON form: this is called in JavaScript.
```ts
setTheme(themes.survey)
setTheme('economist')
setTheme({ ink: '#4f46e5' })
setTheme(null)
```
## A themed instrument
`themes.survey` is a built-in theme for survey widgets. Pass it to any widget to restyle the answer ink and the chrome. The behaviour stays the same. It also sets the widgets' [design](https://elicitjs.github.io/widgets.md#designs): `survey` draws outlined boxes, `surveyBlocks` filled blocks and `surveyLines` hairlines. The widget tokens are `theme.widget`, where `design` names the design and the rest are the colours and sizes it reads.
### Example: The survey theme
One object — themes.survey — restyles the ink, the chrome and the design.
Try: move across the options, click to answer — the look is the only change.
```javascript
// One object restyles the whole instrument: answer ink, chrome, and the
// affordance rings/track/labels all follow themes.survey.
const chart = Elicit(widgets.likert({
question: "How satisfied are you with the result?",
options: ["Very low", "Low", "Neutral", "High", "Very high"],
theme: themes.survey,
}));
mount(chart.dom());
```
## Dark mode
The `background` token paints the chart's own surface, margins included. `themes.dark` uses it with light ink, light labels and a slate grid, so it needs no host CSS. The same spec renders light or dark by changing only the `theme`.
### Example: themes.dark
A slate backdrop with light ink and chrome — the chart paints its own surface.
Try: drag a bar — the interaction is identical, only the palette is dark.
```javascript
// themes.dark carries a `background` token, so the chart paints its own dark
// surface — light ink, light labels, slate grid, no host CSS required. The same
// spec renders identically light or dark; only the theme changes.
const chart = Elicit({
width: 440, height: 240,
margins: { top: 20, right: 20, bottom: 30, left: 36 },
data: [{ cat: "A", n: 30 }, { cat: "B", n: 55 }, { cat: "C", n: 40 }, { cat: "D", n: 22 }],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
theme: themes.dark,
axes: { x: {}, y: { grid: true } },
marks: [
barY({ channels: { x: { field: "cat" }, y: { field: "n", edit: move() } } }),
],
});
mount(chart.dom());
```
## A theme on a plain chart
A theme is a plain object, so it deep-merges cleanly. `ink` is the primary mark colour, used by every mark with no paint channel of its own. `axis` and `grid` style the chrome. A token you name changes, and a token you leave out keeps its default.
### Example: Per-chart theme
ink recolours the bars; axis/grid restyle the chrome. Drag a bar — the value axis still works.
Try: drag a bar up or down.
```javascript
// A theme on a plain chart. `ink` recolours every mark that has no explicit
// paint channel; `axis`/`grid` restyle the chrome. A partial — you name only
// the tokens you change, the rest inherit the default.
const chart = Elicit({
width: 440, height: 240,
margins: { top: 20, right: 20, bottom: 30, left: 36 },
data: [{ cat: "A", n: 30 }, { cat: "B", n: 55 }, { cat: "C", n: 40 }, { cat: "D", n: 22 }],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
theme: {
ink: "#EE7B5E",
axis: { stroke: "#BCC9D4", labelFill: "#6F8294" },
grid: { stroke: "#EDF7F8" },
},
axes: { x: {}, y: { grid: true } },
marks: [
barY({ channels: { x: { field: "cat" }, y: { field: "n", edit: move() } } }),
],
});
mount(chart.dom());
```
## Axes, grids and the plot panel
The `axis` tokens style every axis: `stroke` and `strokeWidth` for the spine and ticks, `line: false` to drop the spine, `tickSize` (0 for none) and `tickPadding` for the gap to the label, `labelAngle` to turn the labels. Each is also an [`axis()` option](https://elicitjs.github.io/marks/axes.md#styling), and the option wins. `grid.show` adds gridlines without a `grid()` element. `panel` paints the plot area under the grid and can frame it; `background` covers the margins too. `bandPadding` sets the gap between bars.
### Example: A grey panel, white gridlines
panel, grid, axis and bandPadding tokens, and nothing else.
Try: drag a bar.
```javascript
// The ggplot2 look from tokens alone: a grey panel under white gridlines,
// no spines or ticks, and wider gaps between the bars.
const chart = Elicit({
width: 440, height: 260,
theme: {
panel: { fill: "#EAF0F4" },
grid: { stroke: "#ffffff", strokeWidth: 1.2, show: "all" },
axis: { line: false, tickSize: 3, stroke: "#14283A", labelFill: "#46596B" },
bandPadding: 0.35,
ink: "#46596B",
},
data: [{ cat: "A", n: 30 }, { cat: "B", n: 55 }, { cat: "C", n: 40 }, { cat: "D", n: 22 }],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
axes: { y: { title: "count" } },
marks: [barY({ channels: { x: { field: "cat" }, y: { field: "n", edit: move() } } })],
});
mount(chart.dom());
```
`axis.discrete` and `axis.continuous` override any axis token for axes of that kind. Use them to drop the spine on the value axis and keep it under the categories. `grid.show: "value"` grids the axis the value runs along: the continuous one, or y when both are. `grid.zero` draws an emphasised line at 0.
### Example: Per-kind axes and a zero rule
A spine under the categories, none on the values, a dotted value grid and a rule at 0.
Try: drag Q2 above zero.
```javascript
// `axis.discrete` / `axis.continuous` style each KIND of axis apart: a spine
// under the categories, none on the values, a dotted value grid and a rule at 0.
const chart = Elicit({
width: 440, height: 260,
theme: {
axis: {
tickSize: 0, tickPadding: 6,
discrete: { line: true, stroke: "#20555A" },
continuous: { line: false },
},
grid: { show: "value", strokeDash: "1 3", stroke: "#94A5B3", zero: { stroke: "#20555A", strokeWidth: 1.5 } },
},
data: [{ q: "Q1", d: 12 }, { q: "Q2", d: -8 }, { q: "Q3", d: 20 }, { q: "Q4", d: 5 }],
schema: {
q: { type: "categorical", domain: ["Q1", "Q2", "Q3", "Q4"] },
d: { type: "quantitative", domain: [-20, 30] },
},
marks: [barY({ channels: { x: { field: "q" }, y: { field: "d", edit: move() } } })],
});
mount(chart.dom());
```
## Typography
`font.family` sets the chart's typeface. `null` inherits the page's. `title`, `subtitle` and `caption` each take `fontFamily`, `fontStyle`, `fontWeight`, `fontSize` and `fill`, so a headline can be a serif over sans-serif labels. The axis takes `fontFamily` and `fontWeight` for its labels and `titleFill`, `titleFontSize` and `titleFontWeight` for its title. A [`text`](https://elicitjs.github.io/marks/text.md) mark takes `fontWeight`, `fontStyle` and `fontFamily`, each a constant or a channel.
### Example: A serif title over sans-serif labels
font, title, subtitle and axis tokens, and a bold text mark.
Try: drag a bar.
```javascript
// Type from the theme: a body family, a serif title, bold axis titles. A text
// mark takes `fontWeight`, `fontStyle` and `fontFamily` per label.
const chart = Elicit({
width: 440, height: 280,
title: "How sure are you?",
subtitle: "Drag each bar to your confidence",
theme: {
font: { family: "'Helvetica Neue', Helvetica, Arial, sans-serif" },
title: { fontFamily: "Georgia, serif", fontSize: 20 },
subtitle: { fontStyle: "italic" },
axis: { titleFontWeight: "bold", titleFill: "#20555A" },
},
axes: { x: false, y: { title: "Confidence (%)" } },
data: [{ claim: "Claim 1", c: 70 }, { claim: "Claim 2", c: 35 }, { claim: "Claim 3", c: 55 }],
schema: {
claim: { type: "categorical", domain: ["Claim 1", "Claim 2", "Claim 3"] },
c: { type: "quantitative", domain: [0, 100] },
},
marks: [
barY({ cornerRadius: 3, channels: { x: { field: "claim" }, y: { field: "c", edit: move() } } }),
text({
dy: -10, fontWeight: "bold", fill: "white",
channels: { x: { field: "claim" }, y: { datum: 0 }, text: { field: "claim" } },
}),
],
});
mount(chart.dom());
```
## Titles and captions
`title`, `subtitle` and `caption` on the `Elicit` spec draw text above and below the plot, left-aligned with it. They reserve space the way a legend does: the chart keeps its declared `width` and `height`, and the plot shrinks to make room. The theme's `title`, `subtitle` and `caption` tokens style them, each with `fill`, `fontSize`, `fontWeight`, `fontFamily` and `fontStyle` (see [Typography](#typography)). A token with no `fill` takes the axis label colour, so the titles follow a dark theme.
### Example: A titled chart with a caption
title, subtitle and caption on the spec; theme.title and theme.caption recolour two of them.
Try: drag a bar — the plot sits between the title block and the caption.
```javascript
const chart = Elicit({
width: 440, height: 260,
margins: { top: 12, right: 40, bottom: 12, left: 56 },
title: "How will the vote split?",
subtitle: "Drag each bar to your estimate",
caption: "Shares in percent; they need not sum to 100.",
// Title tokens restyle all three; omitted ones keep their defaults.
theme: { title: { fill: "#50AEB7" }, caption: { fill: "#6F8294" } },
axes: { x: false },
data: [{ party: "Left", n: 38 }, { party: "Centre", n: 24 }, { party: "Right", n: 33 }],
schema: {
party: { type: "categorical", domain: ["Left", "Centre", "Right"] },
n: { type: "quantitative", domain: [0, 60] },
},
marks: [
barX({
fill: "#50AEB7",
channels: {
y: { field: "party", scale: { reverse: true } },
x: { field: "n", edit: move() },
},
}),
text({
dx: 6, textAnchor: "start", fontSize: 12, format: ".0f",
channels: { y: { field: "party" }, x: { field: "n" }, text: { field: "n" } },
}),
],
});
mount(chart.dom());
```
## Overrides & precedence
The most specific setting wins. A per-datum channel or mark option beats `theme.marks[name]`, which beats the theme token (`ink`), which beats the renderer default. A theme sets the overall look, and a single mark can still override it.
### Example: Per-mark override
ink colours the bars; theme.marks.point overrides just the dots.
Try: drag a dot — its colour comes from theme.marks.point, not ink.
```javascript
// Precedence, most specific first: a per-datum channel > theme.marks[name] >
// the theme token > the renderer default. Here `ink` colours the bars, but
// theme.marks.point overrides just the dots — and a channel would still win.
const chart = Elicit({
width: 440, height: 240,
margins: { top: 20, right: 20, bottom: 30, left: 36 },
data: [{ cat: "A", n: 30 }, { cat: "B", n: 55 }, { cat: "C", n: 40 }, { cat: "D", n: 22 }],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 60] },
},
theme: {
ink: "#2B5D87",
marks: { point: { fill: "#F2B94B" } },
},
marks: [
barY({ channels: { x: { field: "cat" }, y: { field: "n" } } }),
point({
size: 6,
channels: { x: { field: "cat" }, y: { field: "n", edit: move() } },
}),
],
});
mount(chart.dom());
```
## App-wide defaults
Call `setTheme(partial)` once at startup to theme a whole application. Every chart built afterwards inherits it, and a chart's own `theme` layers on top. `setTheme(themes.survey)` makes the survey look the default. `setTheme(null)` resets to the built-in theme.
```js
export const setTheme = globalThis.__llms.comp("setTheme");
export const themes = globalThis.__llms.comp("themes");
setTheme(themes.survey); // app-wide default
// …every Elicit(...) after this inherits it
setTheme("economist"); // or a named theme by name
setTheme({ ink: "#4f46e5" }); // or just a token or two
```
---
# Named themes
> Source: https://elicitjs.github.io/theming/themes/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A **named theme** restyles a whole chart from one word: `theme: "nyt"`. There are twenty. Fourteen are the house styles of [Flint](https://github.com/microsoft/flint-chart), Microsoft's chart grammar, transcribed from its presets. `default`, `survey`, `surveyBlocks`, `surveyLines`, `dark` and `dd` are Elicit.js's own. The three survey themes also set the [design](https://elicitjs.github.io/widgets.md#designs) the widgets are drawn in. Each is a partial [theme](https://elicitjs.github.io/theming.md), so a chart can start from one and change any token.
## Using a named theme
Pass the name as `theme`, or the object from `themes`. `theme: "nyt"` and `theme: themes.nyt` are the same. `setTheme("nyt")` makes it the default for every chart built afterwards.
A named theme sets the surface, the ink and palettes, the fonts of the labels and the title, which axes draw a spine and ticks, which get gridlines, the zero line, the band padding, corner radii, line widths, point size, and the colour of the hover and selection outline. Anything you place yourself stays where you put it.
### Example: theme: "nyt"
A serif headline over sans-serif labels, no value-axis spine, a quiet grid and a rule at zero.
Try: drag a dot after 2024.
```javascript
// A built-in theme by NAME. `theme: themes.nyt` is the same thing.
const chart = Elicit({
width: 480, height: 300,
theme: "nyt",
title: "Where will unemployment go next?",
subtitle: "Rate, %. Drag the dots after 2024 to your forecast.",
caption: "Up to 2024 is observed; the rest is yours.",
context: (d) => d.year <= 2024,
data: [
{ year: 2020, rate: 8.1 }, { year: 2021, rate: 5.4 }, { year: 2022, rate: 3.6 },
{ year: 2023, rate: 3.6 }, { year: 2024, rate: 4.0 },
{ year: 2025, rate: 4.2 }, { year: 2026, rate: 4.4 }, { year: 2027, rate: 4.5 },
],
schema: {
year: { type: "quantitative", domain: [2020, 2027] },
rate: { type: "quantitative", domain: [0, 10] },
},
// Ticks clear of the corner, where the two axes' end labels would meet.
axes: { x: { tickFormat: "d", tickValues: [2021, 2023, 2025, 2027] } },
marks: [
lineY({ channels: { x: { field: "year" }, y: { field: "rate" } } }),
point({ channels: { x: { field: "year" }, y: { field: "rate", edit: move() } } }),
],
});
mount(chart.dom());
```
## Newsroom
`nyt`, `economist`, `bbc` and `datawrapper` are editorial styles. They drop the value-axis spine and ticks, keep a light value grid, and draw a rule at zero. `nyt` sets its headline in Georgia. `economist` uses a blue-grey grid and tighter bars. `bbc` uses large type, a four-colour palette and a heavy zero rule. `datawrapper` uses Roboto and a light solid grid.
### Example: nyt · economist · bbc · datawrapper
The same grouped bar chart under each newsroom theme.
Try: drag any bar — every theme keeps the same gesture.
```javascript
// One chart, drawn under each theme. Only `theme` changes.
const chart = (theme) => Elicit({
width: 320, height: 240, theme,
title: theme,
subtitle: "Chance of each outcome, %",
data: [
{ outcome: "Rain", who: "You", p: 40 }, { outcome: "Rain", who: "Experts", p: 55 },
{ outcome: "Sun", who: "You", p: 35 }, { outcome: "Sun", who: "Experts", p: 30 },
{ outcome: "Snow", who: "You", p: 25 }, { outcome: "Snow", who: "Experts", p: 15 },
],
schema: {
outcome: { type: "categorical", domain: ["Rain", "Sun", "Snow"] },
who: { type: "categorical", domain: ["You", "Experts"] },
p: { type: "quantitative", domain: [0, 60] },
},
marks: [
barY({
channels: {
x: { field: "outcome" }, xOffset: { field: "who" },
y: { field: "p", edit: move() },
fill: { field: "who", legend: { anchor: "top", title: false } },
},
}),
],
});
const row = document.createElement("div");
row.style.cssText = "display:flex;flex-wrap:wrap;gap:20px;max-width:680px";
for (const name of ["nyt", "economist", "bbc", "datawrapper"]) row.append(chart(name).dom());
mount(row);
```
## Print and science
`swiss` is the International Typographic Style: warm paper, black spines, short outward ticks on the value axis, one signal red. `nature` is the journal figure: black Arial, full spines with long ticks, no gridlines, and the Okabe–Ito colours. `deStijl` uses red, yellow and blue on off-white, heavy black value gridlines, and an italic Futura title.
### Example: swiss · nature · deStijl
Typographic, scientific and Neo-Plastic.
Try: drag a bar.
```javascript
// One chart, drawn under each theme. Only `theme` changes.
const chart = (theme) => Elicit({
width: 320, height: 240, theme,
title: theme,
subtitle: "Chance of each outcome, %",
data: [
{ outcome: "Rain", who: "You", p: 40 }, { outcome: "Rain", who: "Experts", p: 55 },
{ outcome: "Sun", who: "You", p: 35 }, { outcome: "Sun", who: "Experts", p: 30 },
{ outcome: "Snow", who: "You", p: 25 }, { outcome: "Snow", who: "Experts", p: 15 },
],
schema: {
outcome: { type: "categorical", domain: ["Rain", "Sun", "Snow"] },
who: { type: "categorical", domain: ["You", "Experts"] },
p: { type: "quantitative", domain: [0, 60] },
},
marks: [
barY({
channels: {
x: { field: "outcome" }, xOffset: { field: "who" },
y: { field: "p", edit: move() },
fill: { field: "who", legend: { anchor: "top", title: false } },
},
}),
],
});
const row = document.createElement("div");
row.style.cssText = "display:flex;flex-wrap:wrap;gap:20px;max-width:680px";
for (const name of ["swiss", "nature", "deStijl"]) row.append(chart(name).dom());
mount(row);
```
## Business
`mckinsey` draws no axes and no gridlines, a near-black primary over electric blues, and a baseline. `powerbiLight` and `powerbi` are the dashboard tile on a white and a near-black canvas: Segoe UI, a quiet grid, bars rounded by 3px. The dark tile's sequential ramp runs from dim to bright, so a higher value is brighter.
### Example: mckinsey · powerbiLight · powerbi
Consulting deck and dashboard tiles.
Try: drag a bar.
```javascript
// One chart, drawn under each theme. Only `theme` changes.
const chart = (theme) => Elicit({
width: 320, height: 240, theme,
title: theme,
subtitle: "Chance of each outcome, %",
data: [
{ outcome: "Rain", who: "You", p: 40 }, { outcome: "Rain", who: "Experts", p: 55 },
{ outcome: "Sun", who: "You", p: 35 }, { outcome: "Sun", who: "Experts", p: 30 },
{ outcome: "Snow", who: "You", p: 25 }, { outcome: "Snow", who: "Experts", p: 15 },
],
schema: {
outcome: { type: "categorical", domain: ["Rain", "Sun", "Snow"] },
who: { type: "categorical", domain: ["You", "Experts"] },
p: { type: "quantitative", domain: [0, 60] },
},
marks: [
barY({
channels: {
x: { field: "outcome" }, xOffset: { field: "who" },
y: { field: "p", edit: move() },
fill: { field: "who", legend: { anchor: "top", title: false } },
},
}),
],
});
const row = document.createElement("div");
row.style.cssText = "display:flex;flex-wrap:wrap;gap:20px;max-width:680px";
for (const name of ["mckinsey", "powerbiLight", "powerbi"]) row.append(chart(name).dom());
mount(row);
```
## Product interfaces
`apple` uses the system colours, no spines or ticks, a hairline grid and bars rounded by 4px. `material` is Material Design 3: a purple-led tonal palette, Google Sans and Roboto, outline-variant gridlines, rounded bars and round legend chips.
### Example: apple · material
Quiet app-interface charts.
Try: drag a bar.
```javascript
// One chart, drawn under each theme. Only `theme` changes.
const chart = (theme) => Elicit({
width: 320, height: 240, theme,
title: theme,
subtitle: "Chance of each outcome, %",
data: [
{ outcome: "Rain", who: "You", p: 40 }, { outcome: "Rain", who: "Experts", p: 55 },
{ outcome: "Sun", who: "You", p: 35 }, { outcome: "Sun", who: "Experts", p: 30 },
{ outcome: "Snow", who: "You", p: 25 }, { outcome: "Snow", who: "Experts", p: 15 },
],
schema: {
outcome: { type: "categorical", domain: ["Rain", "Sun", "Snow"] },
who: { type: "categorical", domain: ["You", "Experts"] },
p: { type: "quantitative", domain: [0, 60] },
},
marks: [
barY({
channels: {
x: { field: "outcome" }, xOffset: { field: "who" },
y: { field: "p", edit: move() },
fill: { field: "who", legend: { anchor: "top", title: false } },
},
}),
],
});
const row = document.createElement("div");
row.style.cssText = "display:flex;flex-wrap:wrap;gap:20px;max-width:680px";
for (const name of ["apple", "material"]) row.append(chart(name).dom());
mount(row);
```
## Playful
`pop` extends `swiss`: process colours on yellow, heavy black spines, thick outlines on every filled mark, oversized points and Arial Black. `cartoon` uses cream paper, a comic typeface, dark outlines, rounded bars, chunky lines and a dashed grid.
### Example: pop · cartoon
Heavy outlines and loud colour.
Try: drag a bar.
```javascript
// One chart, drawn under each theme. Only `theme` changes.
const chart = (theme) => Elicit({
width: 320, height: 240, theme,
title: theme,
subtitle: "Chance of each outcome, %",
data: [
{ outcome: "Rain", who: "You", p: 40 }, { outcome: "Rain", who: "Experts", p: 55 },
{ outcome: "Sun", who: "You", p: 35 }, { outcome: "Sun", who: "Experts", p: 30 },
{ outcome: "Snow", who: "You", p: 25 }, { outcome: "Snow", who: "Experts", p: 15 },
],
schema: {
outcome: { type: "categorical", domain: ["Rain", "Sun", "Snow"] },
who: { type: "categorical", domain: ["You", "Experts"] },
p: { type: "quantitative", domain: [0, 60] },
},
marks: [
barY({
channels: {
x: { field: "outcome" }, xOffset: { field: "who" },
y: { field: "p", edit: move() },
fill: { field: "who", legend: { anchor: "top", title: false } },
},
}),
],
});
const row = document.createElement("div");
row.style.cssText = "display:flex;flex-wrap:wrap;gap:20px;max-width:680px";
for (const name of ["pop", "cartoon"]) row.append(chart(name).dom());
mount(row);
```
## Elicit.js's own
`default` is the built-in look. `survey` restyles the [survey widgets](https://elicitjs.github.io/widgets.md) with an indigo accent and Inter. `dark` paints its own slate surface, so it reads on a dark page with no host CSS. `dd` is the Data & Dialogue Lab theme: the lab's teal as the ink, its blue for handles and answers, then coral, gold, violet, leaf and rose for categories. Shapes carry no stroke, and a stroke that does appear is the same hue a step darker. Every chart on this site is drawn with it.
The palette is also available as colour schemes: `scheme: "dd"` for categories, `"ddramp"` for a sequential channel and `"dddiverging"` for a diverging one.
### Example: dd · survey · dark
Elicit.js's own looks, side by side.
Try: drag a bar.
```javascript
// One chart, drawn under each theme. Only `theme` changes.
const chart = (name) => Elicit({
width: 320, height: 240,
// The dark surface needs light categories; the others keep the site palette.
theme: name === "dark" ? { extends: "dark", palette: ["#50AEB7", "#F2B94B"] } : name,
title: name,
subtitle: "Chance of each outcome, %",
data: [
{ outcome: "Rain", who: "You", p: 40 }, { outcome: "Rain", who: "Experts", p: 55 },
{ outcome: "Sun", who: "You", p: 35 }, { outcome: "Sun", who: "Experts", p: 30 },
{ outcome: "Snow", who: "You", p: 25 }, { outcome: "Snow", who: "Experts", p: 15 },
],
schema: {
outcome: { type: "categorical", domain: ["Rain", "Sun", "Snow"] },
who: { type: "categorical", domain: ["You", "Experts"] },
p: { type: "quantitative", domain: [0, 60] },
},
marks: [
barY({
channels: {
x: { field: "outcome" }, xOffset: { field: "who" },
y: { field: "p", edit: move() },
fill: { field: "who", legend: { anchor: "top", title: false } },
},
}),
],
});
const row = document.createElement("div");
row.style.cssText = "display:flex;flex-wrap:wrap;gap:20px;max-width:680px";
for (const name of ["dd", "survey", "dark"]) row.append(chart(name).dom());
mount(row);
```
## Extending a theme
`extends` starts a partial theme from a named one, and the rest of the object deep-merges over it. The name comes from Flint. Use it to keep a house style and change its colour, a radius or a font.
### Example: { extends: "swiss", … }
Swiss, with a blue ink, rounded bars and an italic title.
Try: drag a bar.
```javascript
// Start from a named theme and change what you need. `extends` names the base;
// the rest deep-merges over it.
const chart = Elicit({
width: 420, height: 260,
theme: {
extends: "swiss",
ink: "#2B5D87", // Swiss blue instead of signal red
marks: { bar: { cornerRadius: 2 } },
title: { fontStyle: "italic" },
},
title: "Budget split",
subtitle: "Drag each bar to your estimate, %",
data: [{ line: "Staff", v: 45 }, { line: "Rent", v: 25 }, { line: "Tools", v: 30 }],
schema: {
line: { type: "categorical", domain: ["Staff", "Rent", "Tools"] },
v: { type: "quantitative", domain: [0, 60] },
},
marks: [barY({ channels: { x: { field: "line" }, y: { field: "v", edit: move() } } })],
});
mount(chart.dom());
```
## What carries over from Flint
Each preset keeps Flint's colours, font stacks, weights and proportions. Flint's `bandFraction` becomes `bandPadding` (one minus it), a point's area becomes a radius, and its presence words become tokens: `omit` turns a spine off or sets `tickSize: 0`, and a value-axis grid becomes `grid.show: "continuous"`. Flint names type sizes with tokens (`text.100` to `text.500`), which these themes set as 11 to 24 px.
Some parts of a Flint theme are layout, which Elicit.js leaves to the spec: data labels on marks, series names at line ends, a value axis on the right, and furniture such as The Economist's red tab or the BBC's footer rule. Draw those with marks and [guides](https://elicitjs.github.io/guides.md) where you need them.
Flint is MIT-licensed. Its theme specification is at [docs/theme-spec.md](https://github.com/microsoft/flint-chart/blob/main/docs/theme-spec.md), and its theme gallery at [microsoft.github.io/flint-chart](https://microsoft.github.io/flint-chart/#/themes).
---
# Looks
> Source: https://elicitjs.github.io/looks/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A **look** changes how the finished chart is drawn: by hand with `looks.rough()`, or through a shader with `looks.sketch()`, `looks.cartoon()`, `looks.halftone()` and `looks.custom()`. Set them in `looks: [...]` on the `Elicit` spec. A look changes no data, scale or gesture. Looks are experimental, so their names and options may change.
## API reference
### `looks (on Elicit) · experimental`
Import `looks` from `elicitjs` and pass in the chart’s `looks: [...]`. A look changes how the chart is drawn and nothing else. `rough` draws in both renderers; the others are shaders and need `CanvasRenderer`.
JSON keyword: `looks.rough`, `looks.sketch`, `looks.cartoon`, `looks.halftone`, `looks.custom`
```ts
looks.rough({ scope?, roughness?, fill?, seed? }) → Look
looks.sketch({ scope?, amount?, grain?, seed? }) → Look
looks.cartoon({ scope?, levels?, outline?, ink? }) → Look
looks.halftone({ scope?, size?, angle? }) → Look
looks.custom(fragment, { scope?, uniforms?, seed? }) → Look
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `scope` | `'marks' \| 'frame'` | `'marks'` | What the look covers: the marks that draw data, or the whole chart. |
| `rough.roughness` | `number` | `1` | How far the pen strays, 0 to 3. 0 draws true lines. |
| `rough.fill` | `'hachure' \| 'solid'` | `'hachure'` | How a mark's fill is drawn: hatched with lines, or filled. |
| `rough.seed / sketch.seed / custom.seed` | `number` | `1` | Picks the randomness. The same seed draws the same chart. A custom shader reads it as `u_seed`. |
| `sketch.amount` | `number` | `1.2` | How far lines wobble, 0 to 2. |
| `sketch.grain` | `number` | `0.25` | The strength of the pencil grain, 0 to 1. |
| `cartoon.levels` | `number` | `4` | Steps of colour per channel, 2 to 16. |
| `cartoon.outline` | `number` | `1` | The strength of the ink line, 0 to 1. |
| `cartoon.ink` | `string` | `near-black` | The ink line's colour. |
| `halftone.size` | `number` | `5` | The distance between dots in px, 2 to 40. |
| `halftone.angle` | `number` | `30` | The angle of the dot screen, in degrees. |
| `custom fragment` | `string` | | GLSL ES 1.00 source that defines `vec4 look(vec2 uv)`. |
| `custom.uniforms` | `{ [name]: number \| number[] }` | | Numbers the fragment reads by name. A number is a `float`; two to four numbers are a `vec2`, `vec3` or `vec4`. |
## Drawn by hand
`looks.rough()` redraws each shape with a pen that wobbles. Lines are drawn twice, corners overshoot, and a mark's fill is hatched. It draws in both [renderers](https://elicitjs.github.io/renderers.md).
Each shape keeps its true outline for the pointer, so a drag grabs a bar where it sits. `roughness` sets how far the pen strays, from 0 to 3. `fill: "solid"` fills a mark with colour in place of hatching. `seed` picks another hand, and the same seed draws the same chart every time.
### Example: A hand-drawn bar chart
looks: [looks.rough()]. The bars are hatched and their edges wobble; the drag still reads each bar's true shape.
Try: **Drag** a bar up or down.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
looks: [looks.rough()],
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
barY({
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
fill: { field: "x" },
},
}),
],
});
mount(chart.dom());
```
## What a look covers
`scope` is `"marks"` by default: the look covers the marks that draw data, and axes, labels, legends and guides stay as drawn. `scope: "frame"` covers the whole chart.
`looks.rough()` leaves text as it is in either scope. A shader look with `scope: "frame"` runs over text too, so tick labels wobble or break into dots.
### Example: The whole frame
scope: "frame" redraws the axis lines and ticks with the marks. fill: "solid" fills the dots.
Try: **Drag** a dot. The line follows, redrawn.
```javascript
const points = d3.range(11).map((t) => ({ t, v: 30 + 40 * Math.sin(t / 2) + t * 2 }));
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
// "frame" redraws the axes too. Text stays as it is.
looks: [looks.rough({ scope: "frame", fill: "solid", roughness: 1.5 })],
data: points,
schema: {
t: { type: "quantitative", domain: [0, 10] },
v: { type: "quantitative", domain: [0, 100] },
},
marks: [
lineY({ strokeWidth: 2, curve: "catmullRom", channels: { x: { field: "t" }, y: { field: "v" } } }),
point({ size: 6, channels: { x: { field: "t" }, y: { field: "v", edit: move() } } }),
],
});
mount(chart.dom());
```
## Shader looks
A shader look runs over the chart's pixels once it is painted. It needs the canvas renderer, so set `renderer: "canvas"`. Under SVG the chart draws without the look and logs a warning.
- `looks.sketch()` wobbles and doubles every line and gives fills a pencil grain. `amount` sets the wobble, from 0 to 2, and `grain` the grain, from 0 to 1.
- `looks.cartoon()` flattens colour into `levels` steps and inks an `outline` where colour changes, in the colour `ink`.
- `looks.halftone()` redraws the chart as dots `size` px apart, on a screen turned by `angle` degrees.
`sketch` and `cartoon` move a pixel by less than 4px, so a mark is drawn where the pointer hits it. So does `halftone` up to a `size` of about 5.7. At a larger `size`, a dot can sit more than 4px from its mark, which is further than a press reaches.
### Example: Sketch
looks.sketch() on canvas: wobbling edges and a pencil grain.
Try: **Drag** a bar.
```javascript
const chart = Elicit({
width: 380, height: 260,
renderer: "canvas",
margins: { top: 14, right: 14, bottom: 26, left: 30 },
looks: [looks.sketch()],
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
barY({
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
fill: { field: "x" },
},
}),
],
});
mount(chart.dom());
```
### Example: Cartoon
looks.cartoon(): flat colour and an ink line.
Try: **Drag** a bar.
```javascript
const chart = Elicit({
width: 380, height: 260,
renderer: "canvas",
margins: { top: 14, right: 14, bottom: 26, left: 30 },
looks: [looks.cartoon()],
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
barY({
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
fill: { field: "x" },
},
}),
],
});
mount(chart.dom());
```
### Example: Halftone
looks.halftone(): the marks as a screen of dots. The axes are outside the default scope.
Try: **Drag** a bar.
```javascript
const chart = Elicit({
width: 380, height: 260,
renderer: "canvas",
margins: { top: 14, right: 14, bottom: 26, left: 30 },
looks: [looks.halftone()],
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
barY({
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
fill: { field: "x" },
},
}),
],
});
mount(chart.dom());
```
## Your own shader
`looks.custom(fragment, options)` runs your GLSL. `fragment` is GLSL ES 1.00 source that defines `vec4 look(vec2 uv)`, which returns the pixel at `uv`. Colour is premultiplied by alpha, both in the frame you read and in the pixel you return.
A fragment can read and call:
| Name | Type | What it is |
| --- | --- | --- |
| `u_frame` | `sampler2D` | The painted chart. |
| `u_resolution` | `vec2` | The frame's size in device px. |
| `u_pixelRatio` | `float` | Device px per chart px. |
| `u_seed` | `float` | The `seed` option. |
| `chartPx(uv)` | `vec2` | A `uv` as chart px, whose origin is the top-left corner. |
| `toUv(px)` | `vec2` | Chart px as a `uv`. |
| `hash(p)` | `float` | Noise from 0 to 1 at a `vec2`, a new value at every point. |
| `noise(p)` | `float` | Noise from 0 to 1 at a `vec2`, smooth between whole numbers. |
`uniforms` passes your own numbers under their own names: a number arrives as a `float`, and two to four numbers as a `vec2`, `vec3` or `vec4`.
A fragment that fails to compile is skipped, and the compiler's error is logged. A shader that moves pixels further than 4px draws a mark away from where the pointer hits it.
### Example: A custom shader
looks.custom(fragment, { uniforms }). The fragment shifts each row sideways by its strength uniform and mixes in its tint.
Try: **Edit** `strength` or `tint` in the code.
```javascript
// `look` returns the pixel at uv. This one shifts each row sideways and tints it.
const wave = `
vec4 look(vec2 uv) {
vec2 p = chartPx(uv);
p.x += sin(p.y / 9.0) * strength;
vec4 c = texture2D(u_frame, toUv(p));
return vec4(mix(c.rgb, tint * c.a, 0.3), c.a);
}`;
const chart = Elicit({
width: 380, height: 260,
renderer: "canvas",
margins: { top: 14, right: 14, bottom: 26, left: 30 },
looks: [looks.custom(wave, { uniforms: { strength: 2.5, tint: [1, 0.3, 0.6] } })],
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
barY({
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
fill: { field: "x" },
},
}),
],
});
mount(chart.dom());
```
## Several looks
`looks.rough()` runs first. Shader looks with `scope: "marks"` run next, in list order, and shader looks with `scope: "frame"` run last, in list order.
### Example: Rough, then sketch
The shapes are redrawn by hand, then the frame takes a light wobble and a pencil grain.
Try: **Drag** a bar.
```javascript
const chart = Elicit({
width: 380, height: 260,
renderer: "canvas",
margins: { top: 14, right: 14, bottom: 26, left: 30 },
looks: [
looks.rough({ scope: "frame" }),
looks.sketch({ scope: "frame", amount: 0.5, grain: 0.4 }),
],
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
barY({
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
fill: { field: "x" },
},
}),
],
});
mount(chart.dom());
```
## Faces, emoji and glyphs
A look covers a glyph part by part, and each part keeps its own edit. `looks.rough()` redraws shapes, so it reaches a [`face`](https://elicitjs.github.io/marks/face.md) and a [`composite`](https://elicitjs.github.io/marks/composite.md) glyph, such as the plant from the [glyph case study](https://elicitjs.github.io/case-studies/glyphs.md). An emoji from a [`symbol`](https://elicitjs.github.io/marks/symbol.md) channel is text, so `looks.rough()` leaves it as drawn and a shader look reaches it.
### Example: A face, by hand
looks.rough({ fill: "solid", roughness: 1.6 }) over a face. The head, eyes, brows and mouth are each redrawn.
Try: **Drag** the mouth, an eye or a brow.
```javascript
const chart = Elicit({
width: 340, height: 340,
// Every part is redrawn by hand, and each still takes its own drag.
looks: [looks.rough({ fill: "solid", roughness: 1.6 })],
margins: { top: 12, right: 12, bottom: 12, left: 12 },
data: [ {
curve: 0.7, smirk: 0.5,
aperture: 0.6, squint: 0.2, browH: 0.5, browT: 0.4,
} ],
schema: {
curve: { type: "quantitative", domain: [0, 1] },
smirk: { type: "quantitative", domain: [0, 1] },
aperture: { type: "quantitative", domain: [0, 1] },
squint: { type: "quantitative", domain: [0, 1] },
browH: { type: "quantitative", domain: [0, 1] },
browT: { type: "quantitative", domain: [0, 1] },
},
marks: [
face({
channels: {
// The mouth is one part, so one drag drives both of its params: the
// vertical component bends it, the horizontal one tilts it into a smirk.
mouthCurve: { field: "curve", edit: slide({ axis: "y", increase: "up" }) },
mouthAsym: { field: "smirk", edit: slide({ axis: "x", increase: "right" }) },
// Each eye is one ellipse: rx opens it, ry squints it. Horizontal and
// vertical drag, so one gesture on an eye reads as reshaping it.
eyeScale: { field: "aperture", edit: slide({ axis: "x", increase: "right" }) },
eyeSquint: { field: "squint", edit: slide({ axis: "y", increase: "down" }) },
// Each brow is one tick: height is where it SITS — a positional channel in
// the face's frame, so `move()` inverts straight back through it — and tilt
// is a magnitude, so it slides.
browHeight: { field: "browH", edit: move({ channels: ["y"] }) },
browTilt: { field: "browT", edit: slide({ axis: "x", increase: "right" }) },
},
}),
],
});
mount(chart.dom());
```
### Example: A face, as a cartoon
The same face on canvas under looks.cartoon(): flat colour and an ink line round every part.
Try: **Drag** the mouth, an eye or a brow.
```javascript
const chart = Elicit({
width: 340, height: 340,
renderer: "canvas",
looks: [looks.cartoon()],
margins: { top: 12, right: 12, bottom: 12, left: 12 },
data: [ {
curve: 0.7, smirk: 0.5,
aperture: 0.6, squint: 0.2, browH: 0.5, browT: 0.4,
} ],
schema: {
curve: { type: "quantitative", domain: [0, 1] },
smirk: { type: "quantitative", domain: [0, 1] },
aperture: { type: "quantitative", domain: [0, 1] },
squint: { type: "quantitative", domain: [0, 1] },
browH: { type: "quantitative", domain: [0, 1] },
browT: { type: "quantitative", domain: [0, 1] },
},
marks: [
face({
channels: {
// The mouth is one part, so one drag drives both of its params: the
// vertical component bends it, the horizontal one tilts it into a smirk.
mouthCurve: { field: "curve", edit: slide({ axis: "y", increase: "up" }) },
mouthAsym: { field: "smirk", edit: slide({ axis: "x", increase: "right" }) },
// Each eye is one ellipse: rx opens it, ry squints it. Horizontal and
// vertical drag, so one gesture on an eye reads as reshaping it.
eyeScale: { field: "aperture", edit: slide({ axis: "x", increase: "right" }) },
eyeSquint: { field: "squint", edit: slide({ axis: "y", increase: "down" }) },
// Each brow is one tick: height is where it SITS — a positional channel in
// the face's frame, so `move()` inverts straight back through it — and tilt
// is a magnitude, so it slides.
browHeight: { field: "browH", edit: move({ channels: ["y"] }) },
browTilt: { field: "browT", edit: slide({ axis: "x", increase: "right" }) },
},
}),
],
});
mount(chart.dom());
```
### Example: Emoji, inked
looks.cartoon() over emoji symbols. The axes are outside the default scope and stay as drawn.
Try: **Click** an emoji to cycle its mood.
```javascript
const chart = Elicit({
width: 380, height: 250,
renderer: "canvas",
// An emoji is text, which only a shader look reaches.
looks: [looks.cartoon()],
margins: { top: 16, right: 16, bottom: 30, left: 64 },
data: [
{ day: "Mon", mood: "ok" }, { day: "Tue", mood: "good" },
{ day: "Wed", mood: "bad" }, { day: "Thu", mood: "good" },
{ day: "Fri", mood: "great" },
],
schema: {
day: { type: "categorical", domain: ["Mon","Tue","Wed","Thu","Fri"] },
mood: { type: "ordinal", domain: ["bad","ok","good","great"] },
},
marks: [
point({
size: 15,
channels: {
x: { field: "day" },
y: { field: "mood" },
symbol: {
field: "mood",
scale: { range: ["😢","😐","🙂","😄"] },
edit: cycle(),
},
},
}),
],
});
mount(chart.dom());
```
### Example: Emoji, sketched
looks.sketch({ amount: 2, grain: 0.5 }): the emoji wobble and take a pencil grain.
Try: **Click** an emoji to cycle its mood.
```javascript
const chart = Elicit({
width: 380, height: 250,
renderer: "canvas",
looks: [looks.sketch({ amount: 2, grain: 0.5 })],
margins: { top: 16, right: 16, bottom: 30, left: 64 },
data: [
{ day: "Mon", mood: "ok" }, { day: "Tue", mood: "good" },
{ day: "Wed", mood: "bad" }, { day: "Thu", mood: "good" },
{ day: "Fri", mood: "great" },
],
schema: {
day: { type: "categorical", domain: ["Mon","Tue","Wed","Thu","Fri"] },
mood: { type: "ordinal", domain: ["bad","ok","good","great"] },
},
marks: [
point({
size: 15,
channels: {
x: { field: "day" },
y: { field: "mood" },
symbol: {
field: "mood",
scale: { range: ["😢","😐","🙂","😄"] },
edit: cycle(),
},
},
}),
],
});
mount(chart.dom());
```
### Example: A plant, hatched
The plant glyph from the glyph case study under looks.rough(). Hatching is see-through, so the stem shows behind the flower.
Try: **Drag** the flower up, down or sideways, or a leaf outwards.
```javascript
const chart = Elicit({
width: 320, height: 340,
looks: [looks.rough()],
margins: { top: 10, right: 10, bottom: 10, left: 10 },
// How is your week going? Three answers, one plant.
data: [{ energy: 0.5, joy: 0.4, support: 0.5 }],
schema: {
energy: { type: "quantitative", domain: [0, 1] }, // how tall it grows
joy: { type: "quantitative", domain: [0, 1] }, // how big it blooms
support: { type: "quantitative", domain: [0, 1] }, // how full its leaves are
},
marks: [
// Every part is placed in the glyph's own units: x and y run from -1 to 1, y up.
composite({
channels: { size: { value: 150 } },
parts: [
// The stem's top is `energy`; the flower below sits on the same field
// and range, so the two always meet.
ruleX({ channels: {
x: { frame: 0 }, y1: { frame: -0.55 },
y2: { field: "energy", frame: [-0.15, 0.65] },
stroke: { value: "#4d7c0f" }, strokeWidth: { value: 6 },
} }),
// Two leaves. A leaf's centre and its width both read `support`, so its
// inner edge stays on the stem as it grows.
ellipse({ channels: {
x: { field: "support", frame: [-0.08, -0.3] }, y: { frame: -0.3 },
rx: { field: "support", frame: [0.06, 0.28],
edit: slide({ axis: "x", increase: "left" }) },
ry: { frame: 0.07 }, angle: { value: -25 },
fill: { value: "#65a30d" },
} }),
ellipse({ channels: {
x: { field: "support", frame: [0.08, 0.3] }, y: { frame: -0.3 },
rx: { field: "support", frame: [0.06, 0.28],
edit: slide({ axis: "x", increase: "right" }) },
ry: { frame: 0.07 }, angle: { value: 25 },
fill: { value: "#65a30d" },
} }),
// The pot.
rect({ channels: {
x1: { frame: -0.3 }, x2: { frame: 0.3 }, y1: { frame: -0.95 }, y2: { frame: -0.55 },
fill: { value: "#b45309" },
} }),
// The flower: drag it up or down to set `energy`, sideways to set `joy`.
point({ channels: {
y: { field: "energy", frame: [-0.15, 0.65], edit: move({ channels: ["y"] }) },
size: { field: "joy", frame: [0.08, 0.3],
edit: slide({ axis: "x", increase: "right" }) },
fill: { value: "#db2777" },
} }),
point({ channels: {
y: { field: "energy", frame: [-0.15, 0.65] },
size: { field: "joy", frame: [0.03, 0.11] },
fill: { value: "#fde047" },
} }),
],
}),
],
});
mount(chart.dom());
```
### Example: A plant, in dots
The same plant on canvas under looks.halftone({ size: 4 }).
Try: **Drag** the flower or a leaf.
```javascript
const chart = Elicit({
width: 320, height: 340,
renderer: "canvas",
looks: [looks.halftone({ size: 4 })],
margins: { top: 10, right: 10, bottom: 10, left: 10 },
// How is your week going? Three answers, one plant.
data: [{ energy: 0.5, joy: 0.4, support: 0.5 }],
schema: {
energy: { type: "quantitative", domain: [0, 1] }, // how tall it grows
joy: { type: "quantitative", domain: [0, 1] }, // how big it blooms
support: { type: "quantitative", domain: [0, 1] }, // how full its leaves are
},
marks: [
// Every part is placed in the glyph's own units: x and y run from -1 to 1, y up.
composite({
channels: { size: { value: 150 } },
parts: [
// The stem's top is `energy`; the flower below sits on the same field
// and range, so the two always meet.
ruleX({ channels: {
x: { frame: 0 }, y1: { frame: -0.55 },
y2: { field: "energy", frame: [-0.15, 0.65] },
stroke: { value: "#4d7c0f" }, strokeWidth: { value: 6 },
} }),
// Two leaves. A leaf's centre and its width both read `support`, so its
// inner edge stays on the stem as it grows.
ellipse({ channels: {
x: { field: "support", frame: [-0.08, -0.3] }, y: { frame: -0.3 },
rx: { field: "support", frame: [0.06, 0.28],
edit: slide({ axis: "x", increase: "left" }) },
ry: { frame: 0.07 }, angle: { value: -25 },
fill: { value: "#65a30d" },
} }),
ellipse({ channels: {
x: { field: "support", frame: [0.08, 0.3] }, y: { frame: -0.3 },
rx: { field: "support", frame: [0.06, 0.28],
edit: slide({ axis: "x", increase: "right" }) },
ry: { frame: 0.07 }, angle: { value: 25 },
fill: { value: "#65a30d" },
} }),
// The pot.
rect({ channels: {
x1: { frame: -0.3 }, x2: { frame: 0.3 }, y1: { frame: -0.95 }, y2: { frame: -0.55 },
fill: { value: "#b45309" },
} }),
// The flower: drag it up or down to set `energy`, sideways to set `joy`.
point({ channels: {
y: { field: "energy", frame: [-0.15, 0.65], edit: move({ channels: ["y"] }) },
size: { field: "joy", frame: [0.08, 0.3],
edit: slide({ axis: "x", increase: "right" }) },
fill: { value: "#db2777" },
} }),
point({ channels: {
y: { field: "energy", frame: [-0.15, 0.65] },
size: { field: "joy", frame: [0.03, 0.11] },
fill: { value: "#fde047" },
} }),
],
}),
],
});
mount(chart.dom());
```
## Limits
- A shader look reads the chart's pixels. A chart that draws [`geoTile()`](https://elicitjs.github.io/marks/geo.md) tiles from a server without CORS headers draws without its shader looks and logs a warning.
- A browser with no WebGL draws the chart without its shader looks and logs a warning.
- `looks.rough()` leaves text and images as drawn.
---
# Interaction effects
> Source: https://elicitjs.github.io/effects/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
An **effect** is how a mark looks while something happens to its row: the pointer is over it, it is selected, a drag holds it. Set effects in `effects: { ... }` on the `Elicit` spec. They paint over the mark and never change the data, so a data-driven `fill` comes back when the state ends. To draw the rules a gesture obeys, such as a clamp's bounds, see [Guides](https://elicitjs.github.io/guides.md).
## API reference
### `effects (on Elicit)`
The interaction-**state** feedback layer, passed as `effects` on `Elicit`. Keyed by state; partial sub-objects merge over the defaults, so you override just the part you care about. Rules (constraint bounds, a pick’s reach, a handle’s track) are not effects — they live on the edit’s `guide`.
```ts
effects: { hovered, selected, target, grabbed, motion }
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `hovered` | `false \| object` | `outline` | The pointer is over this mark, *or* a proximity pick resolved it. Both routes draw the same thing. `false` disables it. |
| `selected` | `false \| object` | `outline` | The mark is in the chart's selection (edit.select / chart.select). Outranks hovered. |
| `target` | `false \| object` | `outline #2563eb, padding 3` | The container a dragged node would join if released now (see Hierarchy). |
| `grabbed` | `false \| string \| object` | `brightness(0.82)` | A drag on this mark is in flight. A string is shorthand for `{ filter }`. |
| `motion` | `boolean` | `on with a mute, neighbours or a linked hover` | Fade each change of state in and out over the spec’s `motion.duration`. `true` fades every state, `false` none. Off when the spec sets `motion: false` or the reader asks for reduced motion. |
| `.filter` | `string` | | A CSS filter on the mark's own element — the one effect that survives a mid-drag re-render untouched. |
| `.opacity · fill · stroke · strokeWidth · cursor` | `any` | | Element effects, applied as CSS properties so they override the mark's paint while set and are removed cleanly on exit. |
| `.others` | `false \| { opacity, filter, fill, stroke, strokeWidth }` | `— (a linked hover: { opacity: 0.3 })` | The mute: a restyle for every mark in no state, while this state holds on at least one row. `false` turns it off. |
| `.neighbours` | `boolean` | `false` | Network and hierarchy datasets only. The highlight also covers the rows linked to the row in this state: a node's links and the nodes at their other ends, a link's two nodes, and everything nested inside any hierarchy node it lights. |
| `hovered.link` | `true \| 'receive' \| false` | `true with two or more charts on the dataset` | Whether this chart’s hover is the dataset’s. `true` sends it and shows the other charts’ hover. `'receive'` shows theirs and sends none. `false` keeps hover in this chart. |
| `.outline` | `false \| { color, darken, fallback, width, padding, dash, opacity }` | `{ color: 'auto', padding: 0, width: 3 }` | An outline overlay traced on the mark’s edge, above every other layer. Handles every node type — circle, rect, line and path. Text is outlined only when the spec sets `outline`, as a box around the label. `color: 'auto'` reads the mark’s fill (or its stroke, when the fill is missing or near-white) and darkens it by `darken` (0.6 hovered, 1.5 selected; negative lightens). `'fill'` / `'stroke'` pick that paint; a CSS colour fixes it; a function `(color, node) => string` rewrites it. `fallback` paints when nothing can be read. `padding` moves the trace out from the edge. |
Returns / emits: Effects draw either as CSS *properties* on the element or as overlay nodes — never as the `fill`/`stroke` attributes a mark’s channels write — so they can’t clobber data-driven style.
## How highlighting works
Every effect answers four questions. Each has its own option.
| Question | Option | Default | | --- | --- | --- | | Which rows are in a state? | the state: `hovered`, `selected`, `target`, `grabbed` | set by the pointer and the selection | | How does a row in the state look? | the state's own options: restyle props and `outline` | an outline | | How do the other rows look meanwhile? | `others`, the mute | unchanged | | Which rows count as in the state? | `neighbours`, and `hovered.link` across charts | the row itself, in this chart |
A state's own options are its **highlight**. `others` is its **mute**: it restyles every row in no state, for as long as the state holds a row. A row in any state is never muted.
By default, hover lights only the editable mark under the pointer. Set `others` or `neighbours` on `hovered`, or link hover across charts, and hover lights the whole row: every mark that draws it, view-only marks too.
`motion` sits beside the states and fades every change in and out. It is on by default wherever a highlight changes other rows: a mute, `neighbours`, or a linked hover. See [Fade in and out](#motion).
```js
effects: {
hovered: { neighbours: true, others: { opacity: 0.2 } }, // light the row and what it links to, fade the rest
selected: { outline: { width: 4 } },
motion: true, // fade every state, plain hover too
}
```
## The states
`effects` is keyed by state, and every state takes the same options.
**`hovered`** applies when the pointer is over the mark, or when a proximity pick resolves to it. Pointing at a mark and a `pick: "nearest"` edit choosing it draw the same thing.
**`selected`** applies when the mark is in the interface's selection.
**`target`** outlines the container a dragged node would join if you released it now. See [Hierarchy](https://elicitjs.github.io/marks/hierarchy.md). Its default outline is `#2563eb`, padded 3px out from the edge.
**`grabbed`** applies while you drag the mark. Pass a string as shorthand for `{ filter }`.
Set a state to `false` to switch it off.
## Hover on an editable mark
`hovered` applies to every editable mark by default, with or without a `pick`. Point at a draggable bar and it responds before you press.
### Example: A plain draggable bar
A single move() on y. Nothing in the spec asks for hover feedback.
Try: **Move** across the bars without pressing, then **drag** one.
```javascript
const chart = Elicit({
width: 380, height: 240,
margins: { top: 14, right: 14, bottom: 28, left: 34 },
data: [
{ cat: "A", n: 62 }, { cat: "B", n: 38 },
{ cat: "C", n: 81 }, { cat: "D", n: 24 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 100] },
},
marks: [
bar({
channels: {
x: { field: "cat" },
// A plain direct-pick edit: you point straight at the bar. `hovered`
// applies to it like any other editable mark.
y: { field: "n", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## The highlight: restyle and outline
A state's highlight paints in one of two ways, and can use both at once.
**Element props** restyle the mark itself: `filter`, `opacity`, `fill`, `stroke`, `strokeWidth`, `cursor`. They override the mark's own paint while the state holds, and the mark's paint returns when it ends. Every prop paints in both [renderers](https://elicitjs.github.io/renderers.md). On canvas, `filter` needs a browser whose 2D context has `filter`; in any other it logs a warning.
**`outline`** draws an overlay on the mark's edge, above every other layer. It takes `color`, `darken`, `fallback`, `width`, `padding`, `dash` and `opacity`, and traces whatever shape the mark is: a ring on a circle or ellipse, the box on a rect (with its corner radius), the segment on a tick, the path itself on an arc slice, line or polygon. `padding` moves the trace out from the edge, and is 0 by default.
A text label gets no outline by default. The cursor change is its feedback. Set `outline` for a state in `effects` and labels get a box around the text in that state.
The outline's colour comes from the mark. With the default `color: "auto"`, it is the mark's fill, or its stroke when the fill is missing or near-white, darkened by `darken` (0.6 for `hovered`, 1.5 for `selected`; a negative value lightens). A teal bar lights up in deep teal and a coral dot in deep coral. `"fill"` or `"stroke"` reads that paint only. A CSS colour fixes the outline to that colour. A function `(color, node) => string` receives the derived colour and returns the one to paint. `fallback` is used when the mark's paint can't be read, such as a gradient fill.
Element props follow the mark wherever it goes. An outline copies the mark's rotation: rotate a mark with an [`angle` channel](https://elicitjs.github.io/marks/point.md#angle) and its outline turns with it. Proximity picking measures the same rotated shape, so the mark that lights up is the mark a drag grabs.
### Example: Element props, and outline
Left restyles the dot; right leaves it alone and rings it. Both keep the fill the data gives it.
Try: **Hover** both charts. The dots' own colours never change.
```javascript
// Two ways to paint a state, both available on every state.
//
// element props filter / opacity / fill / stroke / strokeWidth / cursor —
// restyle the mark itself, without writing its own paint.
// outline an overlay traced around the mark, above every layer.
//
// Left uses element props, right an outline. The dots keep the fill their `group`
// field gives them in both.
const rows = [
{ x: 22, y: 34, group: "a" },
{ x: 50, y: 66, group: "b" },
{ x: 78, y: 40, group: "a" },
];
const schema = {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
group: { type: "categorical", domain: ["a", "b"] },
};
const dots = () => point({
size: 11,
channels: {
x: { field: "x", edit: move() },
y: { field: "y", edit: move() },
fill: { field: "group" },
},
});
// Element props: the dot brightens and thickens. No overlay.
mount(Elicit({
width: 300, height: 220,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: rows, schema,
effects: {
hovered: { filter: "brightness(1.25)", strokeWidth: 4 },
grabbed: { filter: "brightness(0.8)" },
selected: false,
},
marks: [ dots() ],
}).dom());
// Outline: the dot is untouched, and a ring is drawn around it.
mount(Elicit({
width: 300, height: 220,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: rows, schema,
effects: {
hovered: { outline: { color: "#20555A", width: 2, padding: 7, dash: "3 3", opacity: 0.9 } },
selected: false,
},
marks: [ dots() ],
}).dom());
```
## Hovered and selected together
`selected` outranks `hovered`: a selected mark draws as selected while you hover it. Give the two different weights. `hovered` shows which mark a gesture would take, and `selected` shows which one you picked.
The interface holds the selection, separate from the data: `edit.select` writes no `selected` field. See [Editing a selected item](https://elicitjs.github.io/marks/legend.md#dynamic-target).
### Example: A light hover, a firm selection
Alt-click selects, so a plain click still drags. A shallow shade on hover, a deep thick one on selection.
Try: **Alt-click** a bar to select it, **hover** the others, **drag** any.
```javascript
const chart = Elicit({
width: 380, height: 250,
margins: { top: 14, right: 14, bottom: 28, left: 34 },
data: [
{ cat: "A", n: 62 }, { cat: "B", n: 38 },
{ cat: "C", n: 81 }, { cat: "D", n: 24 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 100] },
},
// Different weights: `hovered` says which bar a gesture would take, `selected`
// says which one you picked. `selected` outranks `hovered`. Both keep the default
// `color: "auto"` (a shade of the bar's own colour); `darken` sets how deep.
effects: {
hovered: { outline: { darken: 0.3, width: 2 } },
selected: { outline: { darken: 2, width: 4 } },
grabbed: { filter: "brightness(0.85)" },
},
marks: [
bar({
channels: { x: { field: "cat" }, y: { field: "n", edit: move() } },
// Selection is pipeline state, not a data column: nothing here writes a
// `selected` field. Alt-click selects, so a plain click still drags.
edits: [ select({ when: when.alt }) ],
}),
],
});
mount(chart.dom());
```
## Highlight and mute
A state's own options are its highlight: how a mark in that state looks. `others` is its mute. It restyles every mark that is in no state, for as long as the state holds on at least one row. It takes the element props `opacity`, `filter`, `fill`, `stroke` and `strokeWidth`.
Every state takes `others`. On `selected` it gives a highlight that stays until you clear the selection.
### Example: Select one, fade the rest
selected keeps its default outline. others fades the unselected bars.
Try: **Click** a bar to select it. Click it again to clear.
```javascript
const chart = Elicit({
width: 380, height: 250,
margins: { top: 14, right: 14, bottom: 28, left: 34 },
data: [
{ cat: "A", n: 62 }, { cat: "B", n: 38 },
{ cat: "C", n: 81 }, { cat: "D", n: 24 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 100] },
},
// `others` styles the bars that are in no state while one bar is selected.
effects: {
selected: { others: { opacity: 0.25 } },
},
marks: [
bar({
channels: { x: { field: "cat" }, y: { field: "n" } },
edits: [ select({ toggle: true }) ],
}),
],
});
mount(chart.dom());
```
Setting `others` on `hovered` makes hover apply to the row: every mark that draws the row lights up, on view-only marks too.
## Neighbours in a network
`neighbours: true` extends a state's highlight to the rows linked to it. Hover a node and its links light up, with the nodes at their other ends. Hover a link and its two nodes light up. In a [hierarchy](https://elicitjs.github.io/marks/hierarchy.md), every node it lights brings everything nested inside it, so a container lit across a link lights its contents too.
`neighbours` applies to network and hierarchy datasets, where a `ref` column links one row to another. On a dataset with a single table it does nothing and logs a warning.
### Example: What a factor touches
neighbours lights the hovered factor's links and the factors they connect it to. others fades the rest.
Try: **Hover** a factor, then a link.
```javascript
// A network: factors (nodes) and what causes what (links).
const chart = Elicit({
width: 440, height: 260,
margins: { top: 24, right: 44, bottom: 24, left: 44 },
axes: false,
schema: {
structure: "network",
tables: {
nodes: {
id: { type: "categorical", key: true },
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
links: {
role: "links",
directed: true,
fields: { source: { type: "ref" }, target: { type: "ref" } },
},
},
},
data: {
nodes: [
{ id: "Interest rates", x: 16, y: 80 },
{ id: "Migration", x: 16, y: 20 },
{ id: "New supply", x: 50, y: 88 },
{ id: "Speculation", x: 50, y: 12 },
{ id: "House prices", x: 84, y: 50 },
],
links: [
{ source: "Interest rates", target: "House prices" },
{ source: "Interest rates", target: "New supply" },
{ source: "Migration", target: "House prices" },
{ source: "Speculation", target: "House prices" },
],
},
// Hover a factor: its links light up with it, and everything else fades.
effects: {
hovered: { neighbours: true, others: { opacity: 0.2 } },
},
marks: [
link({ inset: 3, stroke: "#94A5B3", strokeWidth: 1.5 }),
node({
fill: "#50AEB7", size: 9,
channels: { x: { field: "x" }, y: { field: "y" }, text: { field: "id" } },
}),
],
});
mount(chart.dom());
```
## Hover across charts
`hovered` takes one more option, `link`. With `link: true` the chart's hover is the dataset's: the hovered row lights up in every chart on that dataset, and the other rows fade. It is on by default when two or more charts share a dataset. See [Linked hover](https://elicitjs.github.io/dataset.md#hover).
## Fade in and out
`effects.motion` fades each change of state in and out instead of switching it at once. The highlight, the outline and the mute all ease, and a row leaving a state fades out.
It is on by default wherever a highlight changes other rows too: a state with `others` or `neighbours`, or a hover linked across charts. A plain hover outline switches at once. `motion: true` fades every state, and `motion: false` switches every state at once.
The fade takes the spec's `motion.duration`, 220 ms by default. `motion: false` on the spec turns it off with the rest of the chart's motion, as does reduced motion in the reader's system. Only the drawing fades; the data and the selection change at once.
### Example: A linked hover that fades
Two charts on one dataset. Hover a district in either: it lights in both, and the other rows fade to 0.2.
Try: **Move** across the bars, then across the dots.
```javascript
// Six districts: what people pay, and what they earn.
const ds = Elicit.dataset({
schema: {
district: { type: "categorical", domain: ["Ash", "Birch", "Cedar", "Dale", "Elm", "Fern"] },
rent: { type: "quantitative", domain: [0, 3000] },
income: { type: "quantitative", domain: [0, 100] },
},
data: [
{ district: "Ash", rent: 2400, income: 82 },
{ district: "Birch", rent: 1500, income: 48 },
{ district: "Cedar", rent: 1900, income: 71 },
{ district: "Dale", rent: 900, income: 35 },
{ district: "Elm", rent: 2100, income: 55 },
{ district: "Fern", rent: 1200, income: 62 },
],
});
// Two charts on one dataset link their hover. Both mute the other rows,
// so both fade in and out by default.
const bars = ds.chart({
width: 440, height: 200,
margins: { top: 10, right: 16, bottom: 30, left: 44 },
axes: { y: { title: "Rent" } },
effects: { hovered: { others: { opacity: 0.2 } } },
marks: [
bar({
fill: "#50AEB7",
channels: { x: { field: "district" }, y: { field: "rent", edit: move() } },
}),
],
});
const scatter = ds.chart({
width: 440, height: 220,
margins: { top: 10, right: 16, bottom: 36, left: 44 },
axes: { x: { title: "Income" }, y: { title: "Rent" } },
effects: { hovered: { others: { opacity: 0.2 } } },
marks: [
point({
fill: "#F4A259", size: 7,
channels: { x: { field: "income" }, y: { field: "rent" } },
}),
],
});
mount(bars.dom());
mount(scatter.dom());
```
Set `effects: { motion: false }` on a chart to switch its states at once.
To fade the [UI layer](https://elicitjs.github.io/ui.md#motion) too, pass `{ motion: true }` to `ui.attach`.
## Switching a state off
`false` disables a state. Turn one off where the mark reads clearly on its own, such as a dense grid where an outline per cell adds noise.
### Example: Feedback only on drag
hovered: false and selected: false; only the drag reads back.
Try: **Hover** a bar, then **drag** it.
```javascript
// `false` disables a state. Here hover and selection are off, so only the drag
// reads back.
const chart = Elicit({
width: 380, height: 240,
margins: { top: 14, right: 14, bottom: 28, left: 34 },
data: [
{ cat: "A", n: 62 }, { cat: "B", n: 38 },
{ cat: "C", n: 81 }, { cat: "D", n: 24 },
],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C", "D"] },
n: { type: "quantitative", domain: [0, 100] },
},
effects: {
hovered: false,
selected: false,
grabbed: { filter: "brightness(0.78) saturate(1.4)" },
},
marks: [
bar({ channels: { x: { field: "cat" }, y: { field: "n", edit: move() } } }),
],
});
mount(chart.dom());
```
## Hover and proximity, one signal
A `pick: "nearest"` drag draws two things. The ring is the pick's `catchment`, a [guide](https://elicitjs.github.io/guides.md#parts) on the edit. The outline on the resolved dot is the `hovered` effect — the same one you get by pointing straight at a mark.
### Example: Proximity select
Move near a dot to select it; drag from empty space to grab the nearest.
Try: **Move** near a dot to select it · **Drag** from empty space to grab the nearest.
```javascript
const chart = Elicit({
width: 340, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: 25, y: 35 }, { x: 55, y: 68 }, { x: 78, y: 30 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#50AEB7",
size: 10,
channels: {
x: { field: "x" },
y: { field: "y" },
},
edits: [ move({ channels: ["x", "y"], pick: "nearest", threshold: 45, guide: true }) ],
}),
],
});
mount(chart.dom());
```
## Customized effects
The same edit, restyled. The states go in `effects`. The ring goes in the edit's `guide: { catchment }`, because it describes the pick, not the mark's state. The dots keep the `stroke` you set throughout.
### Example: Restyled feedback
A fixed-colour ring padded out from the dot, a thicker selection, a softer grab — paint channels untouched.
Try: **Move** / **drag** — fixed-colour ring, thicker outline, softer grab.
```javascript
const chart = Elicit({
width: 340, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
// EFFECTS are interaction STATE. Each state takes the same vocabulary:
// element props (filter / opacity / fill / stroke / strokeWidth / cursor) that
// ride as CSS over the mark's own paint, plus an `outline` overlay.
effects: {
hovered: { outline: { color: "#50AEB7", width: 2, padding: 8, opacity: 0.7 } },
selected: { outline: { color: "#50AEB7", width: 4, padding: 8, opacity: 1 } },
grabbed: { filter: "brightness(1.08)" },
},
data: [{ x: 25, y: 35 }, { x: 55, y: 68 }, { x: 78, y: 30 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#50AEB7",
size: 10,
channels: {
x: { field: "x" },
y: { field: "y" },
},
// The snap ring is a GUIDE — it shows the pick's reach, a rule about what a
// gesture will grab — so it is styled on the edit, not in `effects`.
edits: [ move({
channels: ["x", "y"], pick: "nearest", threshold: 45,
guide: { catchment: { color: "#50AEB7", dash: "1 3", width: 1.5, opacity: 0.5 } },
}) ],
}),
],
});
mount(chart.dom());
```
---
# Guides
> Source: https://elicitjs.github.io/guides/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A guide draws the **rule** and the **state**: what a gesture is allowed to do, and what is left to do. It views the interface's state rather than rows, so it has no channels, no table and no `edit`, and writes no data. Declare one in `guides: [...]` (`guides.rule`, `guides.region`, `guides.image`, `guides.remaining`, `guides.proximity`, `guides.tip`, `guides.crosshair`, `guides.custom`), or let an edit draw its own with `guide:`. Survey widgets use their own [widget guides](#widget-guides). Guides rebuild every render and let every gesture pass through. For hovered, selected and grabbed feedback, see [Effects](https://elicitjs.github.io/effects.md).
## API reference
### `guides.rule · guides.region · guides.remaining · guides.proximity`
Import `guides` from `elicitjs` and pass in the chart’s `guides: [...]`. All position in **data space** through the same `scale.encode()` a mark uses, so they compose across scale types. Non-interactive.
JSON keyword: `guides.rule`, `guides.region`, `guides.remaining`, `guides.proximity`
```ts
guides.rule({ x?, y?, label, stroke, strokeDash, strokeWidth, opacity }) → Guide
guides.region({ x?, y?, fill, opacity }) → Guide
guides.remaining({ field?, total?, unit?, format?, anchor?, label?, fill?, fontSize? }) → Guide
guides.proximity({ mark, stroke, strokeDash, strokeWidth, opacity }) → Guide
guides.custom((ctx) => FeatureNode[]) → Guide
// any option may be a function of the guide context:
guides.rule({ y: ({ data }) => d3.mean(data, (d) => d.y), label: "mean" })
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `rule.x / y` | `any \| (ctx) => any` | | The value to draw the reference line at — a number, a category, or a function of the data. Give both for a crosshair. |
| `rule.label` | `string \| (ctx) => string` | | Text drawn beside the line. |
| `rule.stroke / strokeDash / strokeWidth / opacity` | `style` | `theme.guide.rule` | Line paint. Restyle every reference line at once through the theme instead. |
| `region.x / y` | `[a, b] \| (ctx) => [a, b]` | | The two values to shade between on that axis. Give both for a rectangle. |
| `region.fill / opacity` | `style` | `#64748b / 0.1` | Band fill and opacity. |
| `remaining.field / total` | `string \| (ctx) => string · number \| (ctx) => number` | `the maintainSum's column · from constraints` | The column being allocated, and the target sum. Omit `field` and it reads the `maintainSum`'s column, else the one column the chart's edits write. Omit `total` and it reads the target from the `maintainSum`, so the total you enforce and the total you show stay one number. With neither, it draws nothing and warns. |
| `remaining.unit / anchor / label` | `string · string · (remaining, used, total) => string` | `— · 'top-right' · —` | `unit` gives the countable phrasing ("3 tokens left"); `anchor` picks the corner; `label` replaces the wording entirely. |
| `remaining.format` | `string \| fn` | `auto` | How the number reads: a d3-format string, or a formatter function. |
| `remaining.fill / fontSize` | `string / number` | `theme / 11` | Readout colour and size. |
| `proximity.mark` | `string` | | The `id` of the mark whose proximity catchment to draw — a dashed ring at the pointer, the radius within which it reaches for a mark. Prefer `guide: { catchment: true }` on the edit itself, which needs no id. |
| `proximity.stroke / strokeDash / strokeWidth / opacity` | `style` | `theme catchment` | Ring paint. |
| `id` | `string` | | Stable identity, on every guide. |
Returns / emits: Each returns a **Guide** (`{ isGuide: true, build(ctx) }`), rebuilt every render so it tracks live data.
### `guides.image(options)`
A picture behind the gridlines and marks, as a CSS background image on the plot. With no `x` or `y` it fills the plot; with them it is placed in data space and moves with the scales.
JSON keyword: `guides.image`
```ts
guides.image({ src, x?, y?, fit?, position?, repeat?, opacity? }) → Guide
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `src` | `string \| (ctx) => string` | | The picture's URL. Required. |
| `x / y` | `[a, b] \| (ctx) => [a, b]` | `the plot` | The picture's extent on that axis, in data units. Unset, it spans the plot on that axis. |
| `fit` | `'fill' \| 'cover' \| 'contain' \| 'none' \| 'scale-down'` | `'fill'` | How the picture is sized in its box, as CSS object-fit. 'fill' stretches it, so data positions line up with it. |
| `position` | `string` | `'center'` | Where the picture sits in its box, as CSS background-position: keywords and percentages. |
| `repeat` | `'no-repeat' \| 'repeat' \| 'repeat-x' \| 'repeat-y'` | `'no-repeat'` | Whether the picture repeats, as CSS background-repeat. |
| `opacity` | `number \| (ctx) => number` | `1` | Fades the picture. |
### `guides.custom(build)`
Draw your own non-interactive nodes from the live render context. One word for “author your own” in every namespace — cf. `edit.custom` and `constraints.custom`.
JSON keyword: `guides.custom`
```ts
guides.custom((ctx) => FeatureNode[]) → Guide
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `ctx` | `object` | | The guide context: { scales, state, features, featureNodes, ui, effects, width, height, stage }. |
| `return` | `FeatureNode[]` | | Nodes to draw. Every one is tagged pointerEvents: 'none', so a custom guide can never capture a gesture. |
| `node.background` | `boolean` | `false` | Draw this node behind the marks — a track, a cell grid — rather than in front. |
### `guides.tip(options) · tip (on a mark)`
A tooltip of the row under the pointer. It reads state and writes nothing, so it never blocks a gesture, and it shows on read-only rows too. Every mark takes `tip` as a shorthand for a tip bound to that mark.
JSON keyword: `guides.tip`
```ts
barY({ tip: true, … }) // every column of the row
barY({ tip: ["city", "rain"], … }) // these columns
barY({ tip: (d) => `${d.city}: ${d.rain}`, … })
guides.tip({ mark, text, anchor, dx, dy, fill, stroke, fontSize, format, touch }) → Guide
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `mark` | `string` | `any mark` | The id of the mark whose rows the tip reads. Left out, it reads whichever mark is under the pointer. |
| `text` | `string[] \| (row, ctx) => string \| string[]` | `every column` | The columns to show as column: value lines, or a function of the row returning a string or an array of lines. |
| `anchor` | `'pointer' \| 'mark'` | `'pointer'` | Where the box sits: beside the pointer, or beside the mark's centre. It flips to stay inside the plot. |
| `dx / dy` | `number` | `12 / 12` | The box's offset from its anchor, in px. |
| `fill / stroke` | `string` | `theme background / axis stroke` | The box's paint. |
| `fontSize` | `number` | `theme font size + 1` | The text size, in px. |
| `format` | `string \| (v) => string` | | How a number prints: a d3 format specifier or a function. Without it, numbers round to three decimals. |
| `touch` | `boolean` | `true` | Show for a finger, while it is on the chart. false shows the tip only for a mouse. |
### `guides.crosshair(options)`
Rules through the pointer across the plot, each labelled with the value under the pointer on its axis. Hidden while the pointer is outside the plot.
JSON keyword: `guides.crosshair`
```ts
guides.crosshair({ x, y, readout, stroke, strokeDash, fontSize, format, touch }) → Guide
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `x / y` | `boolean` | `true / true` | Which rules to draw: the vertical one that reads x, the horizontal one that reads y. |
| `readout` | `boolean` | `true` | Label each rule with its axis value, at the plot's bottom and left edges. |
| `stroke / strokeDash` | `string` | `theme.guide.rule / '3 3'` | The rules' colour and dash pattern. |
| `fontSize` | `number` | `theme font size` | The readout size, in px. |
| `format` | `string \| (v) => string` | | How a readout prints: a d3 format specifier or a function. Without it, numbers round to two decimals. |
| `touch` | `boolean` | `true` | Follow a finger while it is on the chart. false shows the rules only for a mouse. |
### `Instrument affordances`
The chrome a survey instrument draws itself with. Guides like any other — pass them in `guides: [...]`. The built-in [widgets](https://elicitjs.github.io/widgets.md) are assembled from these, so a hand-built instrument gets the same look.
JSON keyword: `guides.prompt`, `guides.options`, `guides.cellGrid`, `guides.sliderTrack`, `guides.quadrants`
```ts
guides.prompt(text, { y }) → Guide // the question, in the top margin
guides.options({ labelOffset, size, control }) → Guide // a choice's options
guides.cellGrid({ padding }) → Guide // a matrix's cells + headers
guides.sliderTrack({ format }) → Guide // a track with end labels
guides.quadrants({ x, y }) → Guide // centred axes + four end labels
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `prompt.y` | `number` | | Lift the prompt clear of whatever sits below it — column headers, an axis title. |
| `options.size / labelOffset` | `number` | `design / 30` | Ring radius in px, and the label's distance below it. |
| `options.control` | `"radio" \| "check"` | `"radio"` | One answer or several: which control a box design draws in each option. |
| `cellGrid.padding` | `number` | `3` | Each cell's inset from its band, in px. |
| `sliderTrack.format` | `fn` | `String` | How the two end labels read. |
| `quadrants.x / y` | `string` | | The variable name to label each axis's high and low ends with. |
### `guide (on an edit)`
What an edit draws about its own **rules**. `guide: true` turns on `bounds` and `catchment` at their defaults; an object turns parts on individually and restyles them.
```ts
guide: true | false | { bounds, catchment, track, color }
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `bounds` | `boolean \| object` | `on with guide: true` | Constraint boundaries on the edit's own value channel — a clamp's band and limit lines, a snap's stops, a maintainSum cap. |
| `catchment` | `boolean \| object` | `on with guide: true` | The reach of a proximity pick: the radius within which a free pointer resolves to a mark. Only drawn by picks that select one. |
| `track` | `boolean \| object` | `off` | Where a handle can travel. Opt-in: extra ink on a chart that already shows the handle, and worth it when the range isn't obvious. |
| `color` | `string` | `theme.constraint.color` | One colour for every part; a part's own colour still wins. |
| `.dash · width · opacity` | `any` | | Per-part stroke appearance. |
## Which kind you want
The two differ in who declares them.
**`guide:` on an edit** draws the edit's own rules. It already knows the channel, the scale and the constraints that gate it, so you repeat none of them. Use it to show what a gesture is allowed to do.
**`guides: [...]` on the spec** draws an annotation you choose — a target line, a shaded range — from whatever you compute out of the guide context.
Use the edit-owned form when the edit already knows what you want to draw. A `guides.rule` at a `clamp` limit restates that limit in a second place, and the two can drift apart.
## An edit draws its own rules
`guide: true` on an edit turns on `bounds` and `catchment`. You repeat nothing from the constraints: the edit draws every dataset constraint whose `field` matches its own channel.
Bounds follow the edit's axis. The same `clamp` draws horizontal lines on a y-edit and vertical ones on an x-edit.
### Example: clamp and snap, drawn by the edit
guide: true draws the allowed band and a labelled line at each clamp limit.
Try: **Drag** a bar past a limit, or between the snap stops.
```javascript
const chart = Elicit({
width: 400, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 36 },
data: [{ cat: "A", n: 55 }, { cat: "B", n: 30 }, { cat: "C", n: 70 }],
schema: {
cat: { type: "categorical", domain: ["A", "B", "C"] },
n: { type: "quantitative", domain: [0, 100] },
},
// The rules this chart enforces. An edit governed by them can draw them.
constraints: [ clamp({ field: "n", min: 20, max: 85 }) ],
marks: [
bar({
channels: {
x: { field: "cat" },
// `guide: true` turns on bounds and catchment. This edit has no proximity
// pick, so only the bounds draw: the allowed band and a labelled line at
// each `clamp` limit. You repeat none of it — the edit draws every
// constraint whose `field` matches its channel.
y: { field: "n", edit: move({ guide: true }) },
},
}),
],
});
mount(chart.dom());
```
## What is left to do
`guides.remaining()` states how much of a budget is still unallocated — the count a reader needs while placing tokens or splitting a total.
```js
guides.remaining({ field: "y", total: 20, unit: "token" }) // "3 tokens left"
guides.remaining({ field: "y", total: 100 }) // "45 of 100 left"
```
Pass no `total` and it reads the target from the chart's own `maintainSum` constraint, so the number you enforce and the number you show cannot drift apart. With neither a `total` nor a `maintainSum` on the field, the guide draws nothing. Set `unit` for the countable phrasing, `anchor` (`"top-right"` by default) for the corner, and `label` for a function of `(remaining, used, total)` when you want your own wording.
### Example: A budget with its remainder
guides.remaining reads the target from the maintainSum constraint, so the budget is written once.
Try: **Drag** a bar — the count updates as the total moves.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 26, right: 14, bottom: 26, left: 34 },
// No `total` here: the guide reads the target off the maintainSum
// constraint, so the budget is written once.
guides: [ guides.remaining({ field: "y", unit: "point" }) ],
data: [
{ x: "A", y: 25 }, { x: "B", y: 20 },
{ x: "C", y: 15 }, { x: "D", y: 10 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
constraints: [ clamp({ min: 0 }), maintainSum({ total: 100, strategy: "cap" }) ],
marks: [
barY({
fill: "#8A78C0",
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Restyling the parts
`guide: true` is shorthand for the parts at their defaults. Pass an object to switch and restyle each one.
A `snap`'s stops draw as short ticks at the plot edge, where the axis also sits. Raise `bounds.tickLength` and `bounds.tickOpacity` to pull them clear of it.
**`bounds`** draws the constraint boundaries: a `clamp`'s band and limits, a `snap`'s stops, a `maintainSum` cap. On with `guide: true`.
**`catchment`** draws the radius in which a proximity pick resolves a free pointer to a mark. On with `guide: true`. Edits that select a target (`pick: "nearest"`, `pick: "sweep"`, `brushSpan`, `brushRect`, `edit.geo.brush`) also turn catchment on when you **omit** `guide`. Set `guide: false` to turn it off.
**`track`** draws where a handle can travel, for handles whose range isn't a scale. Off by default — turn it on where that range isn't obvious from the mark, as on [a face's parameters](https://elicitjs.github.io/marks/face.md#track).
Each part takes `color`, `dash`, `width` and `opacity`; `bounds` adds `bandOpacity`, `fontSize`, `tickLength` and `tickOpacity`. A `color` on the guide itself sets all three parts at once. Theme tokens live at `theme.guide.bounds|catchment|track` (and `theme.constraint.color`).
### Example: One colour, or one per part
Left sets one colour for every part. Right styles each separately and lengthens the snap ticks.
Try: **Move** near a dot to see the catchment ring, then **drag** it into the band.
```javascript
// `guide: true` is shorthand for the parts at their defaults. Pass an object to
// switch and restyle each one.
const rows = [{ x: 30, y: 45 }, { x: 60, y: 62 }, { x: 84, y: 28 }];
const schema = {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
};
const bounds = [
clamp({ field: "y", min: 15, max: 80 }),
snap({ field: "y", step: 10 }),
];
// One colour for every part.
mount(Elicit({
width: 300, height: 220,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: rows, schema, constraints: bounds,
marks: [
point({
size: 9,
channels: {
x: { field: "x" },
y: { field: "y", edit: move({
pick: "nearest", threshold: 40,
guide: { bounds: true, catchment: true, color: "#1B3F60" },
}) },
},
}),
],
}).dom());
// Or one per part. `snap` stops draw as short ticks at the plot edge, where the
// axis sits — `tickLength` and `tickOpacity` pull them clear of it.
mount(Elicit({
width: 300, height: 220,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: rows, schema, constraints: bounds,
marks: [
point({
size: 9,
channels: {
x: { field: "x" },
y: { field: "y", edit: move({
pick: "nearest", threshold: 40,
guide: {
bounds: {
color: "#EE7B5E", dash: "6 2", width: 1.5, opacity: 1,
tickLength: 18, tickOpacity: 0.9,
},
catchment: { color: "#94A5B3", dash: "1 4", width: 1, opacity: 0.35 },
},
}) },
},
}),
],
}).dom());
```
## Rule and region
Annotations you declare in `guides: [...]`. `guides.region` shades a band, `guides.rule` draws a reference line. Both position in data space through the same scales a mark uses, so they stay put as points move.
### Example: A target band with a rule
guides.region shades 40–60; guides.rule marks the midpoint.
Try: **Drag** a dot in and out of the target band.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
guides: [
guides.region({ y: [40, 60], fill: "#1B3F60", opacity: 0.14 }),
guides.rule({ y: 50, label: "target 50" }),
],
data: [{ x: 20, y: 30 }, { x: 50, y: 55 }, { x: 80, y: 70 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#1B3F60",
size: 9,
channels: {
x: { field: "x" },
y: { field: "y" },
},
edits: [ move({ channels: ["x", "y"] }) ],
}),
],
});
mount(chart.dom());
```
## An image behind the marks
`guides.image({ src })` draws a picture behind the gridlines and marks, as a CSS background image on the plot. With no `x` or `y` it fills the plot, which makes it the chart's background. Give `x: [lo, hi]` and `y: [lo, hi]` in data units to place it, and it moves with the scales. Unset, either axis spans the plot.
`fit` defaults to `'fill'`: the picture stretches to its box, so a position on it reads in the same units as the axes. `fit`, `position` and `repeat` take the same values as on the [`image` channel](https://elicitjs.github.io/marks/image.md#settings), so `fit: 'none', repeat: 'repeat'` tiles a texture. `opacity` fades it.
### Example: A floor plan to place things on
guides.image spans 40 × 30 m, so each point's x and y are metres on the plan.
Try: **Drag** the router and the speaker to where you would put them.
```javascript
const chart = Elicit({
width: 440, height: 340,
margins: { top: 14, right: 14, bottom: 30, left: 34 },
data: [
{ item: "router", x: 6, y: 24 },
{ item: "speaker", x: 30, y: 6 },
],
schema: {
item: { type: "categorical" },
x: { type: "quantitative", domain: [0, 40] },
y: { type: "quantitative", domain: [0, 30] },
},
guides: [
// The plan spans 40 × 30 m, so a point on it reads in metres.
guides.image({ src: "/images/floorplan.svg", x: [0, 40], y: [0, 30] }),
],
marks: [
point({
fill: "#2B5D87", size: 8,
channels: { x: { field: "x" }, y: { field: "y" } },
edits: [ move({ channels: ["x", "y"] }) ],
}),
text({
dy: -16,
channels: { x: { field: "x" }, y: { field: "y" }, text: { field: "item" } },
}),
],
});
mount(chart.dom());
```
For a picture per row, or one inside a mark, see [Image](https://elicitjs.github.io/marks/image.md).
## Guides derived from the data
Every option takes a literal or a function of the guide context (`{ data, scales, features, ui, width, height, stage }`), so an annotation can read the rows it annotates. Here one rule is a fixed target and the other is the running **mean**. Guides rebuild each render, so it recomputes on every commit. The band tracks the spread the same way.
### Example: A mean line that chases the bars
guides.rule({ y: ({ data }) => d3.mean(data, (d) => d.y) }) reads the dataset.
Try: **Drag** a bar. The fixed target holds; the mean line and the band follow.
```javascript
const chart = Elicit({
width: 380, height: 260,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
guides: [
// A literal: a fixed reference.
guides.rule({ y: 50, label: "target 50" }),
// A function of the context: recomputed from the live rows every render.
guides.region({
y: ({ data }) => [d3.min(data, (d) => d.y), d3.max(data, (d) => d.y)],
fill: "#50AEB7", opacity: 0.10,
}),
guides.rule({
y: ({ data }) => d3.mean(data, (d) => d.y),
label: "mean",
stroke: "#EE7B5E",
}),
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
data: [
{ x: "A", y: 30 }, { x: "B", y: 55 },
{ x: "C", y: 45 }, { x: "D", y: 70 },
],
constraints: [ clamp({ field: "y", min: 0, max: 100 }) ],
marks: [
bar({
fill: "#50AEB7",
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Tooltips
`tip: true` on any mark shows a tooltip of the row under the pointer: one `column: value` line per column. Pass a list of columns (`tip: ["city", "rain"]`) to show only those, or a function of the row (`tip: (d) => string`) for your own wording.
A tip is a guide, so gestures pass through it: drag a bar while its tooltip is showing. It also shows on read-only rows, such as a locked seed or a [context row](https://elicitjs.github.io/editing/existence.md#context).
### Example: A tip on every bar
tip: true on a barY with move(). The tooltip follows the pointer; the drag works underneath.
Try: **Hover** a bar to read it · **drag** it while the tip is showing.
```javascript
const chart = Elicit({
width: 400, height: 260,
margins: { top: 16, right: 16, bottom: 32, left: 40 },
schema: {
city: { type: "categorical", domain: ["Lima", "Oslo", "Pune", "Rome"] },
rain: { type: "quantitative", domain: [0, 100] },
},
data: [
{ city: "Lima", rain: 12 }, { city: "Oslo", rain: 64 },
{ city: "Pune", rain: 78 }, { city: "Rome", rain: 41 },
],
marks: [
barY({
fill: "#50AEB7",
// A tooltip of the row's columns. The bars stay draggable under it.
tip: true,
channels: {
x: { field: "city" },
y: { field: "rain", edit: move() },
},
}),
],
});
mount(chart.dom());
```
`guides.tip()` is the long form. `text` takes the columns or a function of the row returning a string or an array of lines. `anchor: "mark"` pins the box beside the mark's centre instead of the pointer, and `mark` limits it to the mark with that `id`. `format` sets how numbers print, as a d3 format specifier or a function.
On a touch screen the tip shows while your finger is on the chart. Set `touch: false` to show it only for a mouse. See [Mobile & touch](https://elicitjs.github.io/mobile.md#hover).
### Example: A tip in your own words
guides.tip({ anchor: "mark", text: (d) => [...] }) writes two lines beside the point.
Try: **Hover** a point to read its share · **drag** it up or down.
```javascript
const chart = Elicit({
width: 400, height: 260,
margins: { top: 16, right: 16, bottom: 32, left: 40 },
schema: {
party: { type: "categorical", domain: ["Green", "Labour", "Liberal", "Other"] },
share: { type: "quantitative", domain: [0, 60] },
},
data: [
{ party: "Green", share: 12 }, { party: "Labour", share: 38 },
{ party: "Liberal", share: 31 }, { party: "Other", share: 9 },
],
guides: [
guides.tip({
anchor: "mark",
text: (d) => [`${d.party}`, `${d.share.toFixed(0)}% of the vote`],
}),
],
marks: [
point({
fill: "#7DB86B", size: 8,
channels: {
x: { field: "party" },
y: { field: "share", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Crosshair
`guides.crosshair()` draws dashed rules through the pointer across the plot. Each rule reads the value under the pointer off its axis, at the plot's bottom and left edges. Set `x: false` or `y: false` to draw one rule, and `readout: false` to drop the labels. `format` sets how the readouts print.
The rules hide when the pointer leaves the plot. Gestures pass through them. On a touch screen they follow your finger while it is down; `touch: false` turns that off.
### Example: A crosshair with readouts
guides.crosshair({ format: ".1f" }) reads hours and score under the pointer.
Try: **Move** over the plot to read both axes · **drag** a point to an exact value.
```javascript
const chart = Elicit({
width: 420, height: 260,
margins: { top: 16, right: 16, bottom: 32, left: 40 },
schema: {
hours: { type: "quantitative", domain: [0, 12] },
score: { type: "quantitative", domain: [0, 100] },
},
data: [
{ hours: 2, score: 35 }, { hours: 4, score: 52 },
{ hours: 7, score: 68 }, { hours: 10, score: 81 },
],
guides: [guides.crosshair({ format: ".1f" })],
marks: [
point({
fill: "#EE7B5E", size: 6,
channels: { x: { field: "hours" }, y: { field: "score" } },
edits: [move({ channels: ["x", "y"] })],
}),
],
});
mount(chart.dom());
```
## Widget guides
The [widgets](https://elicitjs.github.io/widgets.md) draw their chrome with guides you can also use in your own spec:
- `guides.prompt(text, { y })` draws the question in the top margin.
- `guides.options({ labelOffset, size, control })` draws a choice's options, one per category, in the theme's [design](https://elicitjs.github.io/widgets.md#designs): rings and labels by default. `size` is a ring's radius in px.
- `guides.cellGrid({ padding })` draws a matrix's cells and headers, each cell inset by `padding` px.
- `guides.sliderTrack({ format })` draws a slider's track with end labels.
- `guides.quadrants({ x, y })` draws centred axes with a label at each end.
Each reads its colours from `theme.widget`.
---
# Responsive sizing
> Source: https://elicitjs.github.io/sizing/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
By default an interface draws at the exact `width` / `height` you give it, in pixels (600×400 if unset). The `responsive` option makes it fit its parent instead. `"scale"` stretches one drawing to the container through a **viewBox** and keeps the aspect ratio. `"reflow"` **redraws at native pixels** on resize: text stays crisp, the width tracks the container, and the height stays fixed. `responsive: true` is the same as `"reflow"`. In every mode, the `width` / `height` you pass is the design size.
## API reference
### `Elicit({ responsive, width, height, … })`
One option on the `ElicitSpec`. Everything else about a chart is unchanged — marks, edits and scales all read the (possibly resized) inner dimensions, so the whole scene reflows for free.
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `responsive` | `'fixed' \| 'scale' \| 'reflow' \| true` | `'fixed'` | `'fixed'`: draw at the pixel width/height. `'scale'`: viewBox, SVG fills the parent width (aspect kept). `'reflow'` (or `true`): re-draw at the parent's measured width on resize. |
| `width / height` | `number` | `600 / 400` | The design size — the exact pixels in `"fixed"`, the viewBox in `"scale"`, and the initial width + fixed height in `"reflow"`. |
Returns / emits: The same **Chart**. A `"reflow"` chart also wires a `ResizeObserver`; call `chart.destroy()` when you unmount it to detach the observer (a no-op in the other modes).
## Scale (viewBox)
`responsive: "scale"` keeps the chart's 480×300 aspect ratio and stretches it to fill the column. Text and strokes scale with it. Use it when a chart should grow and shrink with its container, and text and strokes can scale too.
### Example: Fills the parent width
the same spec at responsive: "scale"; the SVG scales to this card via a viewBox.
```javascript
const cats = ["A","B","C","D","E"];
const chart = Elicit({
width: 480, height: 300,
responsive: "scale",
margins: { top: 16, right: 12, bottom: 28, left: 34 },
data: cats.map((c, i) => ({ cat: c, value: [30, 80, 45, 60, 20][i] })),
schema: {
cat: { type: "categorical", domain: cats },
value: { type: "quantitative", domain: [0, 100] },
},
scales: { x: { type: "band" } },
marks: [
barY({ fill: "#50AEB7", channels: {
x: { field: "cat" },
y: { field: "value", edit: move() },
} }),
],
});
mount(chart.dom());
```
## Reflow (ResizeObserver)
`responsive: "reflow"` redraws at native pixels to fit this card. The width tracks the container and the height stays 300. Resize the window and the bars lay out again at full sharpness. Call `chart.destroy()` on unmount.
### Example: Redraws to the parent width
responsive: "reflow"; drag a bar, then resize the window — layout recomputes.
Try: resize the window; drag a bar.
```javascript
const cats = ["A","B","C","D","E"];
const chart = Elicit({
width: 480, height: 300,
responsive: "reflow",
margins: { top: 16, right: 12, bottom: 28, left: 34 },
data: cats.map((c, i) => ({ cat: c, value: [30, 80, 45, 60, 20][i] })),
schema: {
cat: { type: "categorical", domain: cats },
value: { type: "quantitative", domain: [0, 100] },
},
scales: { x: { type: "band" } },
marks: [
barY({ fill: "#2B5D87", channels: {
x: { field: "cat" },
y: { field: "value", edit: move() },
} }),
],
});
mount(chart.dom());
```
## Fixed (default)
With no `responsive` option, or `responsive: "fixed"`, the chart below is exactly 320×240 pixels at any container width. Use it when a chart must be a precise size.
### Example: Exact pixels
the default: a 320×240 chart that ignores the parent width.
```javascript
const cats = ["A","B","C","D","E"];
const chart = Elicit({
width: 320, height: 240,
margins: { top: 16, right: 12, bottom: 28, left: 34 },
data: cats.map((c, i) => ({ cat: c, value: [30, 80, 45, 60, 20][i] })),
schema: {
cat: { type: "categorical", domain: cats },
value: { type: "quantitative", domain: [0, 100] },
},
scales: { x: { type: "band" } },
marks: [
barY({ fill: "#6F8294", channels: {
x: { field: "cat" },
y: { field: "value", edit: move() },
} }),
],
});
mount(chart.dom());
```
---
# Mobile & touch
> Source: https://elicitjs.github.io/mobile/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
Every chart works with a finger as well as a mouse. You turn nothing on: the same edits run, and a few things adapt so a finger can use them. This page lists what changes and what a phone can't do.
## Example: Ready for a phone
responsive: "scale" fits the screen; small points with move() and a crosshair.
Try: On a phone: **press** near a point to read it · **drag** it · **swipe** beside the chart to scroll.
```javascript
const chart = Elicit({
width: 360, height: 240,
responsive: "scale",
margins: { top: 14, right: 14, bottom: 28, left: 36 },
schema: {
hours: { type: "quantitative", domain: [0, 12] },
score: { type: "quantitative", domain: [0, 100] },
},
data: [
{ hours: 2, score: 35 }, { hours: 4, score: 52 },
{ hours: 7, score: 68 }, { hours: 10, score: 81 },
],
guides: [guides.crosshair({ format: ".0f" })],
marks: [
point({
fill: "#EE7B5E", size: 5,
channels: { x: { field: "hours" }, y: { field: "score" } },
edits: [move({ channels: ["x", "y"] })],
}),
],
});
mount(chart.dom());
```
## Fit the screen
A phone is narrow. Set `responsive: "scale"` or `"reflow"` so the chart fits the screen instead of running off its edge. See [Responsive sizing](https://elicitjs.github.io/sizing.md).
## Grabbing small marks
On a touch screen, each small editable mark gets an invisible target about 44px across: points, handles, thin bars, lines and curves. The mark under your finger wins; otherwise the nearest one within reach does. Large marks and text keep their own size.
A tap may wobble up to 10px and still count as a tap, so `cycle`, `toggle` and click-to-add work with a finger.
In a dense chart, a tap near a mark takes that mark rather than the empty space beside it.
## Scrolling past a chart
A drag that starts on an editable mark edits it, and the page holds still. So does a drag on the plot of a chart with a plane gesture (`draw`, `sweep`, `nearest`, `probe`). A swipe anywhere else scrolls the page.
A full-screen chart with a plane gesture leaves nowhere to scroll from. Keep it shorter than the screen, or leave a margin beside it.
## No hover
A finger has no hover. Tips and the crosshair show while your finger is on the chart and hide when you lift it, so press a mark to read it. Set `touch: false` on [`guides.tip`](https://elicitjs.github.io/guides.md#tips) or [`guides.crosshair`](https://elicitjs.github.io/guides.md#crosshair) to show it only for a mouse.
A `probe` previews while you drag and settles when you lift. A tap settles at once.
## What a phone can't do
- An edit gated on a key, such as `when: when.shift`, can't be reached. Don't gate an edit a phone user needs.
- Wheel zoom (`edit.view.zoom`) needs a wheel. There is no pinch to zoom.
- Arrow-key nudging needs a keyboard.
A double tap counts as a double click, so `dblclick` edits still work.
---
# Widgets
> Source: https://elicitjs.github.io/widgets/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
**Widgets** are ready-made elicitation interfaces for survey questions. Each one returns an `ElicitSpec` built from ordinary marks, edits and constraints, with its chrome drawn as [guides](https://elicitjs.github.io/guides.md). Render one with `Elicit(widgets.likert({…}))`. A [design](#designs) sets how all thirteen are drawn, and you choose one with `theme`. The Likert scale below appears both as a widget and as the plain-API spec it expands to.
## API reference
### `widgets.likert · multipleChoice · slider · matrix · lineCone · ranking · allocation · …`
Import `widgets` from `elicitjs`. Each returns an `ElicitSpec`; pass it straight to `Elicit`. The chart draws one dataset, so `getData()` reads the answer.
JSON keyword: `widgets.allocation`, `widgets.histogram`, `widgets.interval`, `widgets.labeledValue`, `widgets.likert`, `widgets.lineCone`, `widgets.matrix`, `widgets.multipleChoice`, `widgets.probabilityTokens`, `widgets.ranking`, `widgets.region`, `widgets.slider`, `widgets.thermometer`
```ts
likert({ question, options, value, onChange }) → ElicitSpec
multipleChoice({ question, options, maxChoices, value, onChange }) → ElicitSpec
slider({ question, domain, step, value, format, onChange }) → ElicitSpec
thermometer({ question, domain, step, value, onChange }) → ElicitSpec
matrix({ question, questions, options, value, onChange }) → ElicitSpec
ranking({ question, items, onChange }) → ElicitSpec
allocation({ question, categories, total, value, onChange }) → ElicitSpec
histogram({ question, bins, domain, value, onChange }) → ElicitSpec
probabilityTokens({ question, bins, maxTokens, onChange }) → ElicitSpec
interval({ question, category, value: { mean, lo, hi }, domain, symmetric, onChange }) → ElicitSpec
region({ question, domain: { x, y }, value: { x1, x2, y1, y2 }, onChange }) → ElicitSpec
lineCone({ question, x, y, value: { r, spread }, render, samples, seed, onChange }) → ElicitSpec
labeledValue({ question, input, value, domain, label, onChange }) → ElicitSpec
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `question` | `string` | `per widget` | The prompt, drawn into the top margin so it travels with the chart. |
| `onChange` | `(data) => void` | | Called with the committed answer. Hover previews never fire it. |
| `width / height / stage / theme` | | `per widget` | The ordinary spec options, passed through. Every widget takes them, so a survey can size and theme its instruments in one place. `lineCone` has two stages of its own, so it takes no `stage`. An option a widget does not read logs a warning. See [Theming](https://elicitjs.github.io/theming.md) and [Stages](https://elicitjs.github.io/editing/probe.md#basics). |
| `options` | `any[]` | `[]` | The response choices, on a band scale — `likert`, `multipleChoice`, `matrix`. |
| `value` | `any` | | The starting answer, on every widget that takes one. One value for `likert`, `slider`, `thermometer` and `labeledValue`. A list for `multipleChoice` and `matrix`, and one number per category for `allocation` and `histogram`. An object for `interval` (`{ mean, lo, hi }`), `region` (`{ x1, x2, y1, y2 }`) and `lineCone` (`{ r, spread }`); a key you leave out keeps its default. `ranking` and `probabilityTokens` take none. |
| `maxChoices` | `number` | `∞` | `multipleChoice`: how many picks are allowed. A pick over the limit is rejected. |
| `domain / step` | `[min, max] / number` | `[0, 100] / —` | The value range, on every widget that has one: `slider`, `thermometer`, `labeledValue`, `interval`, and `histogram`’s count axis (default `[0, 40]`). `region` takes one per axis, `{ x, y }` (default `[0, 10]` each). `step` is the increment a `slider` or `thermometer` answer snaps to. |
| `format` | `string \| fn` | `auto` | `slider`: how the end labels read. |
| `questions` | `any[]` | `[]` | `matrix`: the rows, one question each. |
| `items` | `any[]` | `['A','B','C','D']` | `ranking`: what is being put in order. |
| `categories / total` | `any[] / number` | `['A','B','C','D'] / 100` | `allocation`: what the budget is split between, and how much there is. Drag one bar and the others give way to keep the total. |
| `bins / maxTokens` | `any[] / number` | `— / 20` | `histogram` and `probabilityTokens`: the buckets, and how many tokens there are to place. |
| `category` | `string` | `'estimate'` | `interval`: what is being estimated. Its starting estimate and bounds are `value`, which defaults to 50%, 30% and 70% of the domain. |
| `symmetric` | `boolean` | `false` | `interval`: drag one cap and the other mirrors it about the mean. It adds `constraints.symmetric` to the widget’s `follow`, `ordering` and `clamp`. |
| `x / y` | `string` | `'x' / 'y'` | `lineCone`: the two variable names labelled on the quadrant frame. The starting correlation and its width are `value`, 0 and 0 by default. |
| `render / samples / seed` | `string / number` | `'samples' / 60 / 7` | `lineCone`: how the spread is drawn, how many sample lines it uses, and the seed that keeps them stable across renders. |
| `input / label` | `'number' \| 'text' / string` | `'number' / 'value'` | `labeledValue`: which editor the answer takes, and the name beside it. |
Returns / emits: An **ElicitSpec** — an ordinary spec, so you can read it, change one key, and pass it on. The chrome each widget draws itself with is a [guide](https://elicitjs.github.io/guides.md): `guides.prompt`, `guides.options`, `guides.cellGrid`, `guides.sliderTrack`, `guides.quadrants`. The plain-API twins below use those same guides, so each block stands alone.
### `theme.widget`
The widget tokens, set through `theme` on a widget, on `Elicit` or with `setTheme`. `design` names the [design](#designs); the others are the colours and sizes it reads. A widget takes its theme when it is built.
JSON keyword: `spec`
```ts
theme: "survey" | "surveyBlocks" | "surveyLines"
theme: { extends: "survey", widget: { design, accent, corner, … } }
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `design` | `"ring" \| "box" \| "block" \| "line" \| string` | `"ring"` | How the widgets are drawn: a built-in design, or one you [registered](#new-design). |
| `accent / onAccent` | `string` | `"#2563eb" / "#ffffff"` | A committed answer, and the text and ticks drawn on it. |
| `tint` | `string` | `"#e9f0fe"` | A chosen option's wash in the box design, and a grabbed card's in the block design. |
| `surface / soft / stroke` | `string` | `white / light grey / grey` | An option box or a card, a filled block or a bar's track, and the edge of a box or a card. |
| `ring / track` | `string` | `"#cbd5e1" / "#e2e8f0"` | An empty control, and a track or a hairline. |
| `cellFill / cellStroke` | `string` | `"#f8fafc" / "#e2e8f0"` | A matrix cell in the ring design. |
| `label / question` | `string` | `"#334155" / "#0f172a"` | An option's label, and the prompt. |
| `grip / shadow` | `string` | `grey / translucent black` | A ranking card's drag handle, and the shadow under a lifted card. |
| `labelSize / itemSize` | `number` | `12 / 13` | The text size of an option's label, and of a list row or a card. |
| `questionSize / questionWeight` | `number` | `13 / 400` | The prompt's size and weight. |
| `radius` | `number` | `11` | The radius of a ring or a radio, and half a checkbox's side. |
| `corner` | `number` | `10` | The corner radius of a box, a block or a card. |
| `gap` | `number` | `8` | The space between options and between cards. |
| `optionHeight / rowHeight` | `number` | `74 / 40` | The height of an option in a row of boxes, and of a list row or a card. |
### `authoring.registerDesign(name, design)`
Adds a design. Every widget then draws with it when `theme.widget.design` names it. State the parts you change; the rest come from `extends`. See [Add a design](#new-design).
No JSON form: this is called in JavaScript.
```ts
authoring.registerDesign(name, { extends, list, tiles, option, answer, grid, track, thumb, card, slots, bar, theme })
authoring.designNames() → string[]
authoring.labelNode(text, x, y, tokens, { width, anchor, fill, fontSize, fontWeight }) → node
authoring.checkNode(cx, cy, tokens) → node
authoring.controlNodes(cx, cy, control, selected, tokens) → node[]
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `extends` | `string` | `"ring"` | The design to take the unstated parts from. |
| `list / tiles` | `boolean` | `false` | `list` stacks multiple choice as a list. `tiles` sizes the plot to the options from `optionHeight`, `rowHeight` and `gap`. |
| `option` | `(option, tokens) => node[]` | `from extends` | Draws one option: its box, its empty control and its label. |
| `answer` | `(option, tokens) => { shape, size, corner, left, top }` | `from extends` | The answer's ink: a `dot` or a `square` on the control, or a `block` that fills the option. |
| `grid / slots` | `(box, tokens) => node[]` | `from extends` | Chrome around a whole matrix, and the lines between a ranking list's slots. |
| `track / thumb` | `(track, tokens) => node[] / (tokens) => { size, fill, stroke, strokeWidth }` | `from extends` | A slider's track, and its handle. |
| `card` | `(card, tokens) => part[]` | `from extends` | A ranking card's parts, back to front: `body`, `badge`, `rank`, `label`, `grip`. Each takes `left` or `right` and its paint. |
| `bar` | `(tokens) => { corner, fillOpacity, track }` | `from extends` | A bar in the widgets drawn on chart axes. |
| `theme` | `ThemeSpec` | | Registers a named theme under the design's name, with `widget.design` set to it. |
## Likert scale — widget & plain API
A point on a band of options, a `create({ pick: "probe" })` edit, and `count({ max: 1, strategy: "replace" })`. Hover to preview the answer, and click to set it. The plain-API version uses the same mark, edit and constraint, and draws the same look with inline `guides.custom` helpers.
### Example: As a widget
Rings, track and labels come from the guide layer.
Try: hover across the scale, then click.
```javascript
const chart = Elicit(widgets.likert({
question: "This tool is easy to use",
options: ["Strongly disagree","Disagree","Neutral","Agree","Strongly agree"],
}));
mount(chart.dom());
```
### Example: The same thing, plain API
Same mark, edit, and constraint — rings/prompt defined inline as guides. This is what widgets.likert expands to.
Try: same look, same interaction — change any line to customize.
```javascript
const options = ["Strongly disagree","Disagree","Neutral","Agree","Strongly agree"];
const radius = 11;
const prompt = (text) => guides.custom(() => [{
type: "text", x: 0, y: -18, text,
textAnchor: "start", fontSize: 13, fill: "#20555A",
}]);
const rings = () => guides.custom((ctx) => {
const cats = ctx.scales.x.domainConfig || [];
const cy = ctx.height / 2;
const cxOf = (c) => ctx.scales.x.encode(c);
const nodes = [];
for (let i = 0; i < cats.length - 1; i++) {
nodes.push({
type: "line",
x1: cxOf(cats[i]) + radius, y1: cy,
x2: cxOf(cats[i + 1]) - radius, y2: cy,
stroke: "#D9E2E9", strokeWidth: 3, background: true,
});
}
for (const c of cats) {
nodes.push({
type: "circle", cx: cxOf(c), cy, r: radius,
fill: "none", stroke: "#BCC9D4", strokeWidth: 1.5,
});
nodes.push({
type: "text", x: cxOf(c), y: cy + 30, text: String(c),
textAnchor: "middle", fontSize: 12, fill: "#20555A",
});
}
return nodes;
});
const chart = Elicit({
width: 560, height: 130,
margins: { top: 34, right: 60, bottom: 44, left: 60 },
axes: false,
data: [],
schema: { choice: { type: "ordinal", domain: options } },
scales: { x: { type: "band" } },
constraints: [ count({ max: 1, strategy: "replace" }) ],
guides: [ prompt("This tool is easy to use"), rings() ],
marks: [
point({
id: "likert",
size: radius - 3,
fill: "#50AEB7",
channels: { x: { field: "choice" } },
edits: [ create({ pick: "probe", channels: ["x"], advance: false }) ],
}),
],
});
mount(chart.dom());
```
## Multiple choice
`toggle()` combines create and remove in one gesture. Click an empty option to pick it, and click your pick to take it back. `maxChoices` caps the number of picks with `count()`.
### Example: Multiple choice (pick ≤ 2)
The hover shows whether a click will pick or un-pick.
Try: pick two, then click one again.
```javascript
const chart = Elicit(widgets.multipleChoice({
question: "Which apply?",
options: ["Fast","Cheap","Reliable","Simple"],
maxChoices: 2,
}));
mount(chart.dom());
```
## Slider
A single knob that follows the pointer and settles when you click or release a drag: `move({ pick: "probe" })`. `snap()` lands it on steps.
### Example: Slider
Track, end caps and value labels are guides.
Try: move across the track and click — or grab the knob and drag.
```javascript
const chart = Elicit(widgets.slider({
question: "How likely is it? (%)",
domain: [0, 100], step: 5, value: 40,
}));
mount(chart.dom());
```
## Question matrix
Questions on a band y, options on a band x. `toggle()` on (x, y) picks a cell, and `unique({ field: "question", strategy: "replace" })` keeps one answer per row.
### Example: Question matrix
The cell grid is a guide, so it never swallows the click.
Try: answer each row; click a row again elsewhere to change it.
```javascript
const chart = Elicit(widgets.matrix({
question: "Rate each aspect",
questions: ["Speed","Cost","Support"],
options: ["Poor","OK","Good","Great"],
}));
mount(chart.dom());
```
## Line + Cone
A two-step correlation question. Aim the line and click, then open the cone and click. `getData()` returns `[{ r, spread }]`, and `on("stage")` reports which question you are on (2 = both answered).
It is a preset over [`trendBand`](https://elicitjs.github.io/marks/trend.md#band) and [`trend`](https://elicitjs.github.io/marks/trend.md) on one dataset. A pinned `intercept: { datum: 0 }` channel and two `clamp` constraints state the correlation. The trend page has [the same spec written out](https://elicitjs.github.io/marks/trend.md#correlation). The inner plot is square, so the line’s screen angle reads as `r`.
### Example: Line + Cone
Crosshair frame and high/low variable labels are guides.
Try: move, click, move, click.
```javascript
const chart = Elicit(widgets.lineCone({
question: "What is the relationship?",
x: "Exercise amount", y: "Body weight",
}));
mount(chart.dom());
const out = document.createElement("div");
out.style.cssText = "font:12px ui-monospace,monospace;color:#6F8294";
const show = () => {
const d = chart.getData()[0];
out.textContent = "stage " + chart.getStage() +
" · r=" + d.r.toFixed(2) + " spread=" + d.spread.toFixed(2);
};
chart.on("change", show); chart.on("stage", show); show();
mount(out);
```
## Ranking
Each item is a card. Drag one to reorder the list: `rank()` on the card's body writes the new order as you cross each slot, and the other cards shift by one place. The card follows the pointer, the others ease into their slots, and the card eases into its own when you let go. With reduced motion on, cards step from slot to slot.
### Example: Ranking
A card per item. The whole card is the handle.
Try: **Drag** a card up or down. The others make room.
```javascript
const chart = Elicit(widgets.ranking({
question: "Rank these priorities",
items: ["Cost", "Speed", "Quality", "Risk"],
}));
mount(chart.dom());
```
The card is a [`composite`](https://elicitjs.github.io/marks/composite.md): a `rect` body that carries the `rank()` edit, with the rank and the label drawn on it. `motion: true` on the glyph eases its parts when the order changes. Along the `rank` channel, whose scale is a band of slots, it draws the grabbed card at the pointer. `motion: true` works on any mark, and [`spec.motion`](https://elicitjs.github.io/start.md#api) sets the duration.
### Example: The same thing, plain API
A composite card, rank() on its body, and motion: true.
Try: **Drag** a card by its label. The press reaches the body.
```javascript
// What widgets.ranking expands to: one card per row, a rank edit on its body,
// and motion: true on the glyph.
const items = ["Cost", "Speed", "Quality", "Risk"];
const chart = Elicit({
width: 420,
height: 238,
margins: { top: 34, right: 16, bottom: 4, left: 16 },
axes: false,
schema: {
item: { type: "categorical", domain: items },
rank: { type: "ordinal", domain: [1, 2, 3, 4] },
},
// The band runs down the plot, so rank 1 is at the top.
scales: { y: { type: "band", padding: 0.17, range: [0, 200] } },
data: items.map((item, i) => ({ item, rank: i + 1 })),
effects: {
hovered: { outline: false, stroke: "#94a3b8" },
grabbed: {
stroke: "#2563eb",
strokeWidth: 1.5,
cursor: "grabbing",
filter: "drop-shadow(0 6px 9px rgba(15, 23, 42, 0.18))",
},
},
marks: [
composite({
id: "card",
motion: true,
channels: {},
parts: [
// The body spans the plot and takes the drag.
rect({
height: 40, cornerRadius: 10, fill: "#ffffff", stroke: "#d5dbe5",
channels: { y: { field: "rank", edit: rank({ cursor: "grab" }) } },
}),
// The rank and the label are inert, so a press on them reaches the body.
text({
fill: "#2563eb", fontWeight: 600,
channels: { x: { value: 20 }, y: { field: "rank" }, text: { field: "rank" } },
}),
text({
fill: "#0f172a", fontSize: 13,
channels: {
x: { value: 40 }, y: { field: "rank" },
text: { field: "item" }, textAnchor: { value: "start" },
},
}),
],
}),
],
});
mount(chart.dom());
```
## Designs
A **design** sets how every widget is drawn: its options, the answer inside them, a slider's track, a ranking card, a bar. Four ship with the library. `ring` is the default and draws rings on a track. The other three come with a named theme.
- The default theme draws `ring`: rings on a track, and the answer is a filled dot.
- `theme: "survey"` draws `box`: each option is an outlined box holding a radio or a checkbox.
- `theme: "surveyBlocks"` draws `block`: options are soft blocks, and the chosen one turns solid.
- `theme: "surveyLines"` draws `line`: controls and hairlines, with nothing boxed.
Pass the theme to a widget, or call `setTheme("survey")` once to draw every widget that way. The three form designs stack multiple choice as a list. The gestures, the data and the constraints are the same in every design.
### Example: theme: "survey"
Outlined boxes, each with a checkbox.
Try: click a row to pick it, and again to take it back.
```javascript
// theme: "survey" draws each option as an outlined box holding a checkbox,
// and stacks them as a list.
const chart = Elicit(widgets.multipleChoice({
question: "Which apply?",
options: ["Fast", "Cheap", "Reliable", "Simple"],
maxChoices: 2,
value: ["Fast"],
theme: "survey",
}));
mount(chart.dom());
```
### Example: theme: "surveyBlocks"
Soft blocks. The chosen one turns solid.
Try: hover across the blocks, then click.
```javascript
// theme: "surveyBlocks" draws options as soft blocks. The chosen one turns solid.
const chart = Elicit(widgets.likert({
question: "This tool is easy to use",
options: ["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"],
value: "Agree",
theme: "surveyBlocks",
}));
mount(chart.dom());
```
### Example: theme: "surveyLines"
Radios and hairlines.
Try: answer each row.
```javascript
// theme: "surveyLines" draws controls and hairlines, with nothing boxed.
const chart = Elicit(widgets.matrix({
question: "Rate each quality",
questions: ["Easy to learn", "Fast", "Reliable"],
options: ["Poor", "Fair", "Good", "Great"],
value: [{ question: "Fast", option: "Great" }],
theme: "surveyLines",
}));
mount(chart.dom());
```
## Customizing styles
Every widget accepts a `theme`, which restyles the answer ink, chrome and affordances together. See [Theming](https://elicitjs.github.io/theming.md). The widget tokens live in `theme.widget`: `design` names the design, and the rest are the colours and sizes it reads. Start from a named theme with `extends` and change the tokens you need.
### Example: Change a design's tokens
extends: "survey", with its own accent, corner and row height.
Try: drag a card.
```javascript
// Start from a design and change its tokens: the accent, the corner, the row height.
const chart = Elicit(widgets.ranking({
question: "Rank these priorities",
items: ["Cost", "Speed", "Quality", "Risk"],
theme: {
extends: "survey",
widget: { accent: "#0f766e", tint: "#dff3f0", corner: 4, rowHeight: 36 },
},
}));
mount(chart.dom());
```
The design and the colours are separate tokens, so any theme takes any design: `theme: { extends: "dark", widget: { design: "block" } }` draws blocks in the dark theme's colours.
### Example: Restyle with a theme
widgets.slider({ …, theme: themes.survey }) — one object restyles the instrument.
Try: drag the knob — only the look changed.
```javascript
// The same slider, restyled by themes.survey — answer ink, track, and labels
// all follow the theme. See /theming.
const chart = Elicit(widgets.slider({
question: "How confident are you?",
domain: [0, 100],
value: 60,
theme: themes.survey,
}));
mount(chart.dom());
```
For a one-off change to a single widget, edit the [plain-API version](#likert): repaint the answer mark or swap a guide. The edits and constraints stay the same.
## Add a design
`authoring.registerDesign(name, design)` adds a design. A design is an object of drawers, one per part. Each drawer takes the box to draw in and the widget tokens, and returns [scene nodes](https://elicitjs.github.io/authoring.md#custom-mark) in plot pixels. State the parts you change and name the design to start from in `extends`. Every widget then draws with it.
### Example: A pill design
Two drawers and a theme, extending box.
Try: click a pill. Then change extends to "line".
```javascript
// A design states the parts it changes. The rest come from the design it extends.
authoring.registerDesign("pill", {
extends: "box",
// One option: a pill with its label inside.
option: (o, t) => [
{ type: "rect", x: o.x, y: o.y, width: o.width, height: o.height,
rx: o.height / 2, fill: t.surface,
stroke: o.selected ? t.accent : t.stroke, strokeWidth: 1 },
authoring.labelNode(o.label, o.cx, o.cy, t, {
width: o.width - 12,
fill: o.selected ? t.onAccent : t.label,
}),
],
// The answer's ink: a block that fills the chosen pill, under its label.
answer: (o, t) => ({ shape: "block", corner: o.height / 2 }),
// Registers theme: "pill" with the design's own tokens.
theme: {
extends: "survey",
widget: { accent: "#0f766e", optionHeight: 40, gap: 6 },
},
});
const chart = Elicit(widgets.likert({
question: "How often do you cycle to work?",
options: ["Never", "Rarely", "Sometimes", "Often", "Daily"],
value: "Often",
theme: "pill",
}));
mount(chart.dom());
```
A design may state these parts:
- `option(o, t)` draws one option. `o` is its box (`x`, `y`, `width`, `height`, `cx`, `cy`) with `label`, `selected`, `control` (`"radio"` or `"check"`) and `layout` (`"row"`, `"list"` or `"cell"` for a matrix).
- `answer(o, t)` describes the answer's ink: `{ shape: "dot" | "square" | "block", size, corner, left, top }`. A `block` fills the option. `left` and `top` place a dot or a square on the control.
- `grid(g, t)` draws chrome around a whole matrix, and `slots(l, t)` the lines between a ranking list's slots.
- `track(s, t)` draws a slider's track from `x1`, `x2`, `y` and `at` (the value's pixel). `thumb(t)` describes its handle.
- `card(c, t)` lists a ranking card's parts, back to front: `body`, `badge`, `rank`, `label` and `grip`. Place each with `left` or `right`, measured from the card's edge. The `body` takes the drag, and its `hovered` and `grabbed` styles become the chart's [effects](https://elicitjs.github.io/effects.md).
- `bar(t)` describes a bar in the widgets drawn on chart axes: `{ corner, fillOpacity, track }`.
- `list` stacks multiple choice as a list. `tiles` sizes the plot to the options from `optionHeight`, `rowHeight` and `gap`.
- `theme` registers a named theme with the design, so `theme: "pill"` selects both.
Take colours and sizes from the tokens `t`, so a theme can change them. `authoring.labelNode`, `authoring.checkNode` and `authoring.controlNodes` draw the label, the tick and the empty control the built-in designs share. A design holds functions, so register it in JavaScript. A JSON spec then names it like any other: `"theme": "pill"`.
## More instruments
Allocation, tokens, intervals, histograms, regions, thermometers and labelled values. Each accepts `question`, `onChange`, `stage` and `theme`. Every widget takes its starting answer as `value` and its range as `domain`: `interval` starts from `value: { mean, lo, hi }`, `region` from `value: { x1, x2, y1, y2 }` inside `domain: { x, y }`.
### Example: Allocation
Bars that redistribute to keep a fixed sum.
Try: **Drag** a bar — siblings rebalance to 100.
```javascript
const chart = Elicit(widgets.allocation({
question: "Allocate 100 points",
categories: ["A", "B", "C", "D"],
total: 100,
}));
mount(chart.dom());
```
### Example: Region
rect + brushRect for a 2-D region.
Try: **Drag** edges, corners, or the body.
```javascript
const chart = Elicit(widgets.region({
question: "Where do you expect the outcome?",
}));
mount(chart.dom());
```
### Example: Interval / CI
Drag the mean to translate the whole interval; drag a cap to resize one end.
Try: **Drag** the centre — lo/hi follow. **Drag** a cap — mean stays put.
```javascript
const chart = Elicit(widgets.interval({
question: "Your estimate and range",
value: { mean: 50, lo: 30, hi: 70 },
}));
mount(chart.dom());
```
`interval` is three `move()` handles over one row, coupled by [constraints](https://elicitjs.github.io/constraints.md#follow). `follow` carries the caps with the mean, `ordering` keeps lo ≤ mean ≤ hi, and `clamp` holds all three inside `domain`. `symmetric: true` adds `symmetric`, so dragging one cap mirrors the other about the mean.
### Example: Symmetric interval
widgets.interval({ symmetric: true }) — one cap mirrors the other.
Try: **Drag** a cap — the other moves the same distance the opposite way. **Drag** the centre — the interval follows.
```javascript
const chart = Elicit(widgets.interval({
question: "Your estimate, ± the same either way",
value: { mean: 50, lo: 35, hi: 65 },
symmetric: true,
}));
mount(chart.dom());
```
### Example: Thermometer
A single value as a vertical bar — probe drag, snap to step.
Try: **Drag** the bar (or move & click) — it snaps to the step.
```javascript
const chart = Elicit(widgets.thermometer({
question: "How likely is rain tomorrow?",
domain: [0, 100],
step: 5,
value: 40,
}));
mount(chart.dom());
```
### Example: Histogram
Editable frequency bins — drag each bar to its count.
Try: **Drag** a bar up or down to set its count.
```javascript
const chart = Elicit(widgets.histogram({
question: "How many cups of coffee per day?",
bins: ["0", "1", "2", "3", "4+"],
domain: [0, 40],
}));
mount(chart.dom());
```
### Example: Probability tokens
Discrete mass as stacked tokens — probe-create a ghost token, click to drop; alt-click removes.
Try: **Hover** a bin and click to drop a token · **Alt-click** to remove.
```javascript
const chart = Elicit(widgets.probabilityTokens({
question: "Spread 20 tokens over the outcomes you expect",
bins: ["Low", "Med", "High"],
maxTokens: 20,
}));
mount(chart.dom());
```
### Example: Labelled value
A draggable numeric readout — the number is the mark.
Try: **Drag** the number up or down.
```javascript
const chart = Elicit(widgets.labeledValue({
question: "Your point estimate",
value: 42,
domain: [0, 100],
}));
mount(chart.dom());
```
---
# JSON specs
> Source: https://elicitjs.github.io/json/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A JSON spec describes a chart as data, with the same keywords and options as the JavaScript API. `compile(json)` returns the spec `Elicit()` takes, so a chart can be stored, sent or generated. The examples on this site show both forms: switch between **JavaScript** and **JSON** above the code.
## API reference
### `compile(json, options?)`
Turns a JSON spec into the spec `Elicit()`, `Elicit.dataset()` or `ds.chart()` takes. It throws, with the path into the JSON, for an unknown keyword, an unregistered function or an expression it cannot read.
No JSON form: this is called in JavaScript.
```ts
compile(json, { functions? }) → ElicitSpec
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `functions` | `Record` | `{}` | The functions the spec names with `{ "fn": "" }`. A name here wins over one set with `registerFunction`. |
Returns / emits: A spec. It builds one chart, so compile again for another.
### `registerFunction(name, fn)`
Registers a function for every later `compile()`. Registering a name again replaces it.
No JSON form: this is called in JavaScript.
```ts
registerFunction(name, fn) → void
```
### `recorder(options?)`
Writes a spec built in JavaScript as JSON. It returns the namespaces `plot`, `elements`, `edit`, `constraints`, `layout`, `guides`, `looks`, `widgets` and `format`. Build the spec from them, then call `toJSON(spec)`. While recording, a factory returns its JSON descriptor. `live(fn)` runs `fn` with the factories building for real, for a function the spec keeps that calls one. `stop()` ends the recording, and the factories build for real from then on.
No JSON form: this is called in JavaScript.
```ts
recorder({ functions? }) → Recorder
recorder.toJSON(spec) → { json, functions }
recorder.live(fn) → the value fn returns
recorder.stop() → void
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `functions` | `Record` | `{}` | Names for the functions the spec uses. A function left out is named after its option. |
## A factory call is an object with a type
Write each factory call as an object whose `type` is the factory's name. `barY({ fill: "teal" })` becomes `{ "type": "barY", "fill": "teal" }`. Options keep their names. A scoped edit takes its dotted path: `edit.line.draw()` is `{ "type": "line.draw" }`.
Where a descriptor sits decides how its `type` is read:
| Key | Holds |
| --- | --- |
| `marks`, and a composite's `parts` | marks and chart elements |
| `elements` | chart elements |
| `guides` | guides |
| `constraints`, and an edit's `constrain` | constraints |
| `layout` | layouts |
| a mark's `edits`, and `edit` on a channel, an axis or a legend | edits |
`compile` works on all three spec shapes:
```js
Elicit(compile(json));
const ds = Elicit.dataset(compile(datasetJson));
ds.chart(compile(chartJson));
```
### Example: A chart from JSON
One mark, one edit and one constraint. Each is an object with a type.
Try: **Drag** a bar. The clamp stops it at 60.
```javascript
// The whole chart is data. Each factory call is an object with a "type".
const json = {
"width": 420, "height": 250,
"margins": { "top": 16, "right": 16, "bottom": 32, "left": 40 },
"data": [
{ "party": "Red", "share": 38 },
{ "party": "Blue", "share": 34 },
{ "party": "Green", "share": 28 }
],
"schema": {
"party": { "type": "categorical" },
"share": { "type": "quantitative", "domain": [0, 100] }
},
"constraints": [{ "type": "clamp", "min": 0, "max": 60 }],
"marks": [
{
"type": "barY",
"fill": "#50AEB7",
"channels": {
"x": { "field": "party" },
"y": { "field": "share", "edit": { "type": "move" } }
}
}
]
};
const chart = Elicit(compile(json));
mount(chart.dom());
```
## Expressions
An option that takes a function in JavaScript takes `{ "expr": "…" }` in JSON. An expression is one JavaScript expression over the option's variables:
| Option | Variables |
| --- | --- |
| a channel's `expr`, a mark's style options (`fill`, `opacity`, `dy`, …), `width`, `height`, `path`, `wrap`, `contains`, `constraints.contain` (`parent`, `child`), and `layout.*` (`where`, `in`) | `datum`, `index`, `data` |
| `lock`, `context` | `datum`, `index`, `table` |
| `format`, `tickFormat` | `value` |
| an axis's `tickSize`, `stroke`, `fill`, `fontWeight`; a grid's `stroke`, `strokeWidth`, `strokeDash` | `value`, `index` |
| a guide's options, an axis's `transform`, an edit's `when` | the keys of the context: `data`, `scales`, `width`, `height`, … |
| `tip`, and a tip's `text` | `datum`, `ctx` |
A channel carries its expression directly: `"fill": { "expr": "…" }` is the JSON form of `fill: { fn: (d) => … }`, and it is read-only in the same way.
An expression reads properties with `.` and `[]`, and takes numbers, strings, `true`, `false`, `null`, arrays and objects. Its operators are `+ - * / %`, `< <= > >=`, `== !=`, `&& || ??`, `!` and `? :`. `==` compares without converting, as `===` does in JavaScript. It calls these functions and no others:
| Functions | Result |
| --- | --- |
| `abs`, `min`, `max`, `round`, `floor`, `ceil`, `sqrt`, `pow`, `clamp(v, lo, hi)` | a number |
| `format(v, specifier)`, `timeFormat(date, specifier)` | text, through a d3 specifier |
| `year(date)`, `month(date)`, `day(date)` | part of a date; January is month `0` |
| `length(v)`, `slice(v, start, end)`, `includes(v, item)`, `lower(v)`, `upper(v)`, `string(v)`, `number(v)` | text and list helpers |
| `sum`, `mean`, `median`, `minOf`, `maxOf`, `extent` — each `(rows, field)` | a column's summary |
| `count(rows)`, `distinct(rows, field)` | the number of rows; a column's distinct values |
### Example: Expressions for a fill, a lock, a guide and a tick label
The fill re-derives from each row. The lock fixes the rows whose kind is actual.
Try: **Drag** a forecast bar above 5. Its fill changes and the mean line follows.
```javascript
// An "expr" is a function written as text. Its variables depend on the option.
const json = {
"width": 420, "height": 260,
"margins": { "top": 16, "right": 16, "bottom": 32, "left": 48 },
"data": [
{ "year": 2021, "rate": 3.4, "kind": "actual" },
{ "year": 2022, "rate": 6.8, "kind": "actual" },
{ "year": 2023, "rate": 3.9, "kind": "forecast" },
{ "year": 2024, "rate": 2.6, "kind": "forecast" }
],
"schema": {
"year": { "type": "ordinal" },
"rate": { "type": "quantitative", "domain": [0, 10] },
"kind": { "type": "categorical" }
},
// The rows that are given stay fixed.
"lock": { "expr": "datum.kind == 'actual'" },
"marks": [
{
"type": "barY",
"channels": {
"x": { "field": "year" },
"y": { "field": "rate", "edit": { "type": "move" } },
// A derived channel: recomputed from the row after every edit.
"fill": { "expr": "datum.kind == 'actual' ? '#94A5B3' : datum.rate > 5 ? '#EE7B5E' : '#50AEB7'" }
}
}
],
// A guide option reads the chart: here, the mean of a column.
"guides": [{ "type": "rule", "y": { "expr": "mean(data, 'rate')" }, "label": "mean" }],
"axes": { "y": { "tickFormat": { "expr": "value + ' %'" } } }
};
const chart = Elicit(compile(json));
mount(chart.dom());
```
## Named functions
Code that is more than one expression stays in JavaScript. Name it in the spec with `{ "fn": "" }`, and supply it in one of two places:
- `compile(json, { functions: { name: fn } })` supplies it for that spec.
- `registerFunction(name, fn)` supplies it for every later `compile()`.
A name in `functions` wins over a registered one. The function receives the same arguments as in the JavaScript API.
`custom` takes its function as the descriptor's `fn`: `edit.custom(fn, { gesture: "click" })` is `{ "type": "custom", "fn": "", "gesture": "click" }`. The same holds for `constraints.custom`, `layout.custom` and `guides.custom`. A channel takes it the same way: `"fill": { "fn": "" }`.
`onChange` takes a named function, and so does a d3 scale passed as a channel's `scale`.
### Example: A custom edit by name
The spec names snapToTens. compile() receives it in functions.
Try: **Drag** a point. Its y lands on a multiple of 10.
```javascript
// Code a spec cannot hold is named in it, and supplied where it is compiled.
const snapToTens = (ctx) => ({
...ctx.datum,
y: Math.round(ctx.scales.y.invertValue(ctx.pointer.y) / 10) * 10,
});
const json = {
"width": 380, "height": 260,
"margins": { "top": 14, "right": 14, "bottom": 26, "left": 34 },
"data": [{ "x": 30, "y": 30 }, { "x": 70, "y": 70 }],
"schema": {
"x": { "type": "quantitative", "domain": [0, 100] },
"y": { "type": "quantitative", "domain": [0, 100] }
},
"marks": [
{
"type": "point",
"fill": "#50AEB7",
"size": 8,
"channels": { "x": { "field": "x" }, "y": { "field": "y" } },
// `edit.custom(fn)`: the function is the descriptor's "fn".
"edits": [{ "type": "custom", "fn": "snapToTens" }]
}
]
};
const chart = Elicit(compile(json, { functions: { snapToTens } }));
mount(chart.dom());
```
## Predicates, formats, renderers and dates
The values the library provides are written by name:
- **`when`** takes a predicate's name: `"when": "shift"`. The predicates are `shift`, `noShift`, `alt`, `noAlt`, `near` and `far`. Those with an argument are descriptors: `{ "type": "modifier", "key": "metaKey" }`, `{ "type": "noModifier", "key": "metaKey" }` and `{ "type": "nearWithin", "threshold": 12 }`.
- **`format`** and **`tickFormat`** take a d3-format string, as in JavaScript. A `format.*` helper is a descriptor: `{ "type": "time", "specifier": "%b %Y" }`, `{ "type": "percent", "specifier": ".0%" }`, `{ "type": "prefix", "prefix": "$", "inner": ",.0f" }`.
- **`renderer`** takes `"svg"` or `"canvas"`, the same names a JavaScript spec takes.
- **`theme`**, `projection`, `curve` and a scale's `scheme` take the names they take in JavaScript.
Write a date as an ISO string. `compile` turns the strings in a `temporal` field's rows into dates.
### Example: Names for predicates, formats and the renderer
A canvas chart over a temporal column, with a time format and a currency prefix.
Try: **Drag** a point to move it. **Shift-click** one to remove it.
```javascript
// Predicates, formats and the renderer are written by name.
const json = {
"width": 440, "height": 260,
"margins": { "top": 16, "right": 16, "bottom": 34, "left": 44 },
"renderer": "canvas",
"data": [
{ "month": "2024-01-01", "price": 420 },
{ "month": "2024-04-01", "price": 465 },
{ "month": "2024-07-01", "price": 450 },
{ "month": "2024-10-01", "price": 510 }
],
"schema": {
// A temporal column is written as ISO strings.
"month": { "type": "temporal", "domain": ["2024-01-01", "2024-10-01"] },
"price": { "type": "quantitative", "domain": [300, 600] }
},
"marks": [
{
"type": "lineY",
"channels": {
"x": { "field": "month" },
"y": { "field": "price", "edit": { "type": "move", "when": "noShift" } }
},
// Shift-click removes a point; a plain drag moves it.
"edits": [{ "type": "remove", "when": "shift" }]
}
],
"axes": {
"x": { "tickFormat": { "type": "time", "specifier": "%b" } },
"y": { "tickFormat": { "type": "prefix", "prefix": "$", "inner": ",.0f" } }
}
};
const chart = Elicit(compile(json));
mount(chart.dom());
```
## Widgets
A widget returns a whole spec, so it sits under `widget`. Chart keys beside it override the widget's own: `{ ...widgets.slider(options), caption }` is `{ "widget": { "type": "slider", … }, "caption": … }`.
### Example: A slider widget
The widget's options sit in its descriptor. The caption is a chart key.
Try: **Drag** the handle.
```javascript
// A widget is a whole spec, so it sits under "widget". Chart keys go beside it.
const json = {
"widget": {
"type": "slider",
"question": "How likely is rain tomorrow?",
"domain": [0, 100],
"value": 40,
"width": 420
},
"caption": "0 means it will stay dry. 100 means it will rain."
};
const chart = Elicit(compile(json));
mount(chart.dom());
```
## From JavaScript to JSON
`recorder()` returns the library's namespaces in recording form: each factory returns its descriptor. Build a spec from them and call `toJSON(spec)` for the JSON and the functions it names. An arrow function that is a single expression over its own parameters is written as an `expr`. Any other function is named, after its option or from `recorder({ functions })`.
### Example: Record a spec
The spec is written with factories. The chart is drawn from the JSON the recorder returns.
Try: **Drag** a bar past 25. The fill is the expression the arrow became.
```javascript
// Build the spec from the recorder's namespaces, then ask for its JSON.
const rec = recorder();
const spec = {
width: 380, height: 220,
margins: { top: 14, right: 14, bottom: 30, left: 36 },
data: [{ option: "A", votes: 12 }, { option: "B", votes: 30 }],
schema: {
option: { type: "categorical" },
votes: { type: "quantitative", domain: [0, 50] },
},
constraints: [rec.constraints.clamp({ min: 0, max: 50 })],
marks: [
rec.plot.barY({
channels: {
x: { field: "option" },
y: { field: "votes", edit: rec.edit.move() },
// An arrow that is one expression is written as an "expr".
fill: { fn: (d) => d.votes > 25 ? "#EE7B5E" : "#50AEB7" },
},
}),
],
};
const { json, functions } = rec.toJSON(spec);
const chart = Elicit(compile(json, { functions }));
mount(chart.dom());
const shown = document.createElement("pre");
shown.textContent = JSON.stringify(json.marks, null, 2);
shown.style.cssText = "font-size: 11px; margin: 8px 0 0;";
mount(shown);
```
## A JSON Schema for specs
The package ships `spec.schema.json`, a JSON Schema (draft 2020-12) of the specs `compile` takes. Import it as `elicitjs/spec.schema.json`. It is generated from the library's own keyword and option tables, so it matches the version you installed.
It lists every keyword with exactly the options its factory reads, and rejects any other key: an option a mark would ignore with an `unknown-option` [warning](https://elicitjs.github.io/warnings.md) fails validation instead. It also checks the spec's top-level keys, channel forms (`field`, `value`, `datum`, `fn`, `expr`), field types, and the names `when`, `format` and `renderer` take. It checks shape only: whether a field is declared, whether a value fits its domain, and whether a function name is registered are found when the chart is built.
Validate a spec with any draft 2020-12 validator, such as Ajv:
```js
export const Ajv2020 = globalThis.__llms.comp("Ajv2020");
import schema from "elicitjs/spec.schema.json" with { type: "json" };
const validate = new Ajv2020({ strict: false }).compile(schema);
if (!validate(json)) console.log(validate.errors); // e.g. /marks/0 must NOT have additional properties
```
To have a language model write specs, give it the schema as a tool's input schema, so the tool's input is the spec. Each descriptor closes its key set with `additionalProperties: false`, so a decoder that enforces the schema cannot invent an option. The schema is about 128 KB, around 35,000 tokens. Providers limit the size and the keywords they accept for constrained decoding, so check yours before turning it on.
## What stays in JavaScript
- **The authoring kit.** A mark or edit written with `authoring.*` is code, so a spec that uses one is written in JavaScript.
- **Live objects.** A d3 scale or projection instance is registered and named with `{ "fn": "" }`. A `ScaleSpec` or a projection name is plain JSON.
- **Callbacks after the chart exists.** `chart.on(…)`, `chart.control(…)` and `ds.set(…)` are calls on the chart.
`compile` takes these keys as written and reads nothing inside them: `data`, `schema`, `theme`, `defaults`, `geojson`, `options`, a projection's `domain`, and a channel's `value` and `datum`. A row may hold a column called `type` or `fn`.
A function reference in an option that takes no function is an error, as is an unknown `type`. The message gives the path, such as `marks[0].channels.fill.expr`.
---
# Warnings
> Source: https://elicitjs.github.io/warnings/ · Elicit.js 0.5.0-alpha.0
Elicit.js warns when a spec asks for something the chart cannot do, and the chart still draws. Each warning has a stable code, a message that names the fix, and its place in the spec. Read them in the console, or take them as records with `onWarning`.
## API reference
### `setWarnings(on)`
Turns warnings on or off. They are on unless `process.env.NODE_ENV` is `"production"`. Each call clears the record of warnings already printed, so a spec that is still wrong warns again.
No JSON form: this is called in JavaScript.
```ts
setWarnings(on: boolean) → void
```
### `onWarning(listener)`
Calls `listener` with each warning as a record, before its console line. Return `false` from the listener to keep that line out of the console. A listener hears nothing while warnings are off.
No JSON form: this is called in JavaScript.
```ts
onWarning((warning) => boolean | void) → unsubscribe
warning: { code, message, path?, hint, key }
```
Options:
| Option | Type | Description |
| --- | --- | --- |
| `code` | `WarningCode` | A stable kebab-case code from the table below. |
| `message` | `string` | The sentence printed after the code. It names the option, the mark and the fix. |
| `path` | `string` | Where in the spec, from its root: `marks[1].table`, `constraints[0]`. Set when the library knows it: always for a spec from `compile()`, and for a mark, guide or constraint once the chart is built. |
| `hint` | `string` | What to do, in a few words. |
| `key` | `string` | What makes the warning distinct. A key warns once until setWarnings is called again. |
Returns / emits: A function that removes the listener.
## The console line
Each warning prints once, as `[elicit] : `:
```text
[elicit] unknown-option: bar({ gapp: … }) is not an option this mark reads, so it is ignored. Mark options are: …
```
A warning prints again only after `setWarnings` is called. Warnings are off when `process.env.NODE_ENV` is `"production"`; `setWarnings(true)` turns them back on.
## Warnings as records
`onWarning` hands each warning to your code as `{ code, message, path, hint, key }`. Use it to show warnings in your own interface, to fail a test, or to send them to an agent.
```js
export const Elicit = globalThis.__llms.comp("Elicit");
export const compile = globalThis.__llms.comp("compile");
export const onWarning = globalThis.__llms.comp("onWarning");
const seen = [];
const off = onWarning((w) => {
seen.push(w);
return false; // keep it out of the console
});
compile({ marks: [{ type: "barY", gapp: 2 }] });
// seen[0] → { code: "unknown-option", path: "marks[0].gapp",
// hint: "Fix the spelling or remove it.", message: "bar({ gapp: … }) …", key: "opt:bar:gapp" }
off();
```
`path` is set for a spec built with `compile()`, and for a mark, guide or constraint once the chart is built. A factory called directly in JavaScript, such as `plot.barY({ gapp: 2 })`, has no place in a spec yet, so its warning has no `path`.
## Codes
| Code | Triggered by | What to do |
| --- | --- | --- |
| `unknown-option` | An option, spec key or channel option that nothing reads, such as `barY({ gapp: 2 })` or `spec.scales.z`. It is ignored. | Fix the spelling, or use the option the message lists. |
| `invalid-value` | A value an option does not take, such as `ordering({ strategy: "block" })` or `spec.lock: "sead"`. A default is used. | Use one of the values the message lists. |
| `ignored-option` | A valid option that does nothing here, such as `move({ mode: "relative" })` with a plane `pick`, or `axes.x.grid` beside your own grid. | Remove it, or change the setup the message names. |
| `missing-option` | A required option is missing: `maintainSum()` with no `total`, `plot.image()` with no `src`. | Add the option. |
| `ignored-channel` | A channel the mark does not draw, such as `series` on a bar or `angle` on a needle. | Remove it, or use the channel the message names. |
| `implicit-channel` | A mark reads a column that no channel names, such as a bar's category axis with no `x` channel. | Name the column in `channels`. |
| `channel-form` | A channel written in a form it cannot use: `{ value }` on a category axis, `{ expr }` outside `compile()`, an edit on a constant or derived channel. | Use `field`, `value` or `datum` as the message says. |
| `no-schema` | `data` with no `schema`. Types and domains are inferred. | Declare the schema. The message prints one inferred from the data. |
| `undeclared-data` | The data has a column or table the schema does not declare. | Declare it in the schema, or drop it from the data. |
| `unknown-column` | A spec or call names a column the table does not declare: a constraint's `field`, `chart.set(field)`. | Name a declared column, or declare it. |
| `unknown-table` | A spec or call names a table the schema does not declare: a mark's or edit's `table`. | Name a declared table. |
| `schema-incomplete` | A field or table lacks what a feature needs: a `type`, a domain, a `default`, a `key: true` column, a `ref` target. | Add what the message names. |
| `type-mismatch` | A value contradicts its field's declared type. | Fix the value, or declare the type the data has. |
| `out-of-domain` | A value outside its field's domain, in the seed rows or a write. | Widen the domain, fix the value, or declare the field `open: true`. |
| `seed-rows` | Seeded rows break a declared rule: a constraint, `multi: false`, a reference to a missing node. They are kept. | Fix the data or the rule. |
| `scale-mismatch` | A channel resolves to a scale kind the mark, edit or layout cannot use, such as a bar on a continuous category axis. | Declare the field's type so the right scale resolves. |
| `structure-mismatch` | A feature needs a network or hierarchy dataset: `link()`, `layout.network.tree()`, `ports`. | Declare `schema.structure` and its tables. |
| `degraded-drawing` | The mark draws, but not as asked: bars overlap, a layout overflows the plot, a curve falls back to straight sides. | Change the data, the size or the option the message names. |
| `edit-never-fires` | An edit no gesture can reach, or one that can write nothing: an edit on a channel whose scale cannot invert, a `pick` no driver claims, `create` on an axis. | Move the edit to a channel or mark it can act on. |
| `edit-conflict` | Two edits or marks compete for one gesture or column, such as a plane edit on two marks over the same rows. | Keep one, or tell them apart with `when`. |
| `write-refused` | A gesture or call could not write: a closed domain is full, a constraint refused a layout. | Loosen the constraint or domain the message names. |
| `unknown-name` | No edit, event, theme, design, icon or renderer has this name: `chart.control("nope")`, `theme: "nope"`. | Use one of the names the message lists, or register it. |
| `bad-call` | A chart, dataset or `ui` call got arguments or a state it cannot act on, such as a call on a destroyed chart. Nothing happened. | Call it as the message shows. |
| `renderer-unsupported` | The renderer cannot draw what the spec asks: a shader look on SVG, `overflow: "visible"` on canvas. | Switch renderer, or drop the option. |
| `load-failed` | An image or a WebGL context did not load. | Check the URL, CORS or the browser's WebGL support. |
| `function-threw` | A function in the spec threw: a channel's `fn`, `layout.custom`. A fallback is used. | Fix the function. |
| `authoring` | A custom mark, constraint, layout or look breaks its contract, such as a constraint that returns neither rows nor a boolean. | See [Custom marks](https://elicitjs.github.io/authoring.md) for what it must return. |
---
# Renderers
> Source: https://elicitjs.github.io/renderers/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
A mark produces plain-data **scene nodes**: a circle at `cx,cy`, a rect, a path. The engine hands the whole scene to a **renderer**, which draws the nodes and reports gestures back. The renderer is the only link between the engine and the screen, so marks, edits, scales, guides and constraints behave the same under any renderer. Set it with `renderer:` on the spec.
The default is `renderer: "svg"`, an SVG backend (`D3Renderer`). `renderer: "canvas"` (`CanvasRenderer`) implements the same contract (`render(context)` in, `onEvent` out) and draws to a ``. A JSON spec takes the same two names. Any object that meets the contract works as well, given as an instance. The examples below run on canvas, and every pointer edit behaves as it does under SVG, because the interaction model lives in the engine. [What each renderer supports](#supports) lists where the two differ.
## Direct-pick drag, on canvas
Under SVG, the browser picks the element under the pointer. A canvas is a single element, so the canvas renderer finds the touched mark geometrically, with the same distance maths as the `nearest` pick. It then dispatches the same `move` edit. Drag a bar and the gesture inverts through the `y` scale and rewrites the value, as it does under SVG.
### Example: Drag a value (canvas)
renderer: 'canvas'. y carries edit: move(); the direct-pick target is hit-tested geometrically against the scene nodes.
Try: **Drag** a bar up or down.
```javascript
const chart = Elicit({
width: 380, height: 260,
renderer: "canvas",
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [
{ x: "A", y: 20 }, { x: "B", y: 45 },
{ x: "C", y: 30 }, { x: "D", y: 60 },
],
schema: {
x: { type: "categorical", domain: ["A", "B", "C", "D"] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
bar({
fill: "#50AEB7",
channels: {
x: { field: "x" },
y: { field: "y", edit: move() },
},
}),
],
});
mount(chart.dom());
```
## Plane gestures, on canvas
Plane-driven edits (`sweep`, `draw`, `nearest`, `create`) resolve their target from the pointer coordinates. The canvas renderer feeds those coordinates through the same pointer state machine, so a you-draw-it sweep works unchanged.
### Example: Sweep a line (canvas)
A plane-pick sweep: drag across the plot to redraw the line. It works from pointer coordinates through the scale, with no node identity needed.
Try: **Drag** left-to-right across the chart to reshape the line.
```javascript
const chart = Elicit({
width: 420, height: 260,
renderer: "canvas",
margins: { top: 16, right: 16, bottom: 40, left: 44 },
data: [
{ month: 0, demand: 50 }, { month: 1, demand: 50 },
{ month: 2, demand: 50 }, { month: 3, demand: 50 },
{ month: 4, demand: 50 }, { month: 5, demand: 50 },
],
schema: {
month: { type: "quantitative", domain: [0, 5] },
demand: { type: "quantitative", domain: [0, 100] },
},
axes: { x: { title: "Month" }, y: { title: "Demand" } },
marks: [
lineY({
stroke: "#315228", strokeWidth: 3, curve: "catmullRom",
channels: {
x: { field: "month" },
y: { field: "demand", edit: move({ pick: "sweep", guide: true }) },
},
}),
],
});
mount(chart.dom());
```
## What each renderer supports
Both renderers draw every mark, element, guide and effect, and report every pointer gesture. A renderer declares what it does beyond that in `supports`. A spec that asks for something its renderer does not declare logs a warning.
| `supports` | Covers | `D3Renderer` | `CanvasRenderer` |
| --- | --- | --- | --- |
| `keyboard` | Tab focus on editable marks, arrow-key nudges, `focusOutline` | yes | no |
| `textEditor` | Typing into a mark with `edit.editText()` | yes | no |
| `filter` | The `filter` prop of an [effect](https://elicitjs.github.io/effects.md#mechanisms) | yes | in browsers whose 2D context has `filter` |
| `overflow` | `overflow: "visible"` | yes | no |
| `shaders` | Shader [looks](https://elicitjs.github.io/looks.md) | no | in browsers with WebGL |
Canvas differs in three more ways, none of which a spec can ask for:
- It finds the mark under the pointer geometrically, with a 4px tolerance around every shape. SVG tests the drawn shape exactly.
- It picks a path along its `points`, so a custom mark that emits only `d` draws and takes no press.
- It draws pixels, so a mark has no element to style with CSS, select in a test, or expose to a screen reader.
A custom renderer sets `supports` to what it implements; unset declares nothing. It can also define `destroy()`, which `chart.destroy()` calls so the renderer can release its listeners and caches.
---
# Authoring SDK
> Source: https://elicitjs.github.io/authoring/ · Elicit.js 0.5.0-alpha.0
>
> Examples name keywords bare (`barY`, `move()`) and call the docs' `mount(node)`. In your code, destructure them from `plot`, `edit`, `elements` or `constraints`, and append `chart.dom()` to the page.
Extend Elicit.js with new marks, edits and gestures. Marks use `authoring.encodeChannel` and `resolveStyle`. Edits use `authoring.makeEdit` and `invertChannel`. Multi-event lifecycles register with `authoring.registerDriver`. Edits go on a channel (`y: { field, edit: move() }`) or in a mark's `edits: [...]`. For the model these extend, see [Core concepts](https://elicitjs.github.io/concepts.md). For the stock edits, see [Editing](https://elicitjs.github.io/editing.md).
## API reference
### `Mark SDK`
Shared foundation every mark factory uses. Import as `authoring.encodeChannel` (or the bare name in these docs). A mark never owns `data` or a domain — `Elicit` owns both.
No JSON form: this is called in JavaScript.
```ts
authoring.normalizeMarkOptions(options) → options
authoring.encodeChannel(scales, channels, name, datum, fallback) → any
authoring.encodeAngle(scales, channels, datum, fallback?) → number
authoring.resolveStyle(scales, channels, datum, defaults?) → style
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `build(data, scales, width, height, ctx?)` | `required` | | Emit `FeatureNode[]` (`circle` / `rect` / `line` / `path` / `text`). Resolve every position and style through `encodeChannel` / `resolveStyle` — never call `scale(d[key])` by hand. A mark that joins another table reads it from `ctx`: `tables`, `schema` and its own `table`. |
| `authoring.normalizeMarkOptions` | `fn` | | Call at the top of the factory. Desugars top-level shorthands (`fill`, `size`, …) into `channels.*.value`. |
| `discreteScale` | `'band' \| 'point'` | | What the mark needs for discrete data (bar → band interval; point/line → tick). Leave unset for span-only marks (rule). |
| `channels / edits / id` | `passthrough` | | Accept them on the factory and pass them through. A mark that drops edits can’t be edited. Constraints go on the spec: a mark given constraints logs a warning. |
| `xKey / yKey` | `string` | `from channels` | Field names the edit/constraint layer reads back — usually the channel’s field. |
| `pointerEvents` | `per-node` | `engine` | Don’t silence the whole mark — leave unset so the engine can. Set per-node on glyph *chrome* (a path over handles) so chrome doesn’t swallow drags. |
Returns / emits: A feature object the engine consumes. Line-family marks also set `seriesKey`, `order`, and `supportsSeries: true`.
### `Edit SDK`
Build descriptors and reuse the same invert/pick helpers the stock edits use. Prefer the ladder: stock edit → `custom` → `makeEdit` → `registerDriver`.
No JSON form: this is called in JavaScript.
```ts
makeEdit(spec) → Edit
custom(fn, options) → Edit
invertChannel(ch, pointer, center?) → value
recenterSpan(node, chA, chB, pointer) → { a, b }
markCenter(node) → { x, y }
schemaDefaults(schema) → Datum
nearestMark(marks, x, y, threshold) → index | null
registerDriver({ name, onEvent, sessionKeys?, options?, wants?, selects? })
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `makeEdit(spec)` | `→ Edit` | | Normalize a partial spec into a full descriptor. Defaults: `gesture: "drag"`, `pick: "direct"`, `channels: null` (inject the channel it’s placed on). Keys the descriptor doesn’t know pass through onto the edit — the sanctioned way a custom driver carries per-edit options (the built-ins’ `edgeInset` works the same way). |
| `apply(ctx)` | `fn` | | Pure given `ctx`. Return a **datum** (splice at index), a **full array** (whole-dataset rewrite), or `undefined` (no-op). Never mutate `ctx.data`. |
| `EditContext` | `ctx` | | `data`, `datum`, `index`, `pointer`, `node`, `event`, resolved `channels`, `markChannels`, `scales`, `schema`, `marks`, … |
| `cardinality` | `'append' \| 'appendMany' \| 'toggle' \| 'delete'` | | Tell constraints which row is active when the dataset’s shape changes (create/remove). |
| `inverts` | `boolean` | `false` | Declares that this edit runs a **pointer** back through a channel’s scale, so that scale must be invertible. Set it on any edit that reads `ctx.pointer`; the dead-drag guard reads this rather than a list of type names. |
| `inline` | `boolean` | `false` | Declares that this edit opens an inline text editor over the mark. It is what wires the double-click lifecycle — type, then Enter or blur commits and Escape cancels — and what `editText` sets. |
| `name` | `string` | `null` | Stable handle for `chart.control(name)`. See [External controls](https://elicitjs.github.io/editing/external-controls.md). |
| `scope` | `'line' \| 'stack' \| 'waffle' \| 'trend' \| 'network' \| 'geo' \| 'axis' \| 'legend' \| 'scale'` | `null` | Mark family the edit needs. Put the family in the API name (`edit.line.*`); the engine warns on a mismatch. |
| `invertChannel` | `fn` | | Pointer → data for one resolved channel — the same path stock move uses. Prefer this over hand-rolled scale.invert. |
Returns / emits: Descriptors the engine routes. Multi-event lifecycles belong in a **driver**, not an `if (pick === …)` branch in the engine.
### `Drivers — authoring.registerDriver`
A driver owns a multi-event plane lifecycle (`hover` / `drag` / `click`, …). Built-ins cover `nearest`, `sweep`, `draw`, `brush`, `probe`, `plane`, …. Register a new one when stock `pick` values aren’t enough.
No JSON form: this is called in JavaScript.
```ts
registerDriver({ name, onEvent(ctx), sessionKeys?, options?, wants?(edit), selects? })
```
Options:
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| `wants(edit)` | `→ boolean` | | Claim edits — usually `edit.pick === name`. |
| `onEvent(ctx)` | `→ boolean` | | Return whether anything changed (commit or redraw). `ctx` has `event`, `edits`, `marks`, `session`, `preview`, `runEdit`, `previewEdit`. |
| `runEdit / previewEdit` | `(edit, index) → boolean` | | Commit through constraints + undo, or park an uncommitted hover preview. |
| `selects` | `boolean` | `false` | If true, the driver writes a selection into `session` so `guide: true` can draw the snap ring / highlight. |
Returns / emits: Replaces a built-in of the same `name`, or adds a new pick. No engine fork required.
## A custom mark
A mark is a view over the chart’s dataset. The factory returns a feature object, and its only required method is `build(data, scales, width, height, ctx?)`.
- Call `normalizeMarkOptions` first.
- Resolve every channel through `encodeChannel` and `resolveStyle`.
- Spread `authoring.markCommon(opts)` to pass `id`, `edits`, `table`, `tip` and `clip` through unchanged.
- Set `discreteScale` when discrete data needs a band or a point scale.
- Set `type` on the feature. Every feature carries one; the example uses `"square"`.
- Leave mark-wide `pointerEvents` to the engine.
To let a datum’s [derived channels (`{ fn }`)](https://elicitjs.github.io/concepts.md#derived) see their row index and the dataset, pass the optional `index` and `data` arguments when you resolve per datum: `authoring.resolveStyle(scales, channels, d, defaults, i, data)`.
### Example: A custom square mark
authoring.normalizeMarkOptions → encodeChannel / resolveStyle → FeatureNode[]. Stock drag still works because the nodes carry data and index.
Try: **Drag** a square — same edit path as a point.
```javascript
// A minimal mark factory — same contract as point/bar.
function square(options = {}) {
const opts = authoring.normalizeMarkOptions(options, { mark: "square", allow: [] });
const { channels = {} } = opts;
return {
// id / edits / table / tip / clip, passed through verbatim.
...authoring.markCommon(opts),
type: "square",
channels,
discreteScale: "point",
xKey: channels.x && channels.x.field,
yKey: channels.y && channels.y.field,
build(data, scales, width, height) {
return data.map((d, i) => {
const style = authoring.resolveStyle(scales, channels, d, { fill: "#50AEB7" });
const cx = authoring.encodeChannel(scales, channels, "x", d, width / 2);
const cy = authoring.encodeChannel(scales, channels, "y", d, height / 2);
const r = authoring.encodeChannel(scales, channels, "size", d, 8);
const side = Math.max(0, r * 2);
return {
type: "rect",
x: cx - side / 2, y: cy - side / 2,
width: side, height: side,
...style, data: d, index: i,
};
});
},
};
}
const chart = Elicit({
width: 380, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: 25, y: 40 }, { x: 55, y: 70 }, { x: 80, y: 35 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
square({
size: 9,
channels: {
x: { field: "x" },
y: { field: "y" },
},
edits: [ move({ channels: ["x", "y"] }) ],
}),
],
});
mount(chart.dom());
```
## The edit ladder
Reach for the smallest tool that fits:
1. **Stock edit** — `move`, `resize`, `create`, … when the behaviour already exists.
2. **`custom(fn)`** — one-off `apply`, same gesture/pick defaults.
3. **`makeEdit(spec)`** — full descriptor control (`type`, `pick`, `cardinality`, `name`, …).
4. **`registerDriver`** — multi-event lifecycle / a new `pick` value.
`apply` is pure: return a new datum, a new array, or `undefined`. Prefer `invertChannel` over hand-rolled `scale.invert`.
### Example: custom(fn) — a one-off apply
custom wraps fn as apply. Drag rewrites y from the pointer; x still uses stock move().
Try: **Drag** vertically on a dot to set y; drag the dot itself to move in x.
```javascript
// Level B — custom(fn): one-off apply, stock gesture/pick defaults.
const bumpY = custom((ctx) => {
if (!ctx.datum) return undefined;
const y = ctx.scales.y.invertValue(ctx.pointer.y);
return { ...ctx.datum, y: Math.round(y) };
});
const chart = Elicit({
width: 380, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: 30, y: 40 }, { x: 70, y: 65 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#1B3F60", size: 9,
channels: {
x: { field: "x", edit: move() },
y: { field: "y" },
},
edits: [ bumpY ],
}),
],
});
mount(chart.dom());
```
### Example: makeEdit + invertChannel
Full descriptor: invert y, then snap to the nearest 10. Same idea as custom, with an explicit type and channels list.
Try: **Drag** the point — it lands on multiples of 10.
```javascript
const snapDrag = authoring.makeEdit({
type: "snapDrag",
gesture: "drag",
channels: ["y"],
apply: (ctx) => {
const ch = ctx.channels[0];
const v = authoring.invertChannel(ch, ctx.pointer);
if (v === undefined || !ctx.datum) return undefined;
return { ...ctx.datum, [ch.field]: Math.round(v / 10) * 10 };
},
});
const chart = Elicit({
width: 360, height: 240,
margins: { top: 16, right: 16, bottom: 28, left: 34 },
data: [ { cat: "A", n: 40 } ],
schema: {
cat: { type: "categorical", domain: ["A"] },
n: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#50AEB7", size: 10,
channels: { x: { field: "cat" }, y: { field: "n" } },
edits: [ snapDrag ],
}),
],
});
mount(chart.dom());
```
## When apply returns a full array
Most edits return one datum, which replaces the row at `index`. Whole-dataset edits, such as reorder, create and remove, return a new array. `rank()` is the built-in example: drag swaps discrete rank slots.
### Example: rank() — array-returning apply
Point scale over ranks; drag swaps with the nearest slot. Your makeEdit can return [...ctx.data] the same way.
Try: **Drag** a point to another rank.
```javascript
const chart = Elicit({
width: 360, height: 260,
margins: { top: 16, right: 16, bottom: 28, left: 80 },
data: [
{ item: "A", rank: 1 },
{ item: "B", rank: 2 },
{ item: "C", rank: 3 },
],
schema: {
item: { type: "categorical", domain: ["A", "B", "C"] },
rank: { type: "ordinal", domain: [1, 2, 3] },
},
marks: [
point({
fill: "#1B3F60", size: 9,
channels: {
x: { value: 40 },
y: { field: "rank", edit: rank() },
},
}),
text({
fontSize: 13,
channels: {
x: { value: 56 },
y: { field: "rank" },
text: { field: "item" },
textAnchor: { value: "start" },
},
}),
],
});
mount(chart.dom());
```
## Register a driver
Stock `pick` values (`direct`, `nearest`, `plane`, `probe`, `sweep`, …) cover most lifecycles. For a new one, register a driver. An edit reaches a driver by naming it, as in `pick: "clickNearest"`, and each edit reaches exactly one driver. `wants(edit)` claims an edit by capability, such as a relative slide, and doesn't re-test `pick`.
`onEvent` handles hover, click and drag. `runEdit` and `previewEdit` commit or preview through the same constraint and undo path as stock edits. Declare `sessionKeys`. Every driver on the mark shares the per-feature session, and the `session.clear()` you receive nulls only your keys. Declare `options` for any setting your driver reads off the edit, or the engine reports it as an unknown option. Set `selects: true` if `guide: true` should draw a snap ring. Set `targetsRow: true` if the driver only chooses a row, so that `chart.control(name, index)` can run its edits on a given row.
### Example: clickNearest — hover, then click to bump
registerDriver + makeEdit({ pick: "clickNearest" }). Hover highlights; click adds 10 to y.
Try: **Hover** near a dot, then **click** to bump its y.
```javascript
// A tiny driver: hover highlights the nearest mark; click bumps its y.
authoring.registerDriver({
name: "clickNearest",
// The keys this driver owns in the shared per-feature session; clear() nulls them.
sessionKeys: ["px", "py", "threshold", "hoverIndex"],
selects: true,
onEvent({ event, edits, marks, session, runEdit }) {
const threshold = 48;
if (event.type === "hover") {
session.set({
px: event.x, py: event.y, threshold,
hoverIndex: authoring.nearestMark(marks, event.x, event.y, threshold),
});
return true;
}
if (event.type === "hoverout") {
session.clear();
return true;
}
if (event.type === "click") {
const index = authoring.nearestMark(marks, event.x, event.y, threshold);
if (index == null) return false;
let changed = false;
for (const e of edits) {
if (e.gesture === "click" && runEdit(e, index)) changed = true;
}
return changed;
}
return false;
},
});
const bump = authoring.makeEdit({
type: "bump",
pick: "clickNearest",
gesture: "click",
channels: ["y"],
guide: true,
apply: (ctx) => {
if (!ctx.datum) return undefined;
const field = ctx.channels[0].field;
return { ...ctx.datum, [field]: Math.min(100, (ctx.datum[field] || 0) + 10) };
},
});
const chart = Elicit({
width: 380, height: 240,
margins: { top: 14, right: 14, bottom: 26, left: 30 },
data: [{ x: 25, y: 30 }, { x: 55, y: 55 }, { x: 80, y: 40 }],
schema: {
x: { type: "quantitative", domain: [0, 100] },
y: { type: "quantitative", domain: [0, 100] },
},
marks: [
point({
fill: "#50AEB7", size: 9,
channels: {
x: { field: "x" },
y: { field: "y" },
},
edits: [ bump ],
}),
],
});
mount(chart.dom());
```
## Glyphs: prefer a group of marks
If a glyph’s handles map to distinct fields of a row, build it as a [`composite`](https://elicitjs.github.io/marks/composite.md): ordinary marks over the same rows. Direct picks then keep each handle to its own field. Use `node.channel` with a `when` guard only when several handles must live on one feature over one datum, because their positions are derived rather than stored as fields.
Put a whole-dataset plane gesture (`create`, `rotate`, …) on exactly one mark. Two marks with the same plane edit fire twice per click.
## Helpers to reuse
Reuse these for proximity and minting:
- `invertChannel` / `recenterSpan` / `markCenter`: pointer ↔ data for positional edits
- `schemaDefaults(schema)`: mint a row with every field set to its default (or `null`)
- `authoring.nextSeriesKey(data, seriesField, schema?)`: the next free series id for a new line
- `nearestMark` / `nearestSeries` / `nearestMarkOnAxis`: shared distance pickers
To restyle the built-in [widgets](https://elicitjs.github.io/widgets.md), register a design: [`authoring.registerDesign`](https://elicitjs.github.io/widgets.md#new-design).
For a custom edit that creates rows, set `cardinality: "append"` so constraints know which row is new. For an edit that runs the pointer back through a scale, set `inverts: true` so the dead-drag guard can check the channel. To drive an edit from external UI, give it a `name` and call [`chart.control(name)`](https://elicitjs.github.io/editing/external-controls.md).
## Where next
- **[Marks](https://elicitjs.github.io/marks/bar.md)** — reference implementations (`point`, `bar`, `rule`) to mirror.
- **[Editing](https://elicitjs.github.io/editing.md)** — stock gestures, pick modes, stages, history.
- **[Composite](https://elicitjs.github.io/marks/composite.md)** — multi-handle glyphs as grouped marks.
- **[Constraints](https://elicitjs.github.io/constraints.md)** — dataset rules your `apply` must respect.
- **[Gestures · Custom](https://elicitjs.github.io/editing/gestures.md#custom)** — more `custom(fn)` patterns with `when`.
---
# Mark & element contracts
> Source: https://elicitjs.github.io/concepts/contracts/ · Elicit.js 0.5.0-alpha.0
What every factory is for: its kind, whether create and remove apply, and what you grab. Axes, grids and legends are on `elements.*`.
## Kinds of factory
| Kind | Meaning |
| --- | --- |
| **data** | Views dataset rows; channels name columns |
| **parametric** | Channels are curve parameters (trend); rows are not created freely |
| **map chrome** | Basemap / tiles; pointer-transparent |
| **element** | Views a scale; its edits write the domain, not rows |
Data, parametric and map-chrome factories are all marks: they view rows. An element views a scale. Guides, the third kind on [Core concepts](https://elicitjs.github.io/concepts.md#feature-kinds), view state and are covered on [Guides](https://elicitjs.github.io/guides.md).
Marks are **inert** until an edit names the column it writes. Edits write **fields**, so an edit goes on a `{ field }` channel. A constant `{ value }` channel carries none.
## Data marks
| Factory | create/remove | What you grab |
| --- | --- | --- |
| `point` | natural | the mark |
| `shape` | natural | the shape |
| `bar` / `barX` / `barY` | remove ok; create awkward | the bar |
| `rect` / `rectX` / `rectY` | natural | the rect (`brushRect` zones) |
| `tick` / `tickX` / `tickY` | natural | the tick |
| `ellipse` | natural | the mark; `rx` and `ry` are separate magnitudes |
| `image` | natural | the picture; a row with no `src` draws nothing |
| `track` | natural | anywhere on the route; `move` on `length` reads the place along it |
| `curve` / `curveX` / `curveY` | less natural | a fat transparent hit path over the stroke |
| `text` / `textX` / `textY` | create awkward; use `editText` | the label |
| `line` / `path` / `polygon` / `area` (+ X/Y) | natural (`edit.line.*`) | per-datum / edge circles; the inside of a closed path for `edit.line.moveSeries` |
| `rule` / `ruleX` / `ruleY` | less natural | the segment when edited |
| `dotStack` | natural (canonical) | tokens |
| `waffle` | N/A → `edit.waffle.fill` | cells |
| `needle` | N/A | the path and its hub; `handles` sets the hub’s paint |
| `arc` / `donut` | `edit.stack.cut` / `edit.stack.merge` | rim boundary dots |
| `composite` | depends on parts | each part is its own feature; in box mode, placed in a per-datum **local frame** |
| `node` / `sticker` | depends on parts | presets over `composite`; the dot or the note |
| `link` | `edit.network.connect` / `remove` | a transparent hit path; endpoint handles where an edit writes that end |
On every mark that draws a grip, `handles` takes `true` (drawn and grabbable), `false` (hidden and inert), or `'hit'` (invisible but grabbable).
## Parametric glyphs
| Factory | Notes | Affordance |
| --- | --- | --- |
| `trend` | x/y are **axes**; intercept/slope are params | a circle at `anchor`, and slope circles at the line’s ends (or one at `probe` under `grip: "probe"`) |
| `trendBand` | the spread around a `trend`; a view of the same rows | spread grips where an edit reaches the row |
| `face` | a **preset** that returns a box-mode `composite` of ordinary marks. The emotion preset binds valence/arousal if unbound | **shape is the control** — each feature is its own mark, so the universal edits apply and there is no `edit.face.*` |
Set a stage on the edit, as in `edit.trend.slope({ stage: 1 })`. The mark takes no stage option.
## Geographic
| Factory | Kind | create/remove |
| --- | --- | --- |
| `geoPoint` / `geoLine` / `geoPolygon` / `geoRect` / `geoText` | data | natural (`edit.geo.*`) |
| `geoBasemap` / `geoTile` | map chrome | N/A |
## Chart elements
Chart elements are exported as `elements.*`. Pass them in `elements: [...]` on the spec, or inside `marks`; both lists draw together, elements first.
| Factory | Edits | Handles |
| --- | --- | --- |
| `axis` / `axisX` / `axisY` | `edit.axis.scale`, `edit.scale.categories` | domain end grips / category labels |
| `grid` / `gridX` / `gridY` | none | — |
| `legend` / … | `edit.legend.category` / `edit.legend.value` | ramp grip / swatches |
| `axisRadial` | none; `edit`, `edits`, `field` and `table` warn | inert; optional x/y placement for per-row rings |
See [Axis, Grid & Rule](https://elicitjs.github.io/marks/axes.md#chart-elements) and [Legend](https://elicitjs.github.io/marks/legend.md).
## Guides and effects
An edit's `guide:` option draws its rules: `bounds`, `catchment` and `track`. An **effect** shows interaction state: `hovered`, `selected` or `grabbed`. Edits that select a target (`pick: "nearest"`, `pick: "sweep"`, `brushSpan`, `brushRect`, `edit.geo.brush`) turn catchment on when you omit `guide`. Set `guide: false` to turn it off. See [Guides](https://elicitjs.github.io/guides.md) and [Effects](https://elicitjs.github.io/effects.md).
---
# API index
> Source: https://elicitjs.github.io/api/ · Elicit.js 0.5.0-alpha.0
Every keyword Elicit.js exports, by namespace, with its own options and the page that documents it. Universal options (`channels`, `edits`, …) are listed once per namespace.
## plot
Marks draw the rows of your dataset.
Universal options: `channels`, `id`, `edits`, `table`, `tip`, `clip`, `motion`, `contains`.
- `plot.arc(options)`: `outerRadius`, `innerRadius`, `padAngle`, `arc`, `start`, `end`, `handles`, `handleSize`, `handleColor` ([docs](https://elicitjs.github.io/marks/arc.md))
- `plot.area(options)`: `orientation`, `curve`, `handles`, `handleSize`, `handleColor`, `connect`, `gradient` ([docs](https://elicitjs.github.io/marks/area.md))
- `plot.areaX(options)` ([docs](https://elicitjs.github.io/marks/area.md))
- `plot.areaY(options)` ([docs](https://elicitjs.github.io/marks/area.md))
- `plot.bar(options)`: `orientation`, `handles`, `handleSize`, `handleColor`, `gradient`, `cornerRadius` ([docs](https://elicitjs.github.io/marks/bar.md))
- `plot.barX(options)` ([docs](https://elicitjs.github.io/marks/bar.md))
- `plot.barY(options)` ([docs](https://elicitjs.github.io/marks/bar.md))
- `plot.composite(options)`: `parts`, `discreteScale` ([docs](https://elicitjs.github.io/marks/composite.md))
- `plot.curve(options)`: `orientation`, `length` ([docs](https://elicitjs.github.io/marks/curve.md))
- `plot.curveX(options)` ([docs](https://elicitjs.github.io/marks/curve.md))
- `plot.curveY(options)` ([docs](https://elicitjs.github.io/marks/curve.md))
- `plot.donut(options)` ([docs](https://elicitjs.github.io/marks/arc.md))
- `plot.dotStack(options)`: `orientation`, `gap`, `ghost`, `label` ([docs](https://elicitjs.github.io/marks/dotstack.md))
- `plot.dotStackX(options)` ([docs](https://elicitjs.github.io/marks/dotstack.md))
- `plot.dotStackY(options)` ([docs](https://elicitjs.github.io/marks/dotstack.md))
- `plot.ellipse(options)` ([docs](https://elicitjs.github.io/marks/ellipse.md))
- `plot.face(options)`: `ink` ([docs](https://elicitjs.github.io/marks/face.md))
- `plot.geoBasemap(options)`: `geojson`, `stroke`, `strokeWidth`, `fill` ([docs](https://elicitjs.github.io/marks/geo.md))
- `plot.geoLine(options)`: `handles`, `handleSize`, `handleColor`, `closed` ([docs](https://elicitjs.github.io/marks/geo.md))
- `plot.geoPoint(options)` ([docs](https://elicitjs.github.io/marks/geo.md))
- `plot.geoPolygon(options)`: `handles`, `handleSize`, `handleColor` ([docs](https://elicitjs.github.io/marks/geo.md))
- `plot.geoRect(options)` ([docs](https://elicitjs.github.io/marks/geo.md))
- `plot.geoText(options)`: `format` ([docs](https://elicitjs.github.io/marks/geo.md))
- `plot.geoTile(options)`: `url`, `subdomains`, `tileSize`, `minZoom`, `maxZoom`, `zoomOffset`, `attribution`, `attributionSize`, `opacity` ([docs](https://elicitjs.github.io/marks/geo.md))
- `plot.image(options)` ([docs](https://elicitjs.github.io/marks/image.md))
- `plot.line(options)`: `orientation`, `curve`, `handles`, `handleSize`, `handleColor`, `connect`, `closed` ([docs](https://elicitjs.github.io/marks/line.md))
- `plot.lineX(options)` ([docs](https://elicitjs.github.io/marks/line.md))
- `plot.lineY(options)` ([docs](https://elicitjs.github.io/marks/line.md))
- `plot.link(options)`: `curve`, `curvature`, `spread`, `arrow`, `arrowSize`, `inset`, `sourceInset`, `targetInset`, `loopRadius`, `format`, `labelBackground`, `labelPadding`, `labelRadius`, `labelOpacity`, `cornerRadius`, `sourceSide`, `targetSide`, `sourceOffset`, `targetOffset`, `handles`, `handleSize`, `handleColor` ([docs](https://elicitjs.github.io/marks/network.md))
- `plot.needle(options)`: `length`, `handles`, `handleSize`, `handleColor`, `baseWidth`, `tipWidth` ([docs](https://elicitjs.github.io/marks/needle.md))
- `plot.node(options)`: `dy`, `shape`, `format` ([docs](https://elicitjs.github.io/marks/network.md))
- `plot.path(options)` ([docs](https://elicitjs.github.io/marks/line.md))
- `plot.point(options)`: `shape` ([docs](https://elicitjs.github.io/marks/point.md))
- `plot.polygon(options)` ([docs](https://elicitjs.github.io/marks/line.md))
- `plot.rect(options)`: `orientation`, `width`, `height`, `cornerRadius`, `gradient` ([docs](https://elicitjs.github.io/marks/rect.md))
- `plot.rectX(options)` ([docs](https://elicitjs.github.io/marks/rect.md))
- `plot.rectY(options)` ([docs](https://elicitjs.github.io/marks/rect.md))
- `plot.rule(options)`: `orientation`, `discreteScale` ([docs](https://elicitjs.github.io/marks/axes.md))
- `plot.ruleX(options)` ([docs](https://elicitjs.github.io/marks/axes.md))
- `plot.ruleY(options)` ([docs](https://elicitjs.github.io/marks/axes.md))
- `plot.shape(options)` ([docs](https://elicitjs.github.io/marks/shape.md))
- `plot.sticker(options)`: `padding`, `cornerRadius`, `maxWidth`, `minWidth`, `minHeight`, `lineHeight`, `format` ([docs](https://elicitjs.github.io/marks/sticker.md))
- `plot.text(options)`: `orientation`, `format`, `wrap`, `lineHeight` ([docs](https://elicitjs.github.io/marks/text.md))
- `plot.textX(options)` ([docs](https://elicitjs.github.io/marks/text.md))
- `plot.textY(options)` ([docs](https://elicitjs.github.io/marks/text.md))
- `plot.tick(options)`: `orientation`, `inset`, `length` ([docs](https://elicitjs.github.io/marks/tick.md))
- `plot.tickX(options)` ([docs](https://elicitjs.github.io/marks/tick.md))
- `plot.tickY(options)` ([docs](https://elicitjs.github.io/marks/tick.md))
- `plot.track(options)`: `path`, `join` ([docs](https://elicitjs.github.io/marks/track.md))
- `plot.trend(options)`: `anchor`, `probe`, `grip`, `handles`, `handleSize`, `handleColor` ([docs](https://elicitjs.github.io/marks/trend.md))
- `plot.trendBand(options)`: `render`, `levels`, `samples`, `seed`, `sigma`, `distribution`, `anchor`, `probe`, `grip`, `handles`, `handleSize`, `handleColor` ([docs](https://elicitjs.github.io/marks/trend.md))
- `plot.waffle(options)`: `orientation`, `unit`, `multiple`, `gap`, `shape`, `showEmpty`, `emptyFill` ([docs](https://elicitjs.github.io/marks/waffle.md))
- `plot.waffleX(options)` ([docs](https://elicitjs.github.io/marks/waffle.md))
- `plot.waffleY(options)` ([docs](https://elicitjs.github.io/marks/waffle.md))
## elements
Chart elements draw a scale: axes, grids and legends.
Universal options: `id`, `edit`, `edits`, `field`, `table`.
- `elements.axis(options)`: `channel`, `anchor`, `transform`, `ticks`, `tickValues`, `tickFormat`, `tickSize`, `tickPadding`, `title`, `titleAngle`, `stroke`, `strokeWidth`, `line`, `fill`, `fontSize`, `fontFamily`, `fontWeight`, `labelAngle`, `titleFill`, `titleFontSize`, `titleFontWeight`, `titlePadding`, `titleAnchor`, `labelAlign`, `labelOffset`, `offset`, `grid`, `handleColor`, `handleSize` ([docs](https://elicitjs.github.io/marks/axes.md))
- `elements.axisRadial(options)`: `channel`, `channels`, `outerRadius`, `innerRadius`, `bandWidth`, `ticks`, `tickValues`, `tickFormat`, `tickSize`, `tickPadding`, `bands`, `title`, `fill`, `stroke`, `strokeWidth`, `fontSize` ([docs](https://elicitjs.github.io/marks/axis-radial.md))
- `elements.axisX(options)` ([docs](https://elicitjs.github.io/marks/axes.md))
- `elements.axisY(options)` ([docs](https://elicitjs.github.io/marks/axes.md))
- `elements.grid(options)`: `channel`, `ticks`, `tickValues`, `stroke`, `strokeWidth`, `strokeDash`, `opacity`, `zero`, `bandPosition` ([docs](https://elicitjs.github.io/marks/axes.md))
- `elements.gridX(options)` ([docs](https://elicitjs.github.io/marks/axes.md))
- `elements.gridY(options)` ([docs](https://elicitjs.github.io/marks/axes.md))
- `elements.legend(options)`: `channel`, `anchor`, `orientation`, `swatchSize`, `gap`, `labelWidth`, `rampLength`, `rampThickness`, `ticks`, `tickFormat`, `title`, `row`, `stroke`, `fill`, `fontSize`, `handleColor`, `handleSize` ([docs](https://elicitjs.github.io/marks/legend.md))
- `elements.legendColor(options)` ([docs](https://elicitjs.github.io/marks/legend.md))
- `elements.legendSize(options)` ([docs](https://elicitjs.github.io/marks/legend.md))
- `elements.legendSymbol(options)` ([docs](https://elicitjs.github.io/marks/legend.md))
## edit
Edits map a gesture back through a scale to write a column.
Universal options: `type`, `name`, `gesture`, `channel`, `channels`, `when`, `pick`, `threshold`, `scope`, `constrain`, `guide`, `stage`, `advance`, `target`, `cardinality`, `inverts`, `viewport`, `magnifies`, `table`, `apply`, `targets`, `cursor`, `grabs`.
- `edit.axis.scale(options)`: `field`, `mode` ([docs](https://elicitjs.github.io/editing/axis.md))
- `edit.brushRect(options)`: `edgeInset`, `resize`, `move` ([docs](https://elicitjs.github.io/editing/handles.md))
- `edit.brushSpan(options)`: `edgeInset`, `spans` ([docs](https://elicitjs.github.io/editing/handles.md))
- `edit.create(options)`: `defaults` ([docs](https://elicitjs.github.io/editing/existence.md))
- `edit.custom(options)`: `defaults`, `into`, `inline`, `multiline`, `spans` ([docs](https://elicitjs.github.io/editing/gestures.md))
- `edit.cycle(options)` ([docs](https://elicitjs.github.io/editing/gestures.md))
- `edit.editText(options)`: `inline`, `multiline` ([docs](https://elicitjs.github.io/marks/sticker.md))
- `edit.geo.brush(options)`: `resize`, `move`, `edgeInset` ([docs](https://elicitjs.github.io/marks/geo.md))
- `edit.geo.create(options)`: `defaults` ([docs](https://elicitjs.github.io/marks/geo.md))
- `edit.geo.createRect(options)`: `defaults`, `width`, `height`, `edgeInset` ([docs](https://elicitjs.github.io/marks/geo.md))
- `edit.geo.draw(options)`: `minDist`, `into`, `defaults` ([docs](https://elicitjs.github.io/marks/geo.md))
- `edit.geo.move(options)`: `mode` ([docs](https://elicitjs.github.io/marks/geo.md))
- `edit.geo.moveSeries(options)` ([docs](https://elicitjs.github.io/marks/geo.md))
- `edit.hierarchy.nest(options)`: `defaults` ([docs](https://elicitjs.github.io/marks/hierarchy.md))
- `edit.legend.category(options)` ([docs](https://elicitjs.github.io/editing/legend.md))
- `edit.legend.value(options)` ([docs](https://elicitjs.github.io/editing/legend.md))
- `edit.line.anchor(options)`: `into`, `series` ([docs](https://elicitjs.github.io/editing/sweep.md))
- `edit.line.draw(options)`: `along`, `value`, `samples`, `minDist`, `series`, `into`, `defaults` ([docs](https://elicitjs.github.io/editing/sweep.md))
- `edit.line.moveSeries(options)` ([docs](https://elicitjs.github.io/editing/sweep.md))
- `edit.line.newSeries(options)`: `along`, `value`, `samples`, `series` ([docs](https://elicitjs.github.io/editing/sweep.md))
- `edit.line.removeSeries(options)`: `series` ([docs](https://elicitjs.github.io/editing/sweep.md))
- `edit.line.sweep(options)`: `mode` ([docs](https://elicitjs.github.io/editing/sweep.md))
- `edit.move(options)`: `mode` ([docs](https://elicitjs.github.io/editing/gestures.md))
- `edit.moveSpan(options)` ([docs](https://elicitjs.github.io/editing/handles.md))
- `edit.network.connect(options)`: `defaults` ([docs](https://elicitjs.github.io/marks/network.md))
- `edit.network.reverse(options)` ([docs](https://elicitjs.github.io/marks/network.md))
- `edit.network.rewire(options)` ([docs](https://elicitjs.github.io/marks/network.md))
- `edit.rank(options)` ([docs](https://elicitjs.github.io/editing/gestures.md))
- `edit.remove(options)` ([docs](https://elicitjs.github.io/editing/existence.md))
- `edit.resize(options)` ([docs](https://elicitjs.github.io/editing/gestures.md))
- `edit.rotate(options)`: `relativeTo`, `pivot`, `fold` ([docs](https://elicitjs.github.io/editing/gestures.md))
- `edit.scale.categories(options)`: `field`, `mode` ([docs](https://elicitjs.github.io/editing/axis.md))
- `edit.select(options)`: `exclusive`, `toggle`, `multi` ([docs](https://elicitjs.github.io/editing/external-controls.md))
- `edit.set(options)` ([docs](https://elicitjs.github.io/editing/external-controls.md))
- `edit.slide(options)`: `axis`, `increase`, `extent`, `mode` ([docs](https://elicitjs.github.io/editing/gestures.md))
- `edit.stack.cut(options)`: `defaults`, `label` ([docs](https://elicitjs.github.io/editing/sweep.md))
- `edit.stack.edge(options)` ([docs](https://elicitjs.github.io/editing/handles.md))
- `edit.stack.merge(options)` ([docs](https://elicitjs.github.io/editing/sweep.md))
- `edit.toggle(options)`: `defaults` ([docs](https://elicitjs.github.io/editing/gestures.md))
- `edit.trend.intercept(options)`: `anchor`, `probe` ([docs](https://elicitjs.github.io/marks/trend.md))
- `edit.trend.interceptSpread(options)`: `anchor`, `probe` ([docs](https://elicitjs.github.io/marks/trend.md))
- `edit.trend.slope(options)`: `anchor`, `probe` ([docs](https://elicitjs.github.io/marks/trend.md))
- `edit.trend.slopeSpread(options)`: `anchor`, `probe` ([docs](https://elicitjs.github.io/marks/trend.md))
- `edit.view.pan(options)`: `limit` ([docs](https://elicitjs.github.io/editing/axis.md))
- `edit.view.zoom(options)`: `factor`, `limit`, `minSpan`, `min`, `max`, `mode` ([docs](https://elicitjs.github.io/editing/axis.md))
- `edit.waffle.fill(options)` ([docs](https://elicitjs.github.io/marks/waffle.md))
- `edit.when.alt(options)` ([docs](https://elicitjs.github.io/editing.md))
- `edit.when.far(options)` ([docs](https://elicitjs.github.io/editing.md))
- `edit.when.modifier(options)` ([docs](https://elicitjs.github.io/editing.md))
- `edit.when.near(options)` ([docs](https://elicitjs.github.io/editing.md))
- `edit.when.nearWithin(options)` ([docs](https://elicitjs.github.io/editing.md))
- `edit.when.noAlt(options)` ([docs](https://elicitjs.github.io/editing.md))
- `edit.when.noModifier(options)` ([docs](https://elicitjs.github.io/editing.md))
- `edit.when.noShift(options)` ([docs](https://elicitjs.github.io/editing.md))
- `edit.when.shift(options)` ([docs](https://elicitjs.github.io/editing.md))
## constraints
Constraints are rules over the dataset. Each one rejects or repairs every edit.
Universal options: `table`.
- `constraints.clamp(options)`: `min`, `max`, `field` ([docs](https://elicitjs.github.io/constraints.md))
- `constraints.contain(options)`: `parent`, `child`, `maxDepth`, `maxChildren` ([docs](https://elicitjs.github.io/marks/hierarchy.md))
- `constraints.count(options)`: `max`, `strategy` ([docs](https://elicitjs.github.io/constraints.md))
- `constraints.custom(options)` ([docs](https://elicitjs.github.io/constraints.md))
- `constraints.follow(options)`: `field`, `lead` ([docs](https://elicitjs.github.io/constraints.md))
- `constraints.maintainSum(options)`: `total`, `field`, `strategy` ([docs](https://elicitjs.github.io/constraints.md))
- `constraints.monotonic(options)`: `field`, `along`, `direction`, `series` ([docs](https://elicitjs.github.io/constraints.md))
- `constraints.ordering(options)`: `field`, `strategy` ([docs](https://elicitjs.github.io/constraints.md))
- `constraints.snap(options)`: `step`, `origin`, `field` ([docs](https://elicitjs.github.io/constraints.md))
- `constraints.spacing(options)`: `field`, `min`, `series` ([docs](https://elicitjs.github.io/constraints.md))
- `constraints.symmetric(options)`: `field`, `about` ([docs](https://elicitjs.github.io/constraints.md))
- `constraints.unique(options)`: `field`, `max`, `strategy` ([docs](https://elicitjs.github.io/constraints.md))
## layout
Layouts arrange and space marks in pixel space after each edit, writing the settled boxes back to the data.
Universal options: `table`, `where`.
- `layout.column(options)`: `gap`, `in` ([docs](https://elicitjs.github.io/layout.md))
- `layout.custom(options)` ([docs](https://elicitjs.github.io/layout.md))
- `layout.dodge(options)`: `gap`, `in` ([docs](https://elicitjs.github.io/layout.md))
- `layout.grid(options)`: `columns`, `gap`, `in` ([docs](https://elicitjs.github.io/layout.md))
- `layout.hierarchy.contain(options)` ([docs](https://elicitjs.github.io/layout.md))
- `layout.network.force(options)` ([docs](https://elicitjs.github.io/layout.md))
- `layout.network.layered(options)` ([docs](https://elicitjs.github.io/layout.md))
- `layout.network.tree(options)` ([docs](https://elicitjs.github.io/layout.md))
- `layout.pack(options)`: `gap`, `keep`, `in` ([docs](https://elicitjs.github.io/layout.md))
- `layout.row(options)`: `gap`, `in` ([docs](https://elicitjs.github.io/layout.md))
- `layout.tidy(options)`: `snap`, `gap`, `in` ([docs](https://elicitjs.github.io/layout.md))
## guides
Guides draw reference lines and interaction state. They never write data.
Universal options: `id`.
- `guides.cellGrid(options)`: `padding` ([docs](https://elicitjs.github.io/guides.md))
- `guides.crosshair(options)`: `x`, `y`, `readout`, `stroke`, `strokeDash`, `fontSize`, `format`, `touch` ([docs](https://elicitjs.github.io/guides.md))
- `guides.custom(options)`: `tracksPointer` ([docs](https://elicitjs.github.io/guides.md))
- `guides.image(options)`: `src`, `x`, `y`, `fit`, `position`, `repeat`, `opacity` ([docs](https://elicitjs.github.io/guides.md))
- `guides.options(options)`: `labelOffset`, `size`, `control` ([docs](https://elicitjs.github.io/guides.md))
- `guides.prompt(options)`: `y` ([docs](https://elicitjs.github.io/guides.md))
- `guides.proximity(options)`: `mark`, `stroke`, `strokeDash`, `strokeWidth`, `opacity` ([docs](https://elicitjs.github.io/guides.md))
- `guides.quadrants(options)`: `x`, `y` ([docs](https://elicitjs.github.io/guides.md))
- `guides.region(options)`: `x`, `y`, `fill`, `opacity`, `stroke`, `label` ([docs](https://elicitjs.github.io/guides.md))
- `guides.remaining(options)`: `field`, `total`, `unit`, `format`, `anchor`, `label`, `fill`, `fontSize` ([docs](https://elicitjs.github.io/guides.md))
- `guides.rule(options)`: `x`, `y`, `stroke`, `strokeDash`, `strokeWidth`, `opacity`, `label` ([docs](https://elicitjs.github.io/guides.md))
- `guides.sliderTrack(options)`: `format` ([docs](https://elicitjs.github.io/guides.md))
- `guides.tip(options)`: `mark`, `text`, `anchor`, `dx`, `dy`, `fill`, `stroke`, `fontSize`, `format`, `touch` ([docs](https://elicitjs.github.io/guides.md))
## looks
Looks change how the finished chart is drawn: by hand, or through a shader. Experimental.
Universal options: `scope`.
- `looks.cartoon(options)`: `levels`, `outline`, `ink` ([docs](https://elicitjs.github.io/looks.md))
- `looks.custom(options)`: `uniforms`, `seed` ([docs](https://elicitjs.github.io/editing/gestures.md))
- `looks.halftone(options)`: `size`, `angle` ([docs](https://elicitjs.github.io/looks.md))
- `looks.rough(options)`: `roughness`, `fill`, `seed` ([docs](https://elicitjs.github.io/looks.md))
- `looks.sketch(options)`: `amount`, `grain`, `seed` ([docs](https://elicitjs.github.io/looks.md))
## widgets
Widgets are complete survey instruments. Each returns a spec.
- `widgets.allocation(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.histogram(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.interval(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.labeledValue(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.likert(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.lineCone(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.matrix(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.multipleChoice(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.probabilityTokens(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.ranking(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.region(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.slider(options)` ([docs](https://elicitjs.github.io/widgets.md))
- `widgets.thermometer(options)` ([docs](https://elicitjs.github.io/widgets.md))
## format
Formatters turn a value into a string for a label or an axis.
- `format.number(options)` ([docs](https://elicitjs.github.io/json.md))
- `format.percent(options)` ([docs](https://elicitjs.github.io/json.md))
- `format.prefix(options)` ([docs](https://elicitjs.github.io/json.md))
- `format.si(options)` ([docs](https://elicitjs.github.io/json.md))
- `format.suffix(options)` ([docs](https://elicitjs.github.io/json.md))
- `format.time(options)` ([docs](https://elicitjs.github.io/json.md))