# Charts

Charts from the kit: a component for each chart people use (`LineChart`,
`BarChart`, `PieChart`, `HeatMap`, `SankeyChart`, …), and `Chart` for one of
your own, its marks written as children. They draw on a canvas, follow the
page's colours light and dark, take a million points, and say what they show
to a screen reader. Back to the [map](README.md).

```mote
// docs: whole
state rows: json = [{day: "Mon", visitors: 820, orders: 41}, {day: "Tue", visitors: 932, orders: 48}, {day: "Wed", visitors: 901, orders: 52}, {day: "Thu", visitors: 934, orders: 47}, {day: "Fri", visitors: 1290, orders: 66}, {day: "Sat", visitors: 1330, orders: 72}, {day: "Sun", visitors: 1320, orders: 70}]

column gap=24 padding=16
  LineChart data=rows x="day" y="visitors" label="Visitors this week"
  Chart data=rows x="day" label="Visitors and orders"
    Bar y="visitors" label="Visitors"
    Line y="orders" label="Orders" axis="right" dots=true
    Rule y=1000 label="target"
```

## Mental model

- **A chart is data and marks.** The data is rows of records (`[{day, visitors}]`),
  a record of columns (`{t: [...], v: [...]}`), or a list of numbers. A mark
  says how fields are drawn: a line through `visitors`, bars of `orders`. A
  component such as `LineChart` is a chart whose marks are made for you from
  its props; `Chart` is one whose marks you write.
- **Every number is worked out off the page.** The scales, the ticks, the
  stacks, the bins, a line reduced to what its pixels can show, what is under
  the pointer: all of it is the *plot* battery's (`batteries/plot`, Rust run as
  WebAssembly), in a worker the charts share. The page sends its data there
  once, as columns, and from then on asks only for pictures: "this view, this
  size". What comes back is a draw list (rectangles, paths, arcs, labels as
  numbers) that the page paints on a canvas.
- **Words are the page's.** An axis's ticks come back as numbers; the page
  writes them with [`fmt`](words.md) and [`time`](language.md#time) in its own
  language, measures them, and turns, thins or shortens them so that none
  touches another.
- **Nothing a frame needs waits.** While a new picture is on its way, the last
  one is drawn moved and stretched as the view moved; the answer comes a few
  milliseconds later and replaces it.
- **The data is followed.** Assign new rows, and the chart draws them. Push
  rows onto the list it was given, and only the new rows are sent: a line fed
  sixty times a second costs a row a frame, not the whole line.

## A chart for each kind

Every component takes `data=`, a `label=` (its name for a screen reader, and
what the PNG and CSV are called), `height=`, and the props of its kind. Fields
are named as text: `x="day"`.

### Lines and areas

```mote
// docs: whole
state rows: json = [{month: "Jan", desktop: 186, mobile: 80}, {month: "Feb", desktop: 305, mobile: 200}, {month: "Mar", desktop: 237, mobile: 120}, {month: "Apr", desktop: 73, mobile: 190}, {month: "May", desktop: 209, mobile: 130}, {month: "Jun", desktop: 214, mobile: 140}]
state cfg: json = [{key: "desktop", label: "Desktop"}, {key: "mobile", label: "Mobile"}]

column gap=24 padding=16
  LineChart data=rows x="month" config=cfg curve="smooth" dots=true
  AreaChart data=rows x="month" config=cfg stacked=true
  AreaChart data=rows x="month" config=cfg stack="expand" label="Share by device"
```

| Chart | Written | |
|---|---|---|
| line | `LineChart data=rows x="day" y="visitors"` | one series |
| multi-line | `LineChart data=rows x="day" config=[{key: "a", label: "A"}, {key: "b"}]` | a series each; a legend |
| step line | `LineChart … curve="step"` | `curve`: `linear` (unsaid), `smooth` (never overshoots), `step` |
| moving average | `LineChart … average=7` | each line the mean of its last 7 rows |
| area | `AreaChart data=rows x="day" y="visitors" gradient=true` | |
| stacked area | `AreaChart … config=cfg stacked=true` | |
| 100% area | `AreaChart … config=cfg stack="expand"` | each x adds up to the whole |
| stream | `AreaChart … config=cfg stack="stream" curve="smooth"` | about a middle that moves as little as it can |

`scale="time"` (or `"utc"`) reads x as moments in milliseconds: ticks fall on
calendar boundaries (whole hours, midnights, the 1st of a month) in the
reader's zone (`zone="UTC"` for UTC), across a change of the clocks, and each
says only what changed: `06:00`, `12:00`, `Nov 3`, `Dec`, `2027`. Unsaid, x is
read from the data: words are categories, numbers are numbers. `yScale=` is
`"log"`, `"symlog"` or `"sqrt"`; `yDomain=[0, 100]` fixes the value axis.

### Bars

```mote
// docs: whole
state rows: json = [{month: "Jan", desktop: 186, mobile: 80}, {month: "Feb", desktop: 305, mobile: 200}, {month: "Mar", desktop: 237, mobile: 120}]
state cfg: json = [{key: "desktop", label: "Desktop"}, {key: "mobile", label: "Mobile"}]
state budget: json = [{step: "Revenue", change: 420}, {step: "Costs", change: -160}, {step: "Gross", change: 0, total: true}, {step: "Wages", change: -120}, {step: "Net", change: 0, total: true}]

column gap=24 padding=16
  BarChart data=rows x="month" config=cfg
  BarChart data=rows x="month" config=cfg orientation="horizontal" stacked=true
  WaterfallChart data=budget x="step" y="change" total="total" labels=true
```

| Chart | Written | |
|---|---|---|
| grouped bars | `BarChart data=rows x="month" config=cfg` | side by side |
| stacked | `BarChart … stacked=true` | |
| 100% | `BarChart … stack="expand"` | |
| horizontal | `BarChart … orientation="horizontal"` | |
| sorted | `BarChart … sort="desc"` | by the first series |
| lollipop | `LollipopChart data=rows x="cause" y="n"` | a line and a dot |
| dumbbell | `DumbbellChart data=rows x="team" from="before" to="after"` | two values a category, joined |
| waterfall | `WaterfallChart data=rows x="step" y="change" total="total"` | each bar starts where the last ended; a `total` row stands from zero |
| Pareto | `ParetoChart data=rows x="cause" y="n"` | largest first, the running share on a second axis |
| histogram | `Histogram data=rows value="height" bins="fd"` | `bins`: `"sturges"` (unsaid), `"fd"` (Freedman–Diaconis), a width |
| bullet | `BulletChart data=kpis name="name" value="value" target="target" ranges=["poor", "ok", "good"]` | each row on a scale of its own |

`labels=true` writes each value on its bar; `xChars=3` cuts the categories'
words to three letters; `radius=` rounds the bars' ends.

### Distributions and points

| Chart | Written | |
|---|---|---|
| box plot | `BoxPlot data=rows x="team" y="weight"` | quartiles, median, whiskers to 1.5 IQR, outliers |
| violin | `ViolinChart data=rows x="team" y="weight"` | the density of each group's values, its quartiles inside |
| scatter | `ScatterChart data=rows x="height" y="weight" series="team"` | a colour and a shape per `series` |
| bubble | `ScatterChart … size="age"` | the area follows `size` |
| connected scatter | `ScatterChart … connect=true` | joined in the rows' order |
| with a fit | `ScatterChart … trend="linear"` (or `"loess"`) | the line and its 95% band |

### Grids

```mote
// docs: whole
state busy: json = [{day: "Mon", hour: "9h", n: 12}, {day: "Mon", hour: "10h", n: 30}, {day: "Tue", hour: "9h", n: 18}, {day: "Tue", hour: "10h", n: 44}]
state kept: json = [{cohort: "Jan", week: "W0", share: 1}, {cohort: "Jan", week: "W1", share: 0.62}, {cohort: "Feb", week: "W0", share: 1}, {cohort: "Feb", week: "W1", share: 0.58}]

column gap=24 padding=16
  HeatMap data=busy x="hour" y="day" value="n" labels=true
  CohortChart data=kept cohort="cohort" period="week" value="share"
```

| Chart | Written | |
|---|---|---|
| heat map | `HeatMap data=rows x="hour" y="day" value="n"` | `labels=true`, `diverge=true` (a ramp through the ground), `domain=[0, 1]` |
| calendar | `CalendarHeatMap data=rows date="date" value="commits"` | a cell a day, weeks across, a block a year |
| cohort | `CohortChart data=rows cohort="month" period="week" value="kept"` | shares, written in the cells |

### Round charts

```mote
// docs: whole
state browsers: json = [{browser: "Chrome", visitors: 275}, {browser: "Safari", visitors: 200}, {browser: "Firefox", visitors: 187}, {browser: "Other", visitors: 90}]

row gap=16 padding=16 flex-wrap=wrap
  PieChart data=browsers value="visitors" name="browser" donut=true labels="percent"
    text "752" font-size=24 font-weight=700
  GaugeChart value=72 label="Uptime score" bands=[50, 80, 100]
```

| Chart | Written | |
|---|---|---|
| pie, donut | `PieChart data=rows value="visitors" name="browser" donut=true` | children go in the middle; `labels=true` or `"percent"` |
| radial bars | `RadialChart data=rows value="visitors" name="browser" max=300` | a ring a row |
| gauge | `GaugeChart value=72 min=0 max=100 bands=[50, 80, 100]` | |
| radar | `RadarChart data=rows x="skill" config=cfg grid="circle"` | a spoke a row, a shape a series |
| polar area | `PolarAreaChart data=rows value="n" name="month"` | equal slices, each as far out as its value |

### Money, flows, trees, time

| Chart | Written | |
|---|---|---|
| candlestick | `CandlestickChart data=rows x="at" open="o" high="h" low="l" close="c" volume="vol"` | the volume in a pane below; both zoom together |
| OHLC | `CandlestickChart … ohlc=true` | ticks instead of candles |
| funnel | `FunnelChart data=rows name="stage" value="n"` | the share of the first, and of the step before, in the tooltip |
| Sankey | `SankeyChart data=links from="from" to="to" value="n"` | a row a link |
| treemap | `TreemapChart data=nodes name="name" parent="parent" value="size"` | squarified; `parent` names a row's parent (none for the top) |
| sunburst | `SunburstChart data=nodes name="name" parent="parent" value="size"` | the same tree as rings |
| timeline (Gantt) | `GanttChart data=rows start="start" end="end" task="task" name="who"` | without `task`, each bar in the first lane free |

### Small charts

```mote
// docs: whole
state accounts: json = [{id: 1, name: "Ada", trend: [3, 5, 4, 8, 6, 9]}, {id: 2, name: "Ben", trend: [9, 7, 8, 4, 5, 3]}]

column gap=8 padding=16
  for a in accounts key=a.id
    row gap=12 align-items=center
      text a.name width=80
      Sparkline data=a.trend
      Sparkline data=a.trend kind="bar"
      Sparkline data=[1, -1, 1, 1, -1] kind="winloss"
```

`Sparkline data=numbers kind="line"` (or `"area"`, `"bar"`, `"winloss"`):
96 × 24, no axes, no legend, `tooltip=true` to point at it.

## Chart: marks of your own

`Chart` draws the marks written under it, on one set of axes:

```mote
// docs: whole
state days: json = [{day: 1, visitors: 820, low: 760, high: 880, orders: 41}, {day: 2, visitors: 932, low: 870, high: 990, orders: 48}, {day: 3, visitors: 901, low: 850, high: 960, orders: 52}, {day: 4, visitors: 1290, low: 1200, high: 1370, orders: 66}]

Chart data=days x="day" label="Visitors, with their range, and orders"
  Band lower="low" upper="high"
  Line y="visitors" label="Visitors"
  Bar y="orders" label="Orders" axis="right"
  Rule y=1000 label="target"
  Note x=4 y=1290 label="launch"
```

| Mark | Props | |
|---|---|---|
| `Line y=` | `label color curve dots dash width axis stack by mean` | `dash=1`…`4` a pattern; `by="region"` a line a value of that field; `mean=7` the trailing mean of 7 rows |
| `Area y=` | `label color curve stack offset gradient opacity axis by` | marks of one `stack` stand on one another; `offset`: `"expand"`, `"center"`, `"stream"` |
| `Bar y=` | `label color stack offset axis radius labels by` | bars of different stacks stand side by side |
| `Point y=` | `label color size by shape connect radius axis` | |
| `Rule y=100` or `Rule x=…` | `label color dash axis` | a line across (or up) at a value |
| `Band lower= upper=` | `label color opacity axis` | wears the colour of the series before it |
| `ErrorBar lower= upper=` | `y label color axis` | |
| `Trend y=` | `method span band label color` | a fitted line through the chart's points |
| `Note x= y= label=` | | words at a place |

- `axis="right"` puts a mark on a second value axis; `right={format:
  "percent", domain: [0, 1]}` says how that axis is read.
- `facet="region"`: a small chart for each value of that field, sharing their
  scales (small multiples).
- The marks may also be given as a list: `Chart marks=[{kind: "line", y:
  "visitors"}, …]`, each record as the mark's props with its `kind`.
- A mark is an element that says `data-mark` (its record, as JSON); the chart
  reads its children's, as `flow` reads its nodes. Components of your own may
  write one.

## Data

| Shape | Example | |
|---|---|---|
| rows | `[{day: "Mon", visitors: 820}, …]` | read once, field by field, into columns |
| columns | `{t: [1767225600000, …], v: [12.5, …]}` | a million points cost one copy |
| numbers | `[3, 5, 4, 8]` | the values, and their index along x (sparklines) |

- A field's values are numbers, words (categories, in the order first met),
  moments (milliseconds; a text like `"2026-03-01"` is read too) or `none`
  (a gap: a line breaks there).
- Categories on a band axis are in their order of first appearance;
  `sort="desc"` orders bars by value.
- **A chart follows its data.** New rows (a new list) redraw it. Rows pushed
  onto the same list, with x still rising, are sent alone; with `window=600`
  the chart keeps only the newest 600, whatever the page's list holds; or let
  the page drop its oldest (`feed.shift()`), and the chart drops as many.

## Large data

What a view shows is worked out from what can be seen in it, so the cost of a
frame follows the pixels, not the rows:

- **A line** keeps, in each pixel column, its first and last point and its
  least and most (the "M4" reduction); the least and most of any run of rows
  come from a pyramid of the column, made once. A million points pan and zoom
  with each picture costing a few milliseconds in the worker and well under
  one on the page ([bench/charts](../bench/charts/README.md)). `reduce="lttb"`
  keeps a set number of points for their shape instead; `reduce="none"` draws
  every one.
- **A scatter** is drawn point by point while 5,000 or fewer are in view;
  past that, as a density (each 2 px cell as dark as the points in it). The
  nearest point to the pointer is found from a grid of the data.
- **Bars** narrower than a pixel are drawn a pixel column at a time (the
  tallest bar under it); zoomed in, only the bars in view are laid out.
- **A heat map** is drawn from the grid nearest a pixel: 1000 × 1000 cells
  become about 500 × 500 at first, and each cell itself when zoomed in.
- **A chart scrolled away** (a row of a `for … virtual` list) lets go of its
  data in the worker; it is sent again if the row comes back.

## Interactions

All optional, as props:

| Prop | Does |
|---|---|
| `tooltip=false` | No tooltip. Lines, areas and bars share one along x; points, cells and slices have their own. |
| `crosshair=true` | A line at the pointer's x on a chart that has none. |
| `legend=true` / `false` | Unsaid: a legend where there is more than one series. Each entry is a button that hides and shows its series. |
| `hidden=list` | The series hidden (their numbers), set and read. |
| `zoom=true` | The wheel with Ctrl or ⌘ held, or a pinch, zooms along x about the pointer; a drag pans; across (or with Shift) the wheel pans; a double press shows all. A wheel alone scrolls the page. |
| `range=view` | The x view, `[from, to]` in the data's units (none: all), set and read. |
| `brush=true` | A drag picks a range (`picked=`, set and read); a press elsewhere lets it go; Shift and a drag pans. |
| `pick=f` | A press on a mark: `f({kind, series, label, row, x, y, values})`. |
| `group="sales"` | Charts of one group share the pointer and the view. |
| `download=true` | PNG and CSV buttons over the chart. |

The `chart` element under the kit's components hands `change` a JSON string:
`{type: "pick" | "brush" | "range" | "legend", …}`.

## Accessibility

- Each chart is `role=img` named by `label=`, and described: how many points,
  x from what to what, each series' least, most, mean, first and last.
- Its numbers are in a table a screen reader reads and no one sees: the first
  200 rows, and the rest in brief in its caption.
- An agent that reads the page as text ([`mote.read()`](agents.md#mote-the-page-without-a-picture))
  gets the same: the chart's name and that description on one line, the
  table when it asks for that chart; its legend's entries are buttons it
  can press.
- It takes the keyboard: ← and → walk the points (the tooltip follows, and
  what it says is said), ↑ and ↓ the series there, Home and End the ends, +
  and − zoom, 0 shows all, Enter presses, Escape lets go. The focus is shown.
- Colour is never alone: each series has a marker shape of its own (in the
  legend, on the points), `dash=` gives lines patterns, labels and tooltips
  name every value.

## Theming

Series take `--chart-1` … `--chart-8` where the page sets them (`root
var-chart-1=brand`), else a palette with a light and a dark step each (blue,
orange, green, amber, pink, violet, teal, brown). A series' `color` may be
`"chart-3"` or any CSS colour. Axes, grid and labels take the page's roles
(`dim`, `line`, `fg`, `bg`); up and down (candles, waterfalls, win-loss) take
`ok` and `danger`. All of them are read again when the scheme changes. With
less motion asked for (the system's wish, or `root motion="less"`), a chart
does not ease from one picture to the next.

## Pitfalls

- **Give x a scale when it is a moment.** Unsaid, numbers are numbers: a time
  in milliseconds is drawn as a big number. `scale="time"`.
- **Push, do not rebuild, to stream.** A new list each tick is sent whole each
  tick; `xs.push(row)` (and `xs.shift()`) is a row a tick.
- **Facets do not stack.** Marks in a faceted chart are drawn each alone.
- **The treemap, sunburst and Sankey layouts are a battery of their own**,
  carried by a page that names one of them (`kind="sankey"` as written, as the
  kit's components do).
- **`label=` names the chart**, and the PNG and CSV it downloads: say it.

## The older charts

`BarChart`, `LineChart`, `AreaChart`, `PieChart`, `RadarChart` and
`RadialChart` take the props they always took (`config`, `x`, `orientation`,
`stacked`, `curve`, `dots`, `labels`, `gradient`, `indicator`, `legend`,
`grid`, `yAxis`, `xChars`, `size`, `innerRadius`, `track`, `max` …) and are
drawn this way now. What looks different: the bars, lines and slices are
painted on a canvas (sharp at any density); a legend shows by itself where
there is more than one series (`legend=false` hides it); the category labels
are measured, so as many fit as can; a pie's tooltip also gives the share.
`ChartContainer`, `ChartTooltip`, `ChartLegend`, `ChartLayer` and
`ChartDataTable` stay as parts for a chart of your own made of boxes.

## In the source

| What | Where |
|---|---|
| The components and the marks | `kit/charts.mote` |
| The `chart` element: data into columns, the worker, painting, the axes' words, the pointer, the keyboard, groups | `runtime/page/chart.mote`, part `CH` |
| Scales, ticks (time in a zone), nice domains | `batteries/plot/scale.rs` |
| A chart's data kept: columns, a rolling window, the pyramid, the scatter's grid, the heat map's levels | `batteries/plot/data.rs` |
| Reduction: M4, LTTB, density, the heat map's level | `batteries/plot/reduce.rs` |
| Stacks, bins, quartiles, densities, fits, running sums, ranks | `batteries/plot/stats.rs` |
| Pie, radial, radar, funnel, lanes, calendar | `batteries/plot/layout.rs` |
| Treemap, sunburst, Sankey (the layouts battery) | `batteries/plot/hier.rs`, `treescene.rs`, `batteries/layouts/lib.rs` |
| The picture of each kind, and the draw list | `batteries/plot/scene.rs`, `out.rs` |
| What is under the pointer | `batteries/plot/hit.rs` |
| The wasm calls | `batteries/plot/wasm.rs`, `wire.rs` |
| Built, and sent with a page | `compiler/build.rs` (`plot`, `layouts`); `compiler/src/build.rs` (`CHI`); `compiler/src/tables.rs` (`chart`) |
| Recorded behaviour | `compiler/src/tests_plot.rs`, `tests/charts`, `tests/charts_big`, `tests/kit_base.real.mjs` (Chart), `bench/charts` |
