# dartwork-mpl — full agent reference (llms-full.txt)

This file is generated from the canonical sources listed below and verified
without mutation at docs-build time. Do **not** hand-edit; edit the upstream
files, regenerate this authority explicitly, and then rebuild the docs.

Companions:

- `CLAUDE.md` / `AGENTS.md` — 30-second onboarding for agents.
- `llms.txt` — link index following the llmstxt.org spec.


---
## Quickstart
# Quick Start

A minimal end-to-end workflow: apply a style, create a figure, and
export it. Skim this in five minutes — you'll already know enough to
ship a publication-grade plot.

:::{tip}
A **live ruler** below this section maps `dm.fs(n)` / `dm.fw(n)` / `dm.lw(n)`
to actual point sizes and stroke widths under each preset — drag the sliders
to read off the resolved values without leaving the docs.

If the slider doesn't load (JavaScript disabled, terminal browsers,
or offline LLM contexts), the [static reference table](#fs-fallback-table)
further down lists the same base values per preset.
:::

## At-a-glance ROI

| What used to hurt                   | dartwork-mpl                                    |
| ----------------------------------- | ----------------------------------------------- |
| Hand-tuning `figsize` and `dpi`     | `plt.subplots(figsize=dm.figsize("15cm", "wide"))`  |
| `tight_layout` clipping labels      | `dm.simple_layout(fig)` — deterministic, content-aware |
| Reaching for hex codes              | `color="dc.teal3"` (the curated `dc.*` system), plus `"oc.*"`, `"tw.*"`, `"md.*"`, `"ad.*"`, `"cu.*"`, `"pr.*"` for third-party systems |
| Saving in 3 formats                 | `dm.save_formats(fig, "out", formats=("png", "svg", "pdf"))` |
| Catching margin / overflow problems | `dm.validate_with_fixes(fig)`                   |

Here's a typical matplotlib figure, then the same figure with dartwork-mpl:

::::{tab-set}

:::{tab-item} ✨ With dartwork-mpl

<!-- snippet: no-run — save_and_show writes files + opens a preview -->
```python
import matplotlib.pyplot as plt
import dartwork_mpl as dm
import numpy as np

dm.style.use("scientific")  # curated fonts, colors, line weights

# width = physical figure width, aspect = height/width ratio
fig, ax = plt.subplots(figsize=dm.figsize("15cm", "wide"))

x = np.linspace(0, 10, 200)
ax.plot(x, np.sin(x), color="dc.teal3", label="signal", lw=dm.lw(1.5))
ax.set_xticks(np.arange(0, 11, 2))
ax.set_xlabel("Time [s]")
ax.set_ylabel("Amplitude")
ax.legend()

dm.simple_layout(fig)           # content-aware margins
dm.save_and_show(fig, "first")  # save + inline preview
```

:::

:::{tab-item} 🔧 Vanilla matplotlib

```python
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(5.91, 3.94), dpi=300)

x = np.linspace(0, 10, 200)
ax.plot(x, np.sin(x), color="#1c7ed6", label="signal", lw=1.5)
ax.set_xticks(np.arange(0, 11, 2))
ax.set_xlabel("Time [s]", fontsize=7.5)
ax.set_ylabel("Amplitude", fontsize=7.5)
ax.legend(fontsize=6.5)

fig.tight_layout()
fig.savefig("output.png", dpi=300, bbox_inches="tight")
plt.show()
```

:::

::::

:::{figure} images/quickstart_first_figure.svg
:alt: Scientific-style line chart created with dartwork-mpl
:width: 100%

The same chart rendered with `dm.style.use("scientific")` and
`plt.subplots(figsize=dm.figsize(…, …))` — professional typography,
optimized margins, and named colors.
:::

**Drag the slider to compare — same data, different styling:**

```{raw} html
:file: images/compare_slider.html
```

Same data, same plotting logic — the difference is one `dm.style.use()`
call, the `width` / `aspect` arguments on `dm.figsize`, named colors,
and `simple_layout`.

**What each dartwork-mpl call does:**

| Call                                          | Purpose                                                                            |
| --------------------------------------------- | ---------------------------------------------------------------------------------- |
| `dm.style.use("scientific")`                  | Sets palette, fonts, line weights — see [Styles](styles.md)                        |
| `dm.figsize("15cm", "wide")`                  | Physical width plus an aspect token, returned as the inches tuple `figsize=` expects. |
| `dm.fs(0)`                                    | Returns the base font size of the active preset (`fs(2)` = base + 2 pt, and so on) |
| `dm.simple_layout(fig)`                       | Deterministic content-aware margins (replaces `tight_layout`)                      |
| `dm.save_and_show(fig, "first")`              | Saves multi-format and previews inline in the notebook                             |

(fs-fallback-table)=
### Static reference: `dm.fs(n)` resolved per preset

This is the **JS-free equivalent of the live ruler at the top of the
page** — same numbers, same purpose. Useful when JavaScript is
disabled (AI agents, terminal browsers) or when copying numbers into a
spreadsheet. Each row is the **base font size** that ships with the
preset's `font-*.mplstyle`; `dm.fs(n)` returns ``base + n`` (in
points), `dm.fw(n)` and `dm.lw(n)` apply analogous offsets to font
weight and stroke width.

| Preset         | Base `font.size` (pt) | Typical `dm.fs(2)` (pt) |
| -------------- | --------------------: | ----------------------: |
| `scientific`   | 7.5                   | 9.5                     |
| `report`       | 8.0                   | 10.0                    |
| `web`          | 11.0                  | 13.0                    |
| `presentation` | 19.5                  | 24.7                    |
| `poster`       | 12.0                  | 14.0                    |
| `minimal`      | 7.5                   | 9.5                     |

Source of truth: `src/dartwork_mpl/asset/mplstyle/font-*.mplstyle`. If
those values change, regenerate this table.

## Choosing a purpose and canvas

Explicit width/height/style and journal/template constraints take priority,
then prior project context. Whatever is left unnamed comes from the library,
so every agent and every run draws the same canvas: the purpose picks the
preset and `dm.figsize_for()` gives its default size.

| Context | Existing preset | Canvas when no size is named |
|---|---|---|
| Paper / journal / 논문 | `scientific` | `dm.figsize_for()`: one column (9 cm), two columns (17 cm) for dense data or a grid; the venue's column width wins |
| Report / document / dashboard / 보고서 | `report` | `dm.figsize_for()`: 9 / 12 / 14.5 / 17 cm by data density, 4:3 |
| Talk / slides / presentation / 발표 | `presentation` | `dm.figsize_for()`: 10.5 cm tall under a 16:9 slide's title; wide 11.4 cm for up to 4 x positions, 15.4 cm up to 6, 23.4 cm for more, 4+ series or a second y axis; `"compact"` 11.4 cm for two charts side by side; `dm.figsize_for("full_slide")` (25.4 × 14.29 cm) only for a whole 16:9 slide with no title |

```python
import matplotlib.pyplot as plt
import dartwork_mpl as dm

dm.style.use("report")
years = list(range(2015, 2024))
fig, ax = plt.subplots(figsize=dm.figsize_for(n_points=len(years), n_series=2))
plt.close(fig)
```

These are defaults, not size limits: a size the user, a journal or a template
names wins, through `dm.figsize`. A requested element (a title, gridlines)
keeps the preset's style for every detail the request does not name. For a
final paper figure, ask one short question about single/double columns or the
venue width if it is unknown; for a draft, use the default, say which preset
and size you used and invite correction. Plot text is English unless the user asks for
another language, whatever the conversation language; use a `-kr` preset for
Korean text. A geometry-only edit keeps the
selected preset, data and other style choices. Presets supply defaults;
explicit user overrides take priority. Use `dm.fs(n)`, `dm.fw(n)` and
`dm.lw(n)` for preset-relative changes; retain requested absolute sizes,
widths and colors. Literal-size/width lint warnings are advisory: inspect
and report them without replacing explicit values or hiding warnings.

Both width and height are freely chosen physical dimensions. For example,
this complete script requests 24 × 12 cm using mixed units:

<!-- canvas-explicit-height-example -->
```python
import matplotlib.pyplot as plt
import dartwork_mpl as dm

dm.style.use("report")  # illustrative choice for a report
fig, ax = plt.subplots(figsize=dm.figsize("24cm", "120mm"))
ax.plot([0, 1, 2], [1, 3, 2], linewidth=dm.lw(0))
ax.set_xlabel("Time")
ax.set_ylabel("Value", fontsize=dm.fs(0), fontweight=dm.fw(0))
dm.simple_layout(fig, margin="2%")
dm.save_formats(fig, "output/explicit-canvas", formats=("png", "pdf"),
                bbox_inches=None)
plt.close(fig)
```

The same canvas can use `dm.figsize("240mm", "120mm")` or
`dm.figsize(dm.inch(24 / 2.54), dm.inch(12 / 2.54))`. Native `plt.figure`
with GridSpec/nested GridSpec is also valid for custom panel allocations.
`dm.simple_layout` adjusts content margins without resizing the canvas.
`bbox_inches=None` is already the export default and retains that canvas;
`"tight"` crops to content and can change its dimensions. DPI controls PNG
pixel density, not physical size; PNG sizes quantize to whole pixels while
PDF retains physical page size. The `oversize-width` lint warning above
17 cm asks for a page-fit review; it must not override an explicit size.

## Prompt-driven native customization

Ask for the change in ordinary language, for example “Use report style and
make only the axis labels one step larger.” The agent selects the native
matplotlib label Text objects; the user need not supply plotting code.
On an existing report figure, the corresponding edit is:

```python
for label in (ax.xaxis.label, ax.yaxis.label):
    label.set_fontsize(label.get_fontsize() + 1)
```

This changes only axis-label size and retains tick labels, title, legend,
data, colors, canvas and preset. Keep existing axes/layout when labels still
fit. If a refit is necessary, reuse the original `simple_layout` kwargs, grid
and margins instead of blindly rerunning margin=0 defaults. Disclose necessary
axes or anchored-legend movement rather than promising fixed pixel positions.
One current-relative step is +1 pt (+2.6 pt under `presentation`, `dm.fs(1) - dm.fs(0)`); repeating “one more” increments the retained current value.
`dm.fs(1)` instead means global `font.size` + one step; it does not inspect the
current label or its role-specific default. `dm.lw(n)` adds `n` steps to global
`lines.linewidth`, and `dm.fw(n)` adds `100*n` to global `font.weight`.
An absolute request such as “12 pt” retains that exact value.

Apply the preset before retained overrides and local artist edits. Use native
setters for lines/custom dashes, spines, ticks, tick labels, axis labels, grids
and other supported properties. Discover them through getters,
`artist.properties()`, `help(type(artist))` or official docs for the installed
matplotlib version. Resolve the panel/series/artist before editing; ask one
short question only for material ambiguity. The 18 templates are starting
points, not chart limits. Choose unspecified defaults from data, purpose,
panel density and categorical text; avoid unsolicited palette/legend changes.
See [native styling recipes](recipes.md). Agents can read the bundled native
examples with `dm.get_prompt("03-recipes")` in installed Python, or the MCP
`dartwork-mpl://guide/recipes` resource; `dm.get_prompt("01-policy")` gives the policy.

## Installed Python agents: read, execute, review, revise

No MCP or repository checkout is required. Read installed guidance and both
template tiers with existing Python APIs:

```python
from importlib.resources import files
from pathlib import Path
import dartwork_mpl as dm

print(dm.get_agent_doc("AGENTS"))
print(dm.get_prompt("01-policy"))
print(dm.get_prompt("03-recipes"))
print(dm.get_prompt("02-anti-patterns"))

# Ranking metadata is available without MCP; source_path is repo-relative.
root = files("dartwork_mpl").joinpath("asset", "prompt", "05-templates")
Path("output").mkdir(exist_ok=True)
for tier in ("basic", "advanced"):
    match = dm.find_template("line time series", top_k=1, tier=tier)[0]
    folder = root if tier == "basic" else root.joinpath("advanced")
    source = folder.joinpath(f"{match['template_id']}.py").read_text(encoding="utf-8")
    print(tier, match["template_id"], match["source_path"])
    Path(f"output/template-{tier}.py").write_text(source, encoding="utf-8")
    print(source)  # inspect/adapt; retrieving a template does not execute it
```

Use `dm.lint_code(code)` for source findings and `dm.validate_figure(fig)` for
the full visual warning list. Keep all fields, including `CHECK_FAILED`;
`dm.save_formats` returns `None`, not a validation report. Save PNG/PDF with
`bbox_inches=None`, open the real images and inspect them before handoff.
`dm.validate_data` filters NaN/Inf rows by default; to keep missing-reading line
gaps use `allow_nan=True` with separate shape/alignment/finite-value checks.
It is distinct from the MCP `validate_plot_data` tool.

Follow the [complete executable workflow](../ai/installed_python.md) for a
native Figure, full report, PNG/PDF review and a separate-stem revision.
Use [native multi-panel recipes](layout.md#native-multi-panel-layouts) or
`dm.get_prompt("03-recipes")` for equal grids, global ratios, spans/nesting and
whole-canvas 70:30 or independent 40:60 / 70:30 rows.

## Creating Figures with `dm.figsize`

`dm.figsize(width, aspect)` is the sanctioned way to size a figure. It
returns the inch tuple matplotlib's `figsize=` argument expects, so you
keep the native `plt.subplots` / `plt.figure` constructors and never
hand-roll inches yourself.

```python
# Physical width plus an aspect token (default aspect="standard" = 3/4)
fig, ax = plt.subplots(figsize=dm.figsize("13cm"))
fig, ax = plt.subplots(figsize=dm.figsize("15cm", "wide"))
fig, ax = plt.subplots(figsize=dm.figsize(dm.cm(11.3), "square"))

# Apply a style preset separately
dm.style.use("scientific")
fig, ax = plt.subplots(figsize=dm.figsize("13cm", "wide"))

# Stacked styles
dm.style.stack(["font-report", "theme-dark"])
fig, axes = plt.subplots(2, 2, figsize=dm.figsize("17cm", "standard"))

# Academic-column shortcuts
fig, ax = plt.subplots(figsize=dm.figsize(dm.col1, "golden"))  # 9 cm
fig, ax = plt.subplots(figsize=dm.figsize(dm.col2, "cinema"))  # 17 cm
```

**Width** accepts:

- A unit-suffixed string: `"13cm"`, `"9.5cm"`, `"6.7in"`, `"170mm"`,
  `"24pt"`
- A `Length` value: `dm.cm(11.3)`, `dm.inch(4.6)`, `dm.mm(170)`,
  `dm.pt(24)`, or `dm.length("13cm")` (string parser)
- The sugar constants `dm.col1` (9 cm) and `dm.col2` (17 cm)

Bare `int` / `float` are rejected — the unit must always be explicit.

**The second argument** picks the figure's height in one of four
equivalent forms; use whichever reads naturally for the call site:

| Form                      | Example                              | Notes                                            |
| :------------------------ | :----------------------------------- | :----------------------------------------------- |
| Aspect token              | `dm.figsize("13cm", "wide")`         | One of `square / portrait / tall / standard / golden / wide / a4 / slide / cinema / panoramic`. |
| Numeric ratio             | `dm.figsize("13cm", 0.6)`            | Positive `int` / `float` interpreted as `height / width`. |
| Unit-suffix string height | `dm.figsize("13cm", "8cm")`          | Width and height units may differ.               |
| `Length` value            | `dm.figsize("13cm", dm.cm(8))`       | Useful for `dm.col1` / `dm.col2` heights.        |

Bare numeric strings (`"0.5"`) and unknown aspect tokens raise
`ValueError` with a "did-you-mean" hint, so ambiguous inputs fail
loudly.

:::{note}
The 0.4-era constructors `dm.subplots` and `dm.figure` (and their
`figsize=` / `dpi=` arguments) were removed. Calls now raise
`AttributeError` / `TypeError` with a message naming the modern
`plt.subplots(figsize=dm.figsize(...))` form. See
[`asset/prompt/01-policy.md`](https://github.com/dartworklabs/dartwork-mpl/blob/main/src/dartwork_mpl/asset/prompt/01-policy.md)
for the full lint catalog.
:::

**Multi-panel figures:**

```python
fig, axes = plt.subplots(
    2, 2,
    figsize=dm.figsize("17cm", "standard"),
    width_ratios=[2, 1],
    height_ratios=[1, 2],
)

for ax in axes.flat:
    ax.plot(np.random.randn(100))

dm.simple_layout(fig)
```

## Adding color

dartwork-mpl ships its own curated palette — `dc.*` ("dartwork color"),
a 20-family v5 system with 10 perceptual steps per family — and registers six
third-party design systems alongside it. Use any named color anywhere
matplotlib accepts a color string:

```python
# Curated dartwork palette (recommended starting point)
ax.plot(x, y, color="dc.teal3")                   # cool blue
ax.fill_between(x, y1, y2, color="dc.orange1")     # warm accent
ax.bar(categories, values, color="dc.red1")      # bold call-out

# Third-party systems also available for cross-team consistency
ax.plot(x, y2, color="oc.blue5")                   # OpenColor
ax.plot(x, y1, color="tw.emerald500")              # Tailwind
```

**Discover what's available without leaving Python:**

```python
import dartwork_mpl as dm

dm.list_colors()[:2]        # → [{'name': 'amber', 'kind': 'sequential', ...}, ...]
dm.colors("teal", n=5)      # designed 5-color list
dm.show_colors(names=["teal"], n=5)  # preview swatches and ramps
```

See [Colors and Colormaps](colors.md) for the full palette reference,
or open the [interactive palette explorer](../color_system/colors.md)
to click-and-copy color names from your browser.

## Multi-panel layout

```python
import dartwork_mpl as dm
import numpy as np

dm.style.use("presentation")

x = np.linspace(0, 10, 100)
fig = plt.figure(figsize=dm.figsize("15cm", "wide"))
gs = fig.add_gridspec(1, 2, wspace=0.3)
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1])

ax1.plot(x, np.sin(x), color="dc.red1")
ax2.plot(x, np.cos(x), color="dc.teal3")

dm.label_axes([ax1, ax2])  # adds (a), (b) panel labels
dm.simple_layout(fig, gs=gs)
```

:::{figure} images/quickstart_multi_panel.svg
:alt: Two-panel layout with label_axes showing sin and cos
:width: 100%
:::

## Saving in multiple formats

```python
dm.save_formats(
    fig,
    "output/my_figure",
    formats=("png", "svg", "pdf"),
    dpi=300,
    validate=True,  # auto-check for overflow, overlap, etc.
)
```

## Catch problems before you export

`validate=True` above runs the same checks as the standalone
`validate_with_fixes` helper, which can also patch the easy issues
in-place:

```python
warnings, fixes = dm.validate_with_fixes(fig)
for w in warnings:         # each is a VisualWarning with fix suggestions
    print(w)
# e.g. MARGIN_ASYMMETRY → fix: dm.simple_layout(fig)
```

Use it in CI to fail a build when a figure breaks; use it locally to
get a one-line health check before you `save_formats`.

## Try the interactive UI

If you'd rather see the effect of every parameter before committing
it to code, dartwork-mpl ships a local web app that wires sliders to
your render function and exports the resulting Python script:

```bash
# 1. scaffold a starter viewer (first time only)
pip install "dartwork-mpl[ui]"
dartwork-mpl-ui init ./my-viewer --example simple

# 2. run it — opens the viewer in your default browser
cd my-viewer && python app.py
```

→ [Interactive UI guide](interactive.md)

## Next steps

::::{grid} 1 1 2 3
:gutter: 2

:::{grid-item-card} 🎨 Styles and Presets
Choose the right preset for your use case — papers, reports, slides, posters.

→ [Browse presets](styles.md)
:::

:::{grid-item-card} 🌈 Colors and Colormaps
Explore 900+ named palettes and perceptual OKLCH interpolation.

→ [See palettes](colors.md)
:::

:::{grid-item-card} 📐 Layout and Typography
Panel labels, arrows, font scaling, and margin optimization.

→ [Learn layout](layout.md)
:::

:::{grid-item-card} 💾 Save and Validation
Multi-format export + automatic visual quality checks.

→ [Export guide](save_export.md)
:::

:::{grid-item-card} 🛠️ Interactive UI
Tune fonts, line weights, margins with sliders. Export the exact
script that reproduces what you see.

→ [Interactive UI](interactive.md)
:::

:::{grid-item-card} 🔬 Diagnostics & Templates
`dm.show_colors()` / `plot_fonts()` for asset audit, plus ready-to-use plot
templates like `plot_diverging_bar`.

→ [Extras guide](extras.md)
:::

::::

:::{note}
**Upgrading from a previous PyPI release?** The
[Migration Guide](../migration.md) lists every renamed / removed name
since v0.4.0 with a side-by-side `Before → After` table — most call
sites are one-liners.
:::


---
## Native plot and installed Python recipes
# Recipes — Intent → Function Call

A short cookbook keyed by user intent. Each entry shows the canonical
native invocation. For full templates see
`dartwork-mpl://templates/{plot}`.

> **For a new figure**, pick and apply a style preset:
>
> ```python
> dm.style.use("scientific")   # or "report" / "presentation" / "minimal" / "poster" / "web" / "dark" / "*-kr"
> ```
>
> For a local revision, retain the existing preset and scoped overrides.
> Change the requested artist properties, then fit only if needed as below;
> do not reapply a preset or refit an already-fitting change.
> Presets provide defaults. Use `dm.fs(n)` / `dm.lw(n)` / `dm.fw(n)` for
> preset-relative intent; retain explicit absolute user values and colors.
> Literal-size/width warnings remain advisory: inspect and report them.
> The 18 templates are starters; native matplotlib chart types and properties
> remain available. Choose unspecified defaults from the data and purpose.
>
> Sub-1 **hairline literals** (`linewidth=0.3` for separator edges,
> `linewidth=0.5` for dashed reference lines) are kept as raw numbers
> on purpose — the lint policy explicitly allows them, and they need
> a stable positive value across presets. ``dm.lw(-1)`` would resolve
> to ``0`` for most presets, collapsing edges into the "no border"
> idiom.

## Choose the input version before a revision

For each logical input, keep its name, chosen version, SHA-256, source and
snapshot location visible beside the revision. Explicit requests settle the
choice; do not ask again when the requested version is clear.

| Request | Input choice |
| --- | --- |
| “Keep the previous data; change only the markers/style.” | Verify and reuse the retained bytes used by the previous figure, even if the upstream file changed. |
| “Use the current file.” | Read the authorized current bytes and pin them in a new revision; retain earlier snapshots and prior requested style edits. |
| Data version is materially ambiguous or prior evidence is unknown | Ask one relevant question before choosing; keep the original artifacts. |

Read only user/operator-authorized inputs. For native Python, save copies in
an authorized, user-owned project output area outside `datasets`. MCP instead
uses its operator-authorized private `storage_dir` and existing admission rules.
Never write upstream or collect unrelated files. Consume the pinned bytes/path,
rather than reopening
a mutable upstream path after hashing it. For style-only work, verify every
required input against its previous receipt. A missing/changed snapshot or
unknown input evidence needs clarification, never a silent current-file fallback.
Hashes establish byte identity, not freshness, permission or complete
reproducibility. An old snapshot is not evidence of the latest upstream data.
MCP uses its existing explicit Copy/Retained admission and receipts; native local
copies have no automatic MCP seven-day expiry or deletion guarantee.

## "Report style, only axis labels one step larger"

Agents translate the request into native artist edits; users need not write
plotting code. On an existing report figure, edit only the selected label Texts.
When revising retained source, insert the edit **after the original layout call**
(with its original kwargs), before the report/export block. Inspect the changed
content before deciding whether fitting is necessary.
For an in-memory figure, use its existing layout and artist handles directly.

```python
# Existing fig/ax; the original preset, plotting and layout have already run.
for label in (ax.xaxis.label, ax.yaxis.label):
    label.set_fontsize(label.get_fontsize() + 1)  # one more = current + 1 pt
fig.canvas.draw()  # inspect labels and measure actual Axes/legend bounds
# Continue with the existing report/export block, retaining the canvas.
```

An ordinary label enlargement permits necessary content fitting: if labels
clip or overlap, use the existing fitting method and settings as the starting
point, adjusting only the margins/spacing needed to fit. Keep the physical
canvas, panel/container allocations and explicit ratios, data, colors, other
typography and legend's intended location. Reuse the original `simple_layout`
kwargs/grid when applicable; do not reset to margin=0 defaults, introduce a new
layout engine or refit a change that already fits.

An explicit fixed Axes-position request overrides this fitting permission.
Preserve that geometry; disclose any clipping/conflict without claiming a
finished fit. Ask one relevant question only if a protected constraint must
change or the safe existing fitting method is unclear, retaining the original.
Explicit user instructions take precedence over these defaults.

Active native layout engines can move artists during draw/export. Preserve
their configuration, inspect the actual PNG/PDF, and compare bounds after both
drawing and exporting. Report any necessary Axes movement honestly; preserving
panel allocations does not imply fixed Axes data rectangles. Judge fit from
the actual content and requested constraints, not a universal pixel/mm tolerance.

For an explicit preset-relative request, `label.set_fontsize(dm.fs(1))` uses
global `font.size` + one step (1 pt; 2.6 pt under `presentation`), not
`axes.labelsize` or the current label size.
Repeat current-relative edits from the retained current value. For an absolute
request use `label.set_fontsize(12)` exactly. `dm.fw(1)` adds 100 to the global
base weight, while `dm.lw(1)` adds one step (1 pt; 2.6 pt under
`presentation`) to the global base line width.

## "A selected line: exact width, color and dash/dot spacing"

Resolve the series/panel first; `line` below is its saved existing artist
handle. Apply only the requested setters; do not append another `ax.plot` line.
For a request changing its width, color and nominal dash/dot path lengths:

```python
with plt.rc_context({"lines.scale_dashes": False}):
    line.set_linewidth(2.5)
    line.set_color("#235fa4")
    line.set_linestyle((0, (4, 2, 1, 2)))
```

This preserves the cap style. Change caps only when requested. The tuple gives
offset and alternating nominal on/off path lengths in points; round caps
extend visible ink and shorten visible gaps. Without `scale_dashes=False`,
lengths scale with line width by default. Keep that local context around line
creation or any later setter that rescales dashes when physical lengths must
stay fixed. For relative width use `line.get_linewidth() + delta`.
Check the rendered result; no single dash tuple fits every chart purpose.

### Keep a known Line2D legend sample in sync

A legend sample is a separate artist: editing a data line after legend creation
does not update its sample. For an existing plain `Line2D` series with a known
one-to-one default-handler legend mapping, apply the same requested dash setter
to its existing sample. Keep the legend object, location, text/order, frame and
all other handle properties. Do not call `ax.legend()` again or copy whole
artists with `update_from` (which can replace transforms and other properties).

This partial example requires the saved data-line handle `line` and the known
label `series_label`, with unique labels and default `Line2D` handlers established
by the original construction. The checks do not prove that a custom handler or
proxy represents the line; resolve such mappings from the original construction
or ask before editing. Do not infer the series from its current array index.

```python
from matplotlib.lines import Line2D

legend = ax.get_legend()
if (legend is None or type(line) is not Line2D or
        line not in ax.lines or line.get_label() != series_label):
    raise ValueError("Resolve the existing series and its known legend mapping")
texts = legend.get_texts()
labels = [text.get_text() for text in texts]
if labels.count(series_label) != 1:
    raise ValueError("Expected one known corresponding legend sample")
sample = legend.legend_handles[labels.index(series_label)]
if type(sample) is not Line2D:
    raise ValueError("Resolve the non-Line2D/custom legend sample explicitly")
# Requested nominal dash sequence; retain the existing scale_dashes policy.
for artist in (line, sample):
    artist.set_dashes((6, 2, 1, 2))
fig.canvas.draw()  # inspect both line and sample, then report/export
```

Place this patch after the original legend/layout construction in retained
source. For requested physical path lengths, use the local
`lines.scale_dashes=False` context described above around both setters; apply
only the requested width/color/cap setters to each corresponding artist. Render
and compare both samples and actual bounds. Do not reconstruct a legend to
repair an uncertain mapping or change unrelated properties to make it fit.

## "Only the left spine, x ticks, y tick labels or y grid"

These are independent examples: apply only the line(s) matching the request to
the resolved `ax`. Do not execute the whole block for a single-property edit.

```python
ax.spines["left"].set_color("black")
ax.spines["left"].set_linewidth(0.7)
ax.tick_params(axis="x", which="major", length=4, width=0.7)
ax.tick_params(axis="y", which="major", labelcolor="#235fa4", labelsize=10)
ax.grid(axis="y", which="major", visible=True, color="0.8", linewidth=0.3)
```

Axis labels (`ax.xaxis.label`, `ax.yaxis.label`) differ from tick labels
(`ax.get_xticklabels()`, `ax.get_yticklabels()`). Inspect `type(artist)`,
`artist.properties()`, getters or `help(type(artist))`; consult official docs
for the installed matplotlib version for unsupported or unfamiliar properties.
Ask one short question only if panel/series/property scope is materially unclear.

## File-only scripts: select the backend before creating figures

For standalone PNG/PDF export, start the process with `MPLBACKEND=Agg`, before
importing pyplot or creating figures: `MPLBACKEND=Agg python plot.py` (likewise
`plot-v2.py` and `pin-input.py`). This is scoped to file-only scripts; keep
interactive/notebook backend choices. `dm.figsize` returns the requested inch
tuple, but a GUI backend can quantize a Figure's size at creation. A local
macOS backend observation is not a universal limitation of `dm.figsize`.

Check `fig.get_size_inches()` after creation and after export against the
requested physical canvas. Keep `bbox_inches=None`, then inspect the saved
PDF page width/height (72 points per inch), not only the PNG pixel dimensions.
Report any mismatch and the backend actually used; do not silently resize the
canvas, change layout or blame the unit conversion. Agg avoids the observed
GUI quantization in these file-export examples; still check the actual PDF.

## "Exact canvas width and height (cm, mm or inches)"

Choose the preset by the policy's purpose/context rules first. This complete
example uses `report` as an illustrative selection and writes three equivalent
24 × 12 cm canvases using existing unit forms:

<!-- canvas-units-example -->
```python
import matplotlib.pyplot as plt
import dartwork_mpl as dm

dm.style.use("report")
for name, size in (
    ("cm", dm.figsize("24cm", "12cm")),
    ("mm", dm.figsize("240mm", "120mm")),
    ("in", dm.figsize(dm.inch(24 / 2.54), dm.inch(12 / 2.54))),
):
    fig, ax = plt.subplots(figsize=size)
    ax.plot([0, 1, 2], [1, 3, 2], linewidth=dm.lw(0))
    ax.set_xlabel("Time")
    ax.set_ylabel("Value", fontsize=dm.fs(0), fontweight=dm.fw(0))
    dm.simple_layout(fig, margin="2%")
    dm.save_formats(fig, f"output/canvas-{name}", formats=("png", "pdf"),
                    bbox_inches=None)
    plt.close(fig)
```

`bbox_inches=None` (the existing default) retains the canvas; `"tight"`
crops to content. DPI determines raster pixel density, not physical size;
PNG dimensions quantize to whole pixels. The `oversize-width` warning asks for
page-fit review and must not silently shrink an explicit 24 cm request.

For multi-panel work, native `plt.figure` + GridSpec/nested GridSpec are valid.
GridSpec ratios apply inside its assigned bounds: outer margins and
`wspace`/`hspace` mean a 7:3 grid alone does not allocate 70%/30% of the
whole canvas. For exact whole-canvas regions, use native container allocation
(e.g. `SubFigure`), keep titles, labels and local padding inside each container,
and measure the container bounding boxes to verify the requested allocation.
Keep that allocation distinct from row-specific ratios: two 50:50 rows can
contain 40:60 columns above and 70:30 columns below. Retain the selected preset
and data when changing geometry alone. Do not pass a `SubFigure` directly to
`dm.simple_layout`; this helper requires a parent `Figure`.

## Native multi-panel layouts

Use this setup, choose **one** construction below, then run the shared drawing
and export block. These are executable native matplotlib recipes, not another
layout API. Keep the existing preset, data, colors, fonts, legend and retained
scoped overrides when adapting an existing figure. The example uses a provisional
20 × 16 cm canvas; choose physical dimensions for your page or slide.

```python
import matplotlib.pyplot as plt
import numpy as np
import dartwork_mpl as dm

# Reuse the selected preset for geometry-only revisions.
dm.style.use("scientific")  # report/document: report; talk/slides: presentation
x = np.linspace(0, 12, 121)
fig = plt.figure(figsize=dm.figsize("20cm", "16cm"))
```

### Whole-figure estimate, template guidance and margin correction

`dm.figsize_grid("6cm", "standard", ncols=3, nrows=2, gap="0.6cm")`
returns a whole-figure size: width `3 * 6 + 2 * 0.6 = 19.2cm` and height
`2 * (6 * 0.75) + 0.6 = 9.6cm`. It does not create Axes or set GridSpec
spacing. The requested panel width and gap are inputs to that arithmetic;
labels, outer margins and native `wspace`/`hspace` determine the final Axes
rectangles and gaps. Neither exact 6cm Axes nor exact 0.6cm rendered gaps
are guaranteed. Render and measure the bounds below when those matter.

MCP `compose_layered_plot` returns a starting template (including its example
comments) and an annotation-layer checklist for the agent to adapt. Its
`applied`/`missing` lists use lexical detection in source, not rendered checks.
It does not rewrite code, execute a plot, allocate panels or repair spacing.
Installed Python users can read the same basic/advanced sources through
`importlib.resources`, as shown in the installed workflow below.

The bounded margin/convergence correction tracked by #209 is a separate
concern from template composition and figure-size arithmetic. The current
`dm.simple_layout` measures content and iteratively updates root GridSpec outer
margins, preserving native internal spacing. It does not solve nested local
spacing or guarantee that every label fits every requested canvas. Historical
`auto_layout` is removed; do not call it as an extra correction pass.
`simple_layout` returns `None`, not a convergence or validation report: inspect
`dm.validate_figure(fig)` findings and the actual PNG/PDF before accepting the
result. If content cannot fit the requested geometry, explain the constraint
and agree on a revision; do not silently delete data or shrink fonts.

### Equal grid

```python
gs = fig.add_gridspec(2, 2, wspace=0.5, hspace=0.65)
axes = {name: fig.add_subplot(gs[i // 2, i % 2])
        for i, name in enumerate("ABCD")}
```

### Global row and column ratios

Every row shares the 2:1 column widths; every column shares the 3:2 row heights.
These ratios concern data rectangles inside the grid, excluding gaps and outer
content margins. They do not partition the entire canvas into percentages.

```python
gs = fig.add_gridspec(2, 2, width_ratios=[2, 1], height_ratios=[3, 2],
                      wspace=0.5, hspace=0.65)
axes = {name: fig.add_subplot(gs[i // 2, i % 2])
        for i, name in enumerate("ABCD")}
```

### Spanning, asymmetric and nested

A spans both rows; D spans the lower right region. B/C share a nested grid.
The shared finish fits outer margins through the root `gs`; nested spacing
remains a native local choice.

```python
gs = fig.add_gridspec(2, 3, wspace=0.75, hspace=0.65)
inner = gs[0, 1:].subgridspec(1, 2, width_ratios=[1, 2], wspace=0.8)
axes = {"A": fig.add_subplot(gs[:, 0]),
        "B": fig.add_subplot(inner[0, 0]),
        "C": fig.add_subplot(inner[0, 1]),
        "D": fig.add_subplot(gs[1, 1:])}
```

### Whole-canvas top 70%, bottom 30%

Here `SubFigure` regions include all local labels and padding. Zero container
spacing makes their heights exactly 70%/30% of the canvas. This explicit 2×1
construction gives each row one full-width plot. Data rectangles become smaller
after local margins.

```python
rows = list(fig.subfigures(2, 1, height_ratios=[7, 3], hspace=0))
panels = rows
axes = {}
for name, panel in zip("AB", panels):
    width_cm = panel.bbox.width / fig.dpi * 2.54
    height_cm = panel.bbox.height / fig.dpi * 2.54
    local = panel.add_gridspec(
        1, 1, left=1.15 / width_cm, right=1 - 0.45 / width_cm,
        bottom=1.05 / height_cm, top=1 - 0.80 / height_cm)
    axes[name] = panel.add_subplot(local[0])
```

For a 2×2 variant with two equal panels per row, replace `panels = rows` with
`panels = [panel for row in rows for panel in row.subfigures(1, 2, wspace=0)]`
and use `zip("ABCD", panels)`. The row containers remain exactly 70%/30%.

### Whole-canvas rows 50:50, top widths 40:60, bottom 70:30

A single global `width_ratios` cannot express this. Allocate independent native
containers within each row. Every percentage includes that panel's labels and
padding; it is not a promise about its Axes data width.

```python
rows = list(fig.subfigures(2, 1, height_ratios=[1, 1], hspace=0))
panels = [*rows[0].subfigures(1, 2, width_ratios=[4, 6], wspace=0),
          *rows[1].subfigures(1, 2, width_ratios=[7, 3], wspace=0)]
axes = {}
for name, panel in zip("ABCD", panels):
    width_cm = panel.bbox.width / fig.dpi * 2.54
    height_cm = panel.bbox.height / fig.dpi * 2.54
    local = panel.add_gridspec(
        1, 1, left=1.15 / width_cm, right=1 - 0.45 / width_cm,
        bottom=1.05 / height_cm, top=1 - 0.80 / height_cm)
    axes[name] = panel.add_subplot(local[0])
```

### Shared drawing, measurement and export

Run this after the chosen construction. For the three ordinary grids use the
`simple_layout` line. For either whole-canvas container recipe **omit that line**:
the explicit native local margins above are the legitimate margin path.
The physical padding is a starting point for these labels, not a universal fit;
render, measure and adjust local margins if content does not fit.

```python
from dataclasses import asdict
from pathlib import Path
import json
from matplotlib.ticker import MaxNLocator

for i, (name, ax) in enumerate(axes.items()):
    ax.plot(x, np.sin(x + i), color="oc.blue9", label="Series 1")
    ax.plot(x, np.cos(x + i), color="oc.orange7", label="Series 2")
    ax.set(title=f"{name} · Signal", xlabel="Time (s)", ylabel="Response")
    ax.xaxis.set_major_locator(MaxNLocator(nbins=4))
    ax.yaxis.set_major_locator(MaxNLocator(nbins=4))
    ax.legend(loc="upper right", ncol=2)

# Ordinary GridSpec recipes only; omit for either SubFigure recipe.
dm.simple_layout(fig, gs=gs, margin="2mm")
fig.canvas.draw()
renderer = fig.canvas.get_renderer()
geometry = {"canvas_px": list(fig.bbox.bounds),
            "axes_data_px": {k: list(a.bbox.bounds) for k, a in axes.items()},
            "axes_content_px": {k: list(a.get_tightbbox(renderer).bounds)
                                for k, a in axes.items()}}
# For either container recipe, also record the allocated regions:
# geometry["rows_px"] = [list(row.bbox.bounds) for row in rows]
# geometry["panels_px"] = [list(panel.bbox.bounds) for panel in panels]
# Divide row heights by fig.bbox.height; panel widths by their row width.
# Compare those fractions to the requested ratios, separately from Axes bounds.
report = [asdict(item) for item in dm.validate_figure(fig)]
Path("output").mkdir(exist_ok=True)
Path("output/layout-geometry.json").write_text(json.dumps(geometry, indent=2))
Path("output/layout-report.json").write_text(json.dumps(report, indent=2))
dm.save_formats(fig, "output/layout-v1", formats=("png", "pdf"),
                bbox_inches=None)
```

`dm.simple_layout` needs a parent `Figure`; passing a `SubFigure` raises
`AttributeError` for missing `get_size_inches`. Passing a nested GridSpec with a
parent Figure walks to its root GridSpec and adjusts root outer margins; it
does not solve each nested region independently. Calling it on the root Figure
of a SubFigure tree is not a local-margin solution either. Do not insert fake
helper calls or silently change requested allocations to make validation pass.
Read the full report (including `CHECK_FAILED`), inspect the actual PNG and PDF,
and retain heuristic/advisory warnings with any explanation. Save a revision to
a new stem such as `layout-v2`; keep v1, exact source and geometry for review.

### Measured presentation text correction

For the two whole-canvas recipes above, a measured 20 × 16 cm render using
`presentation` clipped the leftmost `Response` y-label with the initial
1.15 cm local left margin. Increasing only that margin to 1.70 cm cleared
that overflow in both examples. After inspecting the full report and images,
a revision can replace the `local = panel.add_gridspec(...)` call inside the
existing panel loop with:

<!-- snippet: no-run -->
```python
# This measured example's candidate, not a universal fit value.
local = panel.add_gridspec(
    1, 1, left=1.70 / width_cm, right=1 - 0.45 / width_cm,
    bottom=1.05 / height_cm, top=1 - 0.80 / height_cm)
```

Rebuild the figure with that local edit, then repeat drawing, measurement,
validation and image review, saving to a new output stem. Keep the 20 × 16 cm
canvas, requested container ratios, data, colors, preset fonts and legend
anchors. The larger left margin makes the data Axes narrower; it does not
change the container allocations. The value 1.70 cm is a candidate for these
measured examples, not an automatic preset override. If too little data space
remains or content still clips, explain the constraint and ask which constraint
may change; do not silently shrink fonts, remove data, resize the canvas or
relocate legends. The scientific recipe defaults above remain unchanged.

## "Bar chart"

```python
fig, ax = plt.subplots(figsize=dm.figsize("13cm", "standard"))
ax.bar(categories, values, color="oc.blue5", edgecolor="white",
       linewidth=0.3)
ax.set_ylabel("Value")
ax.set_title("…", fontsize=dm.fs(1), fontweight=dm.fw(1))
dm.simple_layout(fig)
```

## "Horizontal bar comparison"

```python
fig, ax = plt.subplots(figsize=dm.figsize("13cm", "standard"))
ax.barh(categories, values, color="oc.blue5", edgecolor="white",
        linewidth=0.3)
ax.set_xlabel("Value")
ax.invert_yaxis()
dm.simple_layout(fig)
```

## "Grouped/dodged bar (multiple categories per group)"

```python
import numpy as np
x = np.arange(len(categories))
w = 0.27
fig, ax = plt.subplots(figsize=dm.figsize("15cm", "standard"))
ax.bar(x - w, series_a, w, color="oc.blue5", label="A",
       edgecolor="white", linewidth=0.3)
ax.bar(x, series_b, w, color="oc.green5", label="B",
       edgecolor="white", linewidth=0.3)
ax.bar(x + w, series_c, w, color="oc.orange5", label="C",
       edgecolor="white", linewidth=0.3)
ax.set_xticks(x); ax.set_xticklabels(categories)
ax.legend(fontsize=dm.fs(-1))
dm.simple_layout(fig)
```

## "Waterfall (incremental change)"

```python
fig, ax = plt.subplots(figsize=dm.figsize("15cm", "standard"))
ax.bar(labels, heights, bottom=baselines, color=colors,
       edgecolor="white", linewidth=0.3)
ax.axhline(0, color="oc.gray7", linewidth=0.3)
dm.simple_layout(fig)
```

## "Line chart, time series"

```python
fig, ax = plt.subplots(figsize=dm.figsize("15cm", "wide"))
ax.plot(t, y, color="oc.blue6", linewidth=dm.lw(0))
ax.set_xlabel("Time"); ax.set_ylabel("Signal")
dm.simple_layout(fig)
```

## "Scatter with trend"

```python
fig, ax = plt.subplots(figsize=dm.figsize("11cm", "square"))
ax.scatter(x, y, color="oc.blue5", edgecolor="white",
           linewidth=0.3, s=20)
dm.simple_layout(fig)
```

## "Heatmap / correlation matrix"

```python
fig, ax = plt.subplots(figsize=dm.figsize("11cm", "square"))
im = ax.imshow(matrix, cmap="viridis", aspect="auto")
cbar = fig.colorbar(im, ax=ax)
cbar.ax.tick_params(labelsize=dm.fs(-1))
dm.simple_layout(fig)
```

## "Stacked bar"

```python
fig, ax = plt.subplots(figsize=dm.figsize("13cm", "standard"))
ax.bar(x, a, color="oc.blue5", label="A",
       edgecolor="white", linewidth=0.3)
ax.bar(x, b, bottom=a, color="oc.green5", label="B",
       edgecolor="white", linewidth=0.3)
ax.legend(fontsize=dm.fs(-1))
dm.simple_layout(fig)
```

## "Twin axis"

```python
fig, ax1 = plt.subplots(figsize=dm.figsize("15cm", "wide"))
ax2 = ax1.twinx()
ax1.bar(x, precip, color="oc.blue3", alpha=0.7,
        edgecolor="white", linewidth=0.3)
ax2.plot(x, temp, color="oc.red6", marker="o", markersize=3,
         linewidth=dm.lw(0))
dm.simple_layout(fig)
```

## "Korean labels"

Apply the language preset before creating the figure:

```python
dm.style.use("report-kr")
fig, ax = plt.subplots(figsize=dm.figsize("13cm", "standard"))
ax.set_xlabel("월")
ax.set_ylabel("값")
dm.simple_layout(fig)
```

Untouched Korean axes read `50만 … 250만` and `23.01` / `16` dates and years
(no `년`). A unit in the label instead: `dm.axis_unit(ax, "y", label="인구
({unit}명)")` (`0, 0.2 … 1.0`; `dm.axis_unit_of(ax)` for value labels). Other
formats on request, one `dm.config` field each: `tick_years=4` (four-digit
years), `date_style="concise"` (`23, May, Sep`), `number_ladder="si"` (`0.5M`
in Korean figures). The override applies to what runs inside its `with`
block: wrap the code from figure creation to the last `dm.simple_layout`, or
set the field on `dm.config`.

## "Small multiples / faceted panels"

```python
fig, axes = plt.subplots(2, 2, figsize=dm.figsize("17cm", "standard"),
                         sharex=True, sharey=True)
for ax, (label, y) in zip(axes.flat, panels, strict=False):
    ax.plot(x, y, color="oc.blue6", linewidth=dm.lw(0))
    ax.text(0.02, 0.95, label, transform=ax.transAxes,
            ha="left", va="top",
            fontsize=dm.fs(0), fontweight=dm.fw(1))
dm.simple_layout(fig)
```

## "Polar / radar / wind rose"

```python
fig, ax = plt.subplots(figsize=dm.figsize("11cm", "square"),
                       subplot_kw={"projection": "polar"})
ax.plot(theta_closed, values_closed, color="oc.blue6", linewidth=dm.lw(0))
ax.fill(theta_closed, values_closed, color="oc.blue3", alpha=0.3)
ax.set_xticks(theta)
ax.set_xticklabels(categories, fontsize=dm.fs(-1))
dm.simple_layout(fig)
```

## "3D scatter / surface"

```python
fig, ax = plt.subplots(figsize=dm.figsize("13cm", "square"),
                       subplot_kw={"projection": "3d"})
ax.scatter(xs, ys, zs, color="oc.blue5", edgecolor="white",
           linewidth=0.3, s=20)
ax.set_xlabel("X"); ax.set_ylabel("Y"); ax.set_zlabel("Z")
dm.simple_layout(fig)
```

## "Multi-panel grid (a/b/c labels)"

`dm.label_axes` accepts `labels` for custom strings and `x` / `y` for
Axes-relative positions (values may extend outside 0–1). With `x="auto"`,
it uses -0.18 when an Axes has a y-label and -0.02 otherwise. `y=None`
(default) is 1.05, except that with `x="auto"` a left title (or a
centre/right one the letter would touch) takes the letter onto the title's
line, just before it. An explicit `y` (even `y=1.05`) keeps that height.
Extra compatible native `Text` properties, such as `color`,
`rotation` and `alpha`, pass through to `ax.text`:

```python
import matplotlib.pyplot as plt
import dartwork_mpl as dm

dm.style.use("scientific")
fig, axes = plt.subplots(2, 2, figsize=dm.figsize("17cm", "standard"),
                         gridspec_kw={"hspace": 0.5, "wspace": 0.35})
for ax in axes.flat:
    ax.plot([0, 1, 2], [1, 3, 2], color="oc.blue9")
dm.label_axes(axes, labels=["(a)", "(b)", "(c)", "(d)"], x=-0.02, y=1.05,
              color="black", rotation=0, alpha=0.9)
dm.simple_layout(fig)
```

`fmt`, `loc` and `xy` are not supported `label_axes` arguments. Use
`labels` for text and `x` / `y` for position. The helper supplies the Axes
transform and left/bottom alignment itself; for custom transforms or
alignment, replace the preceding `dm.label_axes(...)` call with the native
calls below over the same Axes collection, before `dm.simple_layout(fig)`. Do not run both label calls:

<!-- snippet: no-run -->
```python
for ax, label in zip(axes.flat, ["(a)", "(b)", "(c)", "(d)"]):
    ax.text(0.02, 0.98, label, transform=ax.transAxes,
            fontsize=dm.fs(1), fontweight=dm.fw(1), ha="left", va="top")
```

## "Compare style presets side by side"

```python
import matplotlib.pyplot as plt
import dartwork_mpl as dm

presets = ["scientific", "report", "presentation", "minimal"]
fig, axes = plt.subplots(2, 2, figsize=dm.figsize("16cm", "standard"))
for ax, preset in zip(axes.flat, presets):
    with dm.style.context(preset):       # scoped — does not leak
        ax.plot(x, y, color="dc.teal2", linewidth=dm.lw(0))
        ax.set_title(f"'{preset}'",
                     fontsize=dm.fs(1), fontweight=dm.fw(1))
dm.simple_layout(fig)
```

## "Save in multiple formats"

```python
dm.save_formats(fig, "output/figure", formats=("svg", "png", "pdf"),
                bbox_inches=None, dpi=300)
```

## Interpreting optional source auto-fixes

Import `ast` and parse the complete source string with `ast.parse(code)`
before lint/fix. This nonexecuting preflight can detect malformed Python;
repair syntax errors in the source first. Some lint checks skip malformed
source, so empty findings or MCP's “No issues found” do not prove valid
syntax. Parsing and linting do not prove that code can compile, execute or
render correctly, and do not authorize executing arbitrary source.

For a source string named `code`, import `apply_lint_fixes` from
`dartwork_mpl.lint`, then call
`fixed_code, applied, unfixed = apply_lint_fixes(code)`. The MCP tool of the
same name returns a dict with those three keys. Neither route executes the
submitted source. Inspect the diff and every remaining finding: `applied`
locations refer to the original source, `unfixed` to the returned source.

The fixer needs an existing dartwork import binding and locally proven
calls. It can redirect pyplot's `style.use` with one supported literal
preset to that binding, or replace a no-argument `fig.tight_layout()` on a
proven pyplot-created Figure with `simple_layout(fig)`. Not all aliases or
constructors are recognized. It does not invent imports, infer the current
Figure for `plt.tight_layout()`, transfer layout kwargs, or rewrite
unsupported/dynamic styles, bare native Figure layout calls or arbitrary
artist properties. A suggestion alone does not establish an applicable fix.

Unchanged bytes with empty `applied` mean no correction was applied;
nonempty `unfixed` still needs attention, while empty `unfixed` means no
reported findings, not that all checks ran. Changed source can also retain
`unfixed` findings. Preserve the user's style, colors, legend and layout
intent, including intentional overrides. Stop retrying identical source.
Resolve bindings, arguments and intended behavior before making a scoped
source edit, then parse/lint again. For trusted code you choose to execute,
retain the normal runtime validation and actual image-review steps below.

## Native file input: pin the bytes actually consumed

This standalone example expects an authorized UTF-8 `measurements.csv` with
`x,y` columns (blank `y` means a missing reading). Save it as `pin-input.py`
and run `MPLBACKEND=Agg python pin-input.py` for file-only export.
Choose the input and a **new** revision directory in the configuration below.
The small JSON receipt is a local example, not a public schema/API. Treat its
paths as trusted, user-owned project paths, not untrusted service requests.
Keep the receipt, snapshot, exact source, PNG/PDF and full validation findings.

<!-- pinned-input-example -->
```python
import csv
import hashlib
import io
import json
from dataclasses import asdict
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import dartwork_mpl as dm

# User-authorized paths; output must be outside datasets. Never reuse a directory.
choice = "current"  # initial/current-file request; use "previous" for old data
upstream = Path("measurements.csv")
previous_receipt = Path("output/figure-v1/input.json")
revision = Path("output/figure-v1")
logical_name = "measurements"

if choice == "current":
    raw = upstream.read_bytes()  # read upstream once; copy AND parse these bytes
    source = str(upstream.resolve())
    selected_from = None
elif choice == "previous":
    old = json.loads(previous_receipt.read_text(encoding="utf-8"))
    if old["logical_name"] != logical_name:
        raise ValueError("Unknown prior input: clarify the intended version")
    raw = Path(old["snapshot"]).read_bytes()  # missing: stop, do not read upstream
    if hashlib.sha256(raw).hexdigest() != old["sha256"]:
        raise ValueError("Prior snapshot changed: clarify the intended version")
    source = old["source"]
    selected_from = str(previous_receipt.resolve())
else:
    raise ValueError("Choose current or previous explicitly")

rows = list(csv.DictReader(io.StringIO(raw.decode("utf-8"), newline="")))
x = np.array([float(row["x"]) for row in rows])
y = np.array([float(row["y"]) if row["y"] else np.nan for row in rows])
if not np.isfinite(x).all() or np.isinf(y).any() or np.isfinite(y).sum() < 2:
    raise ValueError("Expected finite x and at least two finite y observations")
x, y = dm.validate_data(x, y, allow_nan=True)

revision.mkdir(parents=True, exist_ok=False)  # refuse overwrite, even on rerun
snapshot = revision / "input.csv"
with snapshot.open("xb") as stream:
    stream.write(raw)
receipt = dict(logical_name=logical_name, choice=choice, source=source,
               sha256=hashlib.sha256(raw).hexdigest(),
               snapshot=str(snapshot.resolve()), selected_from=selected_from)
with (revision / "input.json").open("x", encoding="utf-8") as stream:
    json.dump(receipt, stream, indent=2)
print(json.dumps(receipt, indent=2))  # show the selected version, not only a filename

# Keep the existing construction/overrides when adapting this to a revision.
dm.style.use("report")
fig, ax = plt.subplots(figsize=dm.figsize("13cm", "standard"))
ax.plot(x, y, color="oc.blue9", label="Observed")
ax.set(xlabel="Time (s)", ylabel="Response")
ax.legend(loc="upper left")
dm.simple_layout(fig, margin="2mm")
code = Path(__file__).read_text(encoding="utf-8")
with (revision / "plot.py").open("x", encoding="utf-8") as stream:
    stream.write(code)
report = {"lint": [asdict(item) for item in dm.lint_code(code)],
          "visual": [asdict(item) for item in dm.validate_figure(fig)]}
with (revision / "report.json").open("x", encoding="utf-8") as stream:
    json.dump(report, stream, indent=2)
dm.save_formats(fig, str(revision / "figure"), formats=("png", "pdf"),
                bbox_inches=None)
```

For the next style-only revision, retain the construction and all earlier edits,
set `choice = "previous"`, point `previous_receipt` at the previous revision's
`input.json`, and choose a new directory such as `output/figure-v2`. An explicit
current-file request instead sets `choice = "current"` with the authorized
upstream path and another new directory. Never relabel the old receipt as current.
Missing/unreadable receipts, absent snapshots, mismatched hashes or unknown
required inputs stop this example; disclose the problem and ask which available
version to use. Do not repair evidence or silently substitute another file.
Then follow the full report and actual PNG/PDF review steps below. These local
copies persist until the user manages them; they do not inherit MCP expiry.

## Installed Python: native Figure, full report and review

Save this as `plot.py` and run `MPLBACKEND=Agg python plot.py` with the
installed core package for file-only export. Blank
readings represent gaps here. `validate_data` defaults to filtering NaN/Inf
rows, which can close a line gap; `allow_nan=True` preserves them but also
allows infinity, so check shape/alignment/domain separately. This helper
returns cleaned arrays; MCP `validate_plot_data` is a distinct JSON tool.

```python
from dataclasses import asdict
from pathlib import Path
import json
import matplotlib.pyplot as plt
import numpy as np
import dartwork_mpl as dm

# Blank observations represent missing readings, so retain a visible line gap.
x_input = [0, 1, 2, 3, 4, 5]
y_input = [1.0, 1.8, None, 2.1, 1.7, 2.5]
x = np.asarray(x_input, dtype=float)
y = np.asarray([np.nan if v is None else v for v in y_input], dtype=float)
if x.ndim != 1 or y.ndim != 1 or x.shape != y.shape:
    raise ValueError("Expected aligned one-dimensional x/y observations")
if not np.isfinite(x).all() or np.isinf(y).any() or np.isfinite(y).sum() < 2:
    raise ValueError("Expected finite x and at least two finite y observations")
x, y = dm.validate_data(x, y, allow_nan=True)

dm.style.use("report")
fig, ax = plt.subplots(figsize=dm.figsize("13cm", "standard"))
line, = ax.plot(x, y, color="oc.blue9", label="Observed")
ax.set(xlabel="Time (s)", ylabel="Response", title="Missing reading retained")
ax.legend(loc="upper left")
dm.simple_layout(fig, margin="2mm")

# Save this complete script as plot.py before running it.
source_path = Path(__file__)
code = source_path.read_text(encoding="utf-8")
report = {"lint": [asdict(item) for item in dm.lint_code(code)],
          "visual": [asdict(item) for item in dm.validate_figure(fig)]}
Path("output").mkdir(exist_ok=True)
Path("output/figure-v1.py").write_text(code, encoding="utf-8")
Path("output/figure-v1-report.json").write_text(json.dumps(report, indent=2))
dm.save_formats(fig, "output/figure-v1", formats=("png", "pdf"),
                bbox_inches=None)
```

`dm.review(fig, "output/figure-v1")` does the save and the full
`validate_figure` report in one call, adds a summary of the figure and writes
`output/figure-v1.review.json`; for v2, `dm.review(fig, "output/figure-v2",
baseline="output/figure-v1", allow=[...])` lists every summary entry that
changed, and `Review.unexpected` the ones no `allow=` pattern covers. It is
experimental and judges nothing; `complete=True` only means every check ran.

Inspect all fields of the report, then open the **actual PNG** and the PDF
(or a rasterized PDF page) at target size. Check the gap, clipping, labels,
fonts and legend. No image reader means this step remains incomplete.
`CHECK_FAILED` is incomplete validation; `save_formats` returning `None` is
not a clean report. Keep advisory/fallback warnings and explain intentional
choices; don't silently change retained user overrides to silence warnings.

After reviewing v1, copy `plot.py` to `plot-v2.py`, replace every `figure-v1`
output stem in the copy with `figure-v2`, and insert the following immediately
before `source_path = Path(__file__)`. Run `MPLBACKEND=Agg python plot-v2.py`, then inspect
v2 PNG/PDF and its full report. This retains v1 source/files while saving the
exact revised script under v2. Keep previous local edits in later revisions.
Repeated “one more step” acts on retained current label values, not the preset
base. The insertion point is after the original layout call, before report/export.
Follow the local-revision recipe above: ordinary enlargement allows necessary
fitting through the existing method/settings while preserving the canvas,
panel/container allocations and ratios, data, style and legend's intended
location. Keep already-fitting geometry; an explicit Axes-position lock takes
precedence. Ask only when protected constraints must change or the safe existing
fit is unclear. Inspect actual draw/export bounds and PNG/PDF; report necessary
Axes movement. The selected-line recipe also updates its known existing legend
sample in place without rebuilding the legend.

```python
# Insert before the source/report/export block in plot-v2.py.
for label in (ax.xaxis.label, ax.yaxis.label):
    label.set_fontsize(label.get_fontsize() + 1)
# Draw and inspect changed labels before deciding whether a refit is needed.
fig.canvas.draw()
# Compare actual axes/legend bounds after draw/export; inspect for clipping.
# If needed and not geometry-locked, fit through the existing method/settings.
```

Hand off exact source, PNG, PDF and full report for each revision, data/gap
policy, selected preset and canvas, retained warnings and actual image-review
results. Deterministic examples are not proof of autonomous agent success.


---
## Migration guide
---
orphan: true
---

# Migration Guide

This guide collects every rename / deprecation that has shipped on PyPI
(v0.4.0 onwards), **newest release first**. Every removed symbol now
raises `AttributeError` / `ModuleNotFoundError` / `TypeError` (or, for
palette tokens, the usual "not a valid color" error), with migration guidance
where available. A bare submodule import can instead
raise `ModuleNotFoundError` without a replacement hint.

> **New to dartwork-mpl?** You don't need this page. Head to the
> [Quick Start](usage_guide/quickstart.md) — it uses the current API
> end-to-end.

## 0.7.0: two-digit tick years, axis units, 만/억/조

One rule: with no request the library's look applies; ask for another format
and you get that format. The defaults below changed for axes you did not
format yourself; each other format is one `dm.config` field.

| Default now | Before | Ask for another format |
|---|---|---|
| year data (integers 1900–2099) tick whole years: `16, 18 … 24` | `2016 …`, or `2005.0, 2007.5 …` | `tick_years=4`: `2016, 2018 …` |
| dates `23.01, 23.07`; quarters `23.Q1` | `2023, May, Sep` | `date_style="concise"`: `23, May, Sep` (`2023, May, Sep` with `tick_years=4`) |
| Korean figures: `50만 … 250만` from 1,000,000 | `0.5M … 2.5M` | `number_ladder="si"`: `0.5M … 2.5M` |

Use them as `with dm.config.override(tick_years=4):`. The override applies to
what runs inside the `with` block: wrap the code from figure creation to the
last `dm.simple_layout` (and the save), or set the field on `dm.config` for
the whole program. A formatter or locator you set yourself is never
replaced, whatever its class (an explicit `ConciseDateFormatter` stays
English in a Korean figure).

To move the unit into the label instead of the ticks, use
the experimental
`dm.axis_unit(ax, "y", label="Exports (USD {unit})", ladder="finance")`
(`0, 0.2 … 1.0` under `인구 (억명)`); experimental
`dm.axis_unit_of(ax)` gives the unit for value labels.

## 0.7.0: Matplotlib 3.11 minimum

Use Matplotlib >=3.11.0. Matplotlib 3.10 is no longer supported: the pixel
baselines and docs figures are made on 3.11, with differences in text
metrics, pixel rounding and FreeType rasterization. The apparent legend-marker size difference was a stale
historical baseline, not a Matplotlib 3.11 change. dartwork-mpl does not
imitate the 3.10 output. Expect the same small shifts in your own figures
when you upgrade from 3.10. NumPy >=1.26 is required with no upper cap; the NumPy 2.5
date-unit deprecation came from Matplotlib 3.10's own date code.

## 0.6.0: Python 3.11 minimum

Use Matplotlib >=3.10.1,<3.11 with 0.6.0 (raised to >=3.11.0 in 0.7.0,
see above). Use NumPy >=1.26,<2.5 with Matplotlib 3.10: NumPy 2.5 deprecates
the generic date units Matplotlib 3.10 still uses.
The UI extra requires FastAPI >=0.110.0. FastAPI 0.137 and later keep each
included router as one wrapper route; the UI policy now matches against the
routers it builds, so those versions serve requests normally.

Upgrade to Python 3.11 or newer before installing 0.6.0. Supported test
runtimes are 3.11, 3.12 and 3.13. The security patch set requires Pillow 13
and other dependencies that no longer support Python 3.10. The core wheel
now declares Pillow >=13; affected optional extras also declare security
lower bounds for transitive dependencies, so fresh installs receive them.
Jupyter/documentation tools remain development-only.

The MCP extra supports FastMCP >=2.14.7 and patched 3.x below 4, excluding
vulnerable 3.0–3.4.9. FastMCP 2.13.3 pins MCP SDK <1.23, which cannot meet
the patched SDK >=1.30 requirement. Upgrade 2.x installations to 2.14.7;
exact 2.13.3 remains only in disposable legacy source/API compatibility
coverage. The tested 3.x lock is 3.4.10.

## At a glance

The moves you're most likely to hit, regardless of the version you're
coming from:

| Old surface                           | New surface                                          |
| ------------------------------------- | ---------------------------------------------------- |
| `dm.subplots(width=..., aspect=...)`  | `plt.subplots(figsize=dm.figsize(...))`              |
| `dm.figure(width=..., aspect=...)`    | `plt.figure(figsize=dm.figsize(...))`                |
| `plt.tight_layout()`                  | `dm.simple_layout(fig)`                              |
| `dm.auto_layout(fig)`                 | `dm.simple_layout(fig, margin=...)`                  |
| old named-color helper                | `dm.color("oc.red5")` (also accepts hex / `rgb(...)` / `oklch(...)` / `oklab(...)`) |
| `from dartwork_mpl.color import ...`  | `from dartwork_mpl._colors import ...` (submodule renamed) |
| `dartwork_mpl.asset_viz`              | `dartwork_mpl.diagnostics`                           |
| `dartwork_mpl.helpers.formatting`     | `dartwork_mpl.helpers.labels`                        |
| `dm.install_llm_txt()`                | `dm.get_agent_doc(name)` / `dm.agent_doc_path(name)` (or MCP `dartwork-mpl://guide/*`) |
| legacy `ocean*`, `spectrum*`, `focus*`, … families | see [dc.* palette migration](#dc-palette-migration-cumulative) |

The per-release sections below carry the full detail and runnable
snippets.

## v5 — generative color system (0.6.0)

For a PyPI upgrade, the clean-break boundary is **0.5.6 → 0.6.0**.
The 0.5.6 deprecation notice promised v4-only `dc.*` tokens at least two
minor releases before removal. That promise was not met for removed legacy
aliases. Some names exist in both catalogs with different meanings or colors:
check the rendered result and do not assume the same token preserves the old
color. The curated categorical sets remain available.

### Removed root color APIs and module

These are migration directions, not drop-in replacements; arguments, return
values and catalog contents may differ.

| Removed 0.5.6 surface | Current direction |
| --- | --- |
| `dm.get_palette` | `dm.colors(name, n=...)` for a list; `dm.set_colors(...)` sets a cycle. |
| `dm.set_cycle` | `dm.set_colors(...)` sets a global or axes color cycle. |
| `dm.cycle` | `dm.colors("octave", n=8)` returns colors; `dm.set_colors()` sets a cycle. |
| `dm.cycle_cycler` | `dm.set_colors(..., styles=True)` sets color and line-style cycles; it does not return a cycler. |
| `dm.list_palettes` | `dm.list_colors()` lists color families and metadata. |
| `dm.list_colormaps` | `dm.list_colors()` lists families; `matplotlib.colormaps` lists registered colormaps. |
| `dm.plot_colors` | `dm.show_colors()` previews color families. |
| `dm.plot_colormaps` | `dm.show_colors()` previews color families. |
| `dm.show_palette` | `dm.show_colors(names=[...])` previews selected families. |
| `dm.classify_colormap` | Inspect `dm.list_colors()` metadata; it is not a general classifier for arbitrary colormaps. |
| `dm.DartworkColor` | Type against the accepted inputs of the relevant API, such as color names, hex strings and RGB(A) tuples; no public equivalent literal alias is provided. |
| `dm.DartworkColormap` | Use `matplotlib.colors.Colormap` for colormap objects; it is not the former catalog-name literal. |
| `dm.set_palette_version` | No version switch exists; use the current catalog and review changed colors. |
| `dartwork_mpl.cmap` / `dm.cmap` | Use `dm.colors(name)` for a colormap or `matplotlib.colormaps` for registered colormaps. A bare submodule import raises `ModuleNotFoundError`. |


A 107-number generative palette (19 arc-length-equalized chromatic ladders plus
one directly sampled gray ladder, each with 10 `dc.{family}{step}` tokens)
replaced the hand-curated v4 catalog. v5 is a
**full clean break** (design spec:
`docs/superpowers/specs/2026-07-03-color-system-v5-design.md`):

1. **The throwaway v4 aliases were removed — but the curated categorical sets
   were kept.** The flat ad-hoc names (`sunset*`, `ocean*`, `nordic*`,
   `cyber*`, `spectrum*`, `bold*`, `corporate*`) and the numeric cycle aliases
   `0`–`7` no longer resolve. The scientifically curated categorical *sets* —
   `trustworthy`, `vivid`, `neon`, `jewel`, `blue_red`, `teal_amber`, `earth`,
   `forest`, `blue_orange`, and the rest — are **preserved** as first-class
   `dc.*` palettes: reach them through `dm.colors("trustworthy", n=6)` /
   `dm.set_colors("vivid")`, exactly like a generated family (see
   [Palettes](color_system/palettes.md)).
2. **There is no runtime palette-version switch.** The live registry is
   v5-only, so `teal`, `indigo`, and `gray` always mean the 10-step v5
   families.
3. **The old `dm.*` color aliases are gone.** Use `dc.*` named colors or
   `dm.color(...)` when you need a `Color` object.
4. **The palette-token codemod was deleted with the clean break.** The
   mapping table below is reference material for manual edits; there is no
   supported command to rewrite files automatically.
5. **Pre-v5 compatibility colormap files were removed.** Names such as
   `dc.aurora` and `dc.teal_rose` now refer to the v5 colormap catalog.
6. **Semantic tokens are v5-native.** Use `dc.pos`, `dc.neg`, `dc.ref`, and
   `dc.hl` for role-based color; use `dc.ref` rather than a gray shade for
   reference lines.
7. **The generated family set later gained `coral`, `tangerine`, `cobalt`, and
   `fuchsia`.** `coral` is now a recipe-generated 10-step family rather than
   a curated 8-step set.

## v0.5.5 — categorical palette overhaul

A judge-panel redesign reworked the then-current curated `dc.*` palette
catalog into a more coherent, better-covered set. Every palette in that
historical catalog was CIELAB-generated on an even-L\* ladder and CVD + B&W
verified — but several were renamed, merged, or dropped. The token mapping:

| Old token       | New token          | Change |
| --------------- | ------------------ | ------ |
| `spectrum*`  | `vivid*`        | rename |
| `coolwarm*`  | `dc.blue_red*`     | absorbed into the canonical blue-red diverging form |
| `bold*`      | `vivid*`        | merged into `vivid` |
| `corporate*` | `trustworthy*`  | merged into `trustworthy` |
| `dc.warm_cool*` | `dc.blue_orange*`  | removed (weakest under CVD) — use `blue_orange` |

`pastel` / `dusty` were also re-designed into an intentional high-key /
low-key pair (shared hue plan, different L\* band).

**New palettes** you can now reach for: `neon` (max-chroma electric),
`ember` (warm-vibrant), and `green_purple` (tritan-robust diverging).

## v0.5.4 — palette cleanup, module & MCP renames

### Legacy `dc.*` aliases removed

The 7 original back-compat aliases (`Vivid`, `Sunset`, `Ocean`, `Pop`,
`Cyber`, `Autumn`, `Nordic`) no longer resolve — `ocean2`, `nordic1`,
… now raise the usual "not a valid color" error. Their shade index is
preserved when you switch to the curated replacement:

| Old token     | New token (0.5.4)  |
| ------------- | ------------------ |
| `vivid*`   | `bold*`         |
| `sunset*`  | `earth*`        |
| `ocean*`   | `dc.teal*`         |
| `pop*`     | `spectrum*`     |
| `cyber*`   | `jewel*`        |
| `autumn*`  | `dusty*`        |
| `nordic*`  | `teal_indigo*`  |

> **Coming from 0.5.4 or earlier?** `bold` and `spectrum` were themselves
> renamed again in 0.5.5. The
> [dc.\* palette migration](#dc-palette-migration-cumulative) table folds
> both hops into one lookup.

### Curated palettes now use snake_case

| Old token          | New token         |
| ------------------ | ----------------- |
| `dc.teal_seq*`     | `dc.teal*`        |
| `dc.focus*`        | `dc.teal_accent*` |
| `dc.focus_warm*`   | `dc.coral_accent*`|
| `muted*`        | `pastel*`      |
| `dc.teal_amber_div*` | `dc.teal_amber*`|

### Module & entry-point removals

| Removed | Replacement |
| --- | --- |
| `dm.auto_layout(fig)` | `dm.simple_layout(fig, margin=...)` — the legacy `padding` inches arg maps to `margin`; `max_iter` / `tolerance` were obsolete. Now raises a migration-hint `AttributeError`. |
| `dartwork_mpl.helpers.formatting` | `dartwork_mpl.helpers.labels` (`ModuleNotFoundError`) |
| `dartwork_mpl.asset_viz` | `dartwork_mpl.diagnostics` (`ModuleNotFoundError`) |
| MCP `dartwork-mpl://guide/general-guide` | `dartwork-mpl://guide/agent-entry` |
| MCP `dartwork-mpl://guide/layout-guide` | `dartwork-mpl://guide/policy` |
| `ui._config.append_history` / `load_history` | `save_preset` / `load_presets` |

## v0.5.0 — installer removal & lighter core

**The `install_llm_txt` installer was removed.** It copied the bundled
prompt corpus into IDE-specific folders; the corpus is now read at runtime
instead, so there is nothing to install.

| Removed | Replacement |
|---|---|
| `dm.install_llm_txt(...)` | `dm.get_agent_doc(name)` / `dm.agent_doc_path(name)` — `name` ∈ `AGENTS`, `CLAUDE`, `llms`, `llms-full` — or the MCP `dartwork-mpl://guide/*` resources |
| `dm.uninstall_llm_txt(...)` | nothing — the corpus is read at runtime, so there is no install to undo |
| `dm.INSTALL_TARGETS` | nothing — install targets no longer exist |

**`ipython` is no longer a core dependency.** Only `dm.show()` (inline SVG
display in Jupyter) needs it, so it moved to the `notebook` optional
extra. `dm.show()` raises a clear `ImportError` naming the extra when
IPython is absent; every other entry point is unaffected.

| Old install | New install |
|---|---|
| `pip install dartwork-mpl` (pulled in ~30 MB of IPython deps) | `pip install "dartwork-mpl[notebook]"` if you use `dm.show()` |

## v0.4.1 — public API audit (wrapper removals)

The 0.4.1 audit retired the thin matplotlib wrappers whose only
contribution was default kwargs. Where the curated values were worth
keeping they now live as snippets in
[`usage_guide/recipes.md`](usage_guide/recipes.md).

### `dm.subplots` / `dm.figure` removal

The wrappers around the matplotlib figure constructors are gone. Use
`plt.subplots` / `plt.figure` directly and pass
`figsize=dm.figsize(width, aspect)`:

```python
# Before
fig, ax = dm.subplots(width="15cm", aspect="wide")

# Now
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=dm.figsize("15cm", "wide"))
```

If you also passed `style=`, call `dm.style.use(...)` first:

```python
# Before
fig, ax = dm.subplots(width="15cm", aspect="wide", style="scientific")

# Now
dm.style.use("scientific")
fig, ax = plt.subplots(figsize=dm.figsize("15cm", "wide"))
```

`dm.figsize(width, aspect)` accepts a unit-string width (`"15cm"`,
`"5in"`, `"170mm"`, `"24pt"`) or a `Length` value (`dm.cm(15)`,
`dm.col1`, `dm.col2`), and four equivalent aspect forms — token
(`"wide"`), numeric ratio (`0.6`), unit-string height (`"12cm"`), or
`Length` height (`dm.cm(12)`). Bare `int` / `float` widths are rejected.

### `dm.style_spines` / `dm.add_grid` / `dm.minimal_axes` removal

All three were 1–3 line matplotlib calls; the curated kwargs now live in
[`usage_guide/recipes.md`](usage_guide/recipes.md):

| Removed | Inline replacement |
| --- | --- |
| `dm.style_spines(ax, color=c, linewidth=w, which=ws)` | `for s in ws: ax.spines[s].set_color(c); ax.spines[s].set_linewidth(w)` |
| `dm.add_grid(ax)` | `ax.grid(True, color="oc.gray3", alpha=0.3, linewidth=0.5); ax.set_axisbelow(True)` |
| `dm.minimal_axes(ax)` | see [Minimal axes recipe](usage_guide/recipes.md#minimal-axes-tufte-style) |

### `dm.auto_select_colors` → `dm.make_palette`

The rename cleaned up the argument names; the body is unchanged:

```python
# Before
colors = dm.auto_select_colors(n_series=5, color_type="sequential", highlight_index=2)

# Now
colors = dm.make_palette(5, kind="sequential", highlight=2)
```

### Formatter & spine wrappers → direct matplotlib

Five wrappers from audit round 3:

```python
# Before
dm.format_axis_percent(ax)
dm.format_axis_labels(ax, fmt="{:,.0f}")
dm.add_frame(fig)
dm.add_value_labels(ax, bars)
dm.set_xmargin(ax, 0.05); dm.set_ymargin(ax, 0.05)

# Now — direct matplotlib calls, sometimes one-liners
from matplotlib import ticker
ax.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1.0))
ax.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x:,.0f}"))
fig.patches.append(plt.Rectangle((0, 0), 1, 1, fill=False, transform=fig.transFigure))
for bar in bars: ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(),
                          f"{bar.get_height():.0f}", ha="center", va="bottom")
ax.set_xmargin(0.05); ax.set_ymargin(0.05)
```

Eight more from audit round 2 — each is a single matplotlib call now:

```python
# Before / Now
dm.hide_spines(ax, ["top", "right"])            # → for s in ("top", "right"): ax.spines[s].set_visible(False)
dm.hide_all_spines(ax)                           # → for s in ax.spines: ax.spines[s].set_visible(False)
dm.show_only_spines(ax, ["left", "bottom"])      # → for s in ax.spines: ax.spines[s].set_visible(s in ("left", "bottom"))
dm.remove_grid(ax)                               # → ax.grid(False)
dm.format_axis_thousands(ax, axis="y")           # → see snippet below
dm.save_figure(fig, "out.png")                   # → fig.savefig("out.png")
dm.create_figure_with_style(width=..., style=...)  # → dm.style.use(style); plt.subplots(figsize=dm.figsize(...))
dm.templates.diverging_bar.get_source_code()     # → inspect.getsource(dm.templates.diverging_bar)
```

```python
# Thousand separator on y-axis:
from matplotlib import ticker
formatter = ticker.FuncFormatter(lambda x, p: f"{x:,.0f}")   # sep=","
# Non-comma separator:
# formatter = ticker.FuncFormatter(lambda x, p: f"{x:,.0f}".replace(",", sep))
ax.yaxis.set_major_formatter(formatter)   # or ax.xaxis for axis="x"
```

### `dm.Inches` → `dm.Length`

The in-flight `Inches(float)` marker was replaced by `dm.Length`, an
opaque wrapper with per-unit property views (`length.cm`, `length.mm`,
`length.inch`, `length.pt`). It is deliberately **not** a `float`
subclass — passing it to a pt-based (`fontsize=`) or px-based API would
silently misinterpret the value. `dm.Inches` is no longer importable.

## dc.* palette migration (cumulative)

If you have `dc.*` tokens from any release before 0.5.5, this table folds
every rename hop (0.5.4 legacy-alias removal, 0.5.4 snake_case, 0.5.5
overhaul) into a single lookup. Shade indices are preserved
(`ocean2` → `dc.teal2`).

| Legacy token (0.5.3 or earlier) | Current token |
| ------------------------------- | --------------------- |
| `Vivid*` / `vivid*` (alias) | `vivid*` |
| `Sunset*` / `sunset*`     | `earth*`           |
| `Ocean*` / `ocean*`       | `dc.teal*`            |
| `Pop*` / `pop*`           | `vivid*`           |
| `Cyber*` / `cyber*`       | `jewel*`           |
| `Autumn*` / `autumn*`     | `dusty*`           |
| `Nordic*` / `nordic*`     | `forest*`          |
| `spectrum*`                  | `vivid*`           |
| `bold*`                      | `vivid*`           |
| `coolwarm*`                  | `dc.blue_red*`        |
| `corporate*`                 | `trustworthy*`     |
| `dc.warm_cool*`                 | `dc.blue_orange*`     |
| `dc.teal_seq*`                  | `dc.teal*`            |
| `dc.focus*`                     | `dc.teal_accent*`     |
| `dc.focus_warm*`                | `dc.coral_accent*`    |
| `muted*`                     | `pastel*`          |
| `dc.teal_amber_div*`            | `dc.teal_amber*`      |

> These map each old token to its **closest current palette** — the
> colours themselves were re-generated in the overhaul, so a migrated
> token is a starting point, not a byte-identical swap. Browse the live
> set on the [Palettes](color_system/palettes.md)
> page.

## color parsing (old named-color helper → `dm.color`)

The old named-color helper is gone. The replacement is `dm.color`, a single string-parser
entry point that mirrors `dm.length`:

```python
# Before
red = legacy_named_color("oc.red5")

# Now
red = dm.color("oc.red5")               # palette token
red = dm.color("#ff0000")               # hex
red = dm.color("rgb(255, 0, 0)")        # rgb function string
red = dm.color("oklch(0.7 0.2 30)")     # oklch function string
red = dm.color("oklab(0.7 0.1 0.1)")    # oklab function string
```

The submodule was also renamed `color` → `colors`. Anywhere you used
`from dartwork_mpl.color import ...` swap to:

```python
# Before
from dartwork_mpl.color import Color

# Now
from dartwork_mpl._colors import Color
```


---
## Anti-pattern catalog (SSOT, YAML)
# dartwork-mpl anti-pattern catalog (SSOT for lint engine).
#
# Each rule has:
#   id          unique kebab-case identifier
#   severity    critical | warning | info
#   detector
#     kind      regex | substring | ast
#     pattern   regex pattern (Python re, MULTILINE) for kind=regex
#     literal   literal substring (case-sensitive) for kind=substring
#     check     colormap-name | color-name for kind=ast
#   message     short user-facing text shown in the lint report
#   why         (optional) longer rationale; shown only on demand
#   fix_suggestion  (optional) one-line replacement or pointer
#
# Rule IDs are part of the public API: tools, docs, and tests refer
# to them. Do not rename without bumping the dartwork-mpl version.
#
# Modeled relative CIE Y (`relative_y`) is calculated from nominal D65 sRGB; it is not a measurement of a particular display, perceived brightness, or OKLab `L`.

version: 1
rules:
  - id: invalid-colormap-name
    severity: critical
    detector:
      kind: ast
      check: colormap-name
    message: |
      This literal colormap name is absent from the current matplotlib
      registry. Color-family prefixes do not imply matching colormaps.
      Discover valid names with sorted(matplotlib.colormaps).
    why: |
      Static checks cover cmap keywords on conventional ax/plt plotting
      calls, imported pyplot aliases, and pyplot.get_cmap. Dynamic
      expressions and unknown receivers are not evaluated. Live custom
      maps and explicit inline register(name="...") declarations are accepted.
      Registrations with dynamic or implicit names defer this check.
      Registration statements in supplied source are never executed.
    fix_suggestion: 'Choose an exact name from sorted(matplotlib.colormaps).'

  - id: invalid-color-name
    severity: critical
    detector:
      kind: ast
      check: color-name
    message: |
      This literal color is not recognized by matplotlib. Discover named
      colors with matplotlib.colors.get_named_colors_mapping(), or use
      the existing get_color_value and list_color_families MCP tools.
    why: |
      Static checks cover scalar color, facecolor, edgecolor,
      markerfacecolor, and markeredgecolor keywords on conventional
      ax/plt plotting calls and imported pyplot aliases. Dynamic values
      and unknown receivers are not evaluated. The live matplotlib
      color parser accepts registered names, hex, grayscale and C0 tokens.
      Direct literal assignments to get_named_colors_mapping() are also
      recognized without executing the supplied registration code. Direct
      mapping .update(...) calls and assignments with dynamic keys defer
      color-name checks for that source; colormap-name checks still run.
    fix_suggestion: 'Choose a valid color from matplotlib.colors.get_named_colors_mapping().'

  - id: figsize-direct
    severity: critical
    detector:
      kind: regex
      pattern: '\bfigsize\s*=\s*\('
    message: |
      Raw `figsize=(w, h)` tuples bypass dartwork-mpl's physical-width
      contract. Use `figsize=dm.figsize("13cm", "wide")` so the width
      stays in cm/in/mm and the aspect intent is named.
    why: |
      Width and aspect are decided separately so chart-wide width
      consistency can be enforced and so the height follows from the
      content's aspect intent.
    fix_suggestion: 'figsize=dm.figsize("13cm", "standard")'

  - id: tight-layout
    severity: critical
    detector:
      kind: regex
      pattern: '\btight_layout\s*\('
    message: |
      `tight_layout()` collides with dartwork-mpl's spine and legend
      handling. Use `dm.simple_layout(fig)` instead.
    fix_suggestion: 'dm.simple_layout(fig)'

  - id: multirow-subplots-no-gridspec-kw
    severity: info
    detector:
      kind: regex
      pattern: '\bplt\.subplots\(\s*[2-9]\b(?![\s\S]{0,200}?(?:gridspec_kw|sharex|sharey))'
    message: |
      Vertically stacked `plt.subplots(>=2, ...)` was created without
      `gridspec_kw={"hspace": ..., "wspace": ...}`. The matplotlib
      default `hspace` (0.2) frequently causes the upper subplot's
      xlabel / xtick labels to overlap the lower subplot's title once
      `dm.simple_layout(fig)` snaps the outer margins flush. Pass an
      explicit `gridspec_kw` (e.g. `hspace=0.55`, `wspace=0.3`) when
      every subplot has both a title and an xlabel, then verify with
      `dm.validate_figure(fig)` — the `CROSS_AXES_OVERLAP` check will
      flag any residual collisions.
    why: |
      `dm.simple_layout` only adjusts the figure's outer margins; it
      intentionally preserves the GridSpec's `hspace` / `wspace` so
      authors can keep their own intent. That makes the default
      `hspace=0.2` the hidden source of title↔xlabel collisions in
      multi-panel gallery and report figures. The detector scans the
      200 characters following `plt.subplots(<n>` for `gridspec_kw` /
      `sharex` / `sharey` so it catches line-wrapped calls (where the
      kwargs sit on a later line), not just single-line ones. This is
      a best-effort static hint — the authoritative collision check is
      the runtime `CROSS_AXES_OVERLAP` validator.
    fix_suggestion: 'gridspec_kw={"hspace": 0.55, "wspace": 0.3}'

  - id: zero-resize-mention
    severity: warning
    detector:
      kind: substring
      literal: 'Zero-Resize'
    message: |
      "Zero-Resize Policy" was retired in 0.4.0. dartwork-mpl now uses
      free-form width input plus a lint consistency guard.

  - id: plt-style-use
    severity: warning
    detector:
      kind: regex
      pattern: '\bplt\.style\.use\s*\('
    message: |
      Use `dm.style.use(...)` (or `dm.style.stack([...])` for a stack)
      instead of `plt.style.use(...)`.
    fix_suggestion: 'dm.style.use("scientific")'

  - id: plt-show-only
    severity: info
    detector:
      kind: regex
      pattern: '\bplt\.show\s*\(\)'
    message: |
      Prefer `dm.save_and_show(fig, "name")` or `dm.save_formats(fig,
      "name")` so the figure ships with its rendered artifact.

  - id: dm-subplots-removed
    severity: critical
    detector:
      kind: regex
      pattern: '\bdm\.(?:subplots|figure)\s*\('
    message: |
      `dm.subplots` and `dm.figure` were REMOVED — accessing them now
      raises `AttributeError`. Use `plt.subplots(figsize=dm.figsize(...))`
      (or `plt.figure(figsize=dm.figsize(...))` for custom GridSpec).
      Apply style separately via `dm.style.use(...)`.
    why: |
      Both functions were thin wrappers around `plt.subplots` / `plt.figure`
      that bundled style mutation, polymorphic `width=`, and a deny-list
      of legacy kwargs. Removing them keeps the matplotlib API native and
      reduces dartwork-mpl's surface to a single sizing helper.
    fix_suggestion: 'plt.subplots(figsize=dm.figsize("13cm", "standard"))'

  - id: cm2in-figsize
    severity: critical
    detector:
      kind: regex
      pattern: 'figsize\s*=\s*\([^)]*cm2in'
    message: |
      `figsize=(dm.cm2in(...), dm.cm2in(...))` is the legacy 0.3
      pattern: `dm.cm2in` itself raises `AttributeError`. Use
      `figsize=dm.figsize("<n>cm", "<aspect>")` instead.
    fix_suggestion: 'figsize=dm.figsize("9cm", "standard")'

  - id: dm-spines-removed
    severity: critical
    detector:
      kind: regex
      pattern: '\bdm\.(?:style_spines|add_grid|minimal_axes)\s*\('
    message: |
      `dm.style_spines`, `dm.add_grid`, and `dm.minimal_axes` were
      REMOVED in 0.4.1 (#156). They were thin matplotlib wrappers
      whose only contribution was curated default kwargs. Inline the
      raw matplotlib calls instead, or copy a snippet from
      `docs/usage_guide/recipes.md` (publication grid, minimal axes,
      thin gray spines).
    fix_suggestion: 'see docs/usage_guide/recipes.md'

  - id: dm-legacy-wrappers-removed
    severity: critical
    detector:
      kind: regex
      pattern: '\bdm\.(?:format_axis_percent|format_axis_labels|format_axis_thousands|add_frame|add_value_labels|set_xmargin|set_ymargin|hide_spines|hide_all_spines|show_only_spines|remove_grid|save_figure|create_figure_with_style)\s*\('
    message: |
      These legacy `dm.*` helpers were REMOVED in 0.4.1. They were
      thin formatter, spine, margin, and figure wrappers around native
      matplotlib calls. Inline the matplotlib API directly, or use the
      recipes in `docs/migration.md` / `docs/usage_guide/recipes.md`;
      dartwork-mpl keeps recipes and utilities rather than wrapper
      functions for simple matplotlib operations.
    fix_suggestion: 'see docs/migration.md'

  - id: dm-auto-select-colors-renamed
    severity: critical
    detector:
      kind: regex
      pattern: '\bdm\.(?:helpers\.colors\.)?auto_select_colors\s*\('
    message: |
      `auto_select_colors` was renamed to `make_palette` in 0.4.1
      (#156) for vocabulary alignment with `make_offset`.
      Argument cleanup at the same time:
      `n_series` → `n`, `color_type` → `kind`,
      `highlight_index` → `highlight`.
    fix_suggestion: 'dm.make_palette(n, kind="categorical")'

  - id: dm-auto-layout-removed
    severity: critical
    detector:
      kind: regex
      pattern: '\bdm\.auto_layout\s*\('
    message: |
      `dm.auto_layout` was REMOVED in 0.5.4 — accessing it now raises
      `AttributeError`. Use `dm.simple_layout(fig, margin=...)`: the
      legacy `padding` inches argument maps to `margin`;
      `max_iter`/`tolerance` are obsolete (simple_layout is
      direct-calc).
    fix_suggestion: 'dm.simple_layout(fig)'

  - id: dm-named-renamed
    severity: critical
    detector:
      kind: regex
      pattern: '\bdm\.named\s*\('
    message: |
      `dm.named` was REMOVED in 0.4.1 — the replacement is
      `dm.color(...)`, a single string-parser entry point that accepts
      token names, hex, and `rgb()`/`oklch()`/`oklab()` functional
      strings.
    fix_suggestion: 'dm.color("oc.red5")'

  - id: dm-model-b-color-api-removed
    severity: critical
    detector:
      kind: regex
      pattern: "\\bdm\\.(?:get_\u0070alette|set_\u0063ycle|cycle|cycle_\u0063ycler|list_\u0070alettes|list_\u0063olormaps|plot_\u0063olors|plot_\u0063olormaps|show_\u0070alette|classify_\u0063olormap|Dartwork\u0043olor|Dartwork\u0043olormap|set_palette_version)\\b"
    message: |
      Version 0.6.0 removed the old palette, cycle, diagnostic,
      and color-class vocabulary; there is no palette-version switch.
      For current color operations use `dm.colors(...)`,
      `dm.set_colors(...)`, `dm.list_colors()`, or `dm.show_colors()`.
    fix_suggestion: 'dm.colors("blue", n=5)'

  - id: dm-removed-namespaces
    severity: critical
    detector:
      kind: regex
      pattern: '\bdm\.(?:agent_utils|xplot)\b'
    message: |
      `dm.agent_utils` and `dm.xplot` were REMOVED in 0.4. The
      agent_utils surfaces moved to `dm.lint` / `dm.validate_figure` /
      `dm.helpers`; the xplot templates now live in `dm.templates`
      (e.g. `dm.templates.plot_diverging_bar`). See docs/migration.md.
    fix_suggestion: 'see docs/migration.md'

  - id: dm-install-llm-txt-removed
    severity: critical
    detector:
      kind: regex
      pattern: '\bdm\.(?:install_llm_txt|uninstall_llm_txt|INSTALL_TARGETS)\b'
    message: |
      The `install_llm_txt` installer family
      (`install_llm_txt`/`uninstall_llm_txt`/`INSTALL_TARGETS`) was
      REMOVED in 0.5. The agent-doc corpus is read at runtime — use
      `dm.get_agent_doc(name)` / `dm.agent_doc_path(name)`, or the MCP
      `dartwork-mpl://guide/*` resources.
    fix_suggestion: 'dm.get_agent_doc("llms")'

  - id: deprecated-width-token
    severity: critical
    detector:
      kind: regex
      pattern: '\bdm\.(SW|MW|TW|DW|FS_[A-Z_]+|WIDTHS)\b'
    message: |
      `dm.SW/MW/TW/DW/FS_*/WIDTHS` were REMOVED in 0.4.0 — accessing
      them now raises `AttributeError`. Use
      `figsize=dm.figsize("<n>cm", "<aspect>")`, or `dm.col1`/`dm.col2`
      for academic columns.

  - id: raw-width-number
    severity: critical
    detector:
      kind: regex
      # `dm.figsize(13, ...)` or `dm.figsize(13.5)` — bare numbers carry
      # no unit and dartwork-mpl rejects them at runtime. Catch the
      # call site with a clearer message than the raised TypeError.
      pattern: '\bdm\.figsize\s*\(\s*-?\d+(?:\.\d+)?\s*[,)]'
    message: |
      `dm.figsize(<bare number>, ...)` is rejected — bare numbers carry
      no unit. Pass a unit string (`"13cm"`, `"5in"`, `"170mm"`,
      `"24pt"`) or a Length value (`dm.cm(13)`, `dm.col1`, `dm.col2`).
    fix_suggestion: 'dm.figsize("13cm", "standard")'

  - id: dpi-arg
    severity: critical
    detector:
      kind: regex
      # Allow one level of nested parens (e.g. ``figsize=(8, 6)``)
      # before the ``dpi=`` token so that
      # ``plt.figure(figsize=(8,6), dpi=200)`` is caught. The previous
      # ``[^)]*`` form bailed at the first ``)`` and silently missed
      # this very common spelling. ``savefig(dpi=...)`` is intentionally
      # outside this rule's scope — see ``savefig-direct``.
      pattern: '\bplt\.(?:subplots|figure)\s*\((?:[^()]|\([^()]*\))*\bdpi\s*='
    message: |
      `dpi=` should not be set per-figure. The active dartwork-mpl
      style controls dpi (display vs savefig). Direct
      ``savefig(dpi=...)`` is flagged separately by ``savefig-direct``.

  - id: raw-hex-color
    severity: info
    detector:
      kind: regex
      pattern: '\b(?:color|c)\s*=\s*["'']#[0-9a-fA-F]{3,8}["'']'
    message: |
      Raw hex is valid. Prefer named tokens for unspecified defaults;
      retain explicit user colors and report this advisory when relevant.
      Examples: `color="oc.blue6"` (Open Color),
      `color="tw.sky500"` (Tailwind), or `color="dc.blue6"` (dartwork core
      categorical). These register as matplotlib named colors; wrap in
      `dm.color("oc.blue6")` when you need a Color object.
    why: |
      Named palettes give consistent perception across reports and
      let style presets remap colors centrally. The dartwork core catalog's
      construction model uses OKLab L, OKLCH C/h, and ΔEOK. Its optional
      modeled-relative-Y output lock preserves shipped colors and topology;
      it is not an authoring space. CIELAB/CIEDE2000 and CVD simulation remain
      model-specific validation diagnostics, and WCAG contrast luminance is a
      separate pairwise text-contrast metric.
    fix_suggestion: 'Retain explicit user colors; for unspecified defaults prefer named tokens such as color="oc.blue6".'

  - id: fontsize-literal
    severity: warning
    detector:
      kind: regex
      pattern: '\bfontsize\s*=\s*\d+(?:\.\d+)?'
    message: |
      A literal fontsize pins an absolute pt size. This is advisory:
      retain explicit user values and report relevant warnings. For
      unspecified defaults or preset-relative intent, use `dm.fs(n)`
      or role defaults; relative-to-current edits use the target getter.
    fix_suggestion: 'Retain explicit absolute values; otherwise prefer role defaults or fontsize=dm.fs(n).'

  - id: linewidth-literal
    severity: warning
    detector:
      kind: regex
      # Match only literals whose integer part is >= 1. Sub-1 values
      # (e.g. ``linewidth=0.3`` for hairline edges) and the no-border
      # idiom ``linewidth=0`` are common, intentional decoration and
      # don't fight the active style — bundled templates rely on them.
      pattern: '\b(?:linewidth|lw)\s*=\s*[1-9]\d*(?:\.\d+)?'
    message: |
      A literal linewidth (>= 1) pins an absolute pt width. This is
      advisory: retain explicit user values and report relevant warnings.
      For preset-relative intent use `dm.lw(n)`; relative-to-current edits
      use the target getter. `linewidth=0` disables a border; sub-1
      hairline widths such as `linewidth=0.3` remain allowed.
    fix_suggestion: 'Retain explicit absolute values; otherwise prefer linewidth=dm.lw(n).'

  - id: savefig-direct
    severity: warning
    detector:
      kind: regex
      pattern: '\b(?:fig|plt)\.savefig\s*\('
    message: |
      Direct `savefig(...)` bypasses the dartwork-mpl save preset
      (multi-format, dpi, metadata). Use
      `dm.save_formats(fig, "name")` for scripts or
      `dm.save_and_show(fig, "name")` for notebooks.
    fix_suggestion: 'dm.save_formats(fig, "name")'

  - id: jet-cmap
    severity: warning
    detector:
      kind: regex
      pattern: 'cmap\s*=\s*["''](?:jet|hsv|gist_rainbow|gist_ncar|nipy_spectral|rainbow)["'']'
    message: |
      Rainbow colormaps (`jet`, `hsv`, `gist_rainbow`, `gist_ncar`,
      `nipy_spectral`, `rainbow`) can distort ordinal interpretation.
      This is advisory: retain explicit supported user choices and
      explain/report the warning. For unspecified defaults prefer
      `viridis`, `cividis`, `inferno`, `magma`, `plasma` or a dartwork map
      (`dm.list_colors()`).
    fix_suggestion: 'Retain an explicit supported colormap; for unspecified defaults prefer cmap="viridis".'

  - id: oversize-width
    severity: warning
    detector:
      kind: regex
      # Match a > 17 cm literal in either of the two canonical width
      # contexts: a `width=` kwarg (legacy / non-figsize callers) or
      # the first positional of `dm.figsize("...cm", ...)`. The aspect
      # argument (second positional) is filtered out because it sits
      # behind a `,` rather than directly after `(`.
      pattern: '(?:width\s*=\s*|\bdm\.figsize\s*\(\s*)["''](?:1[89]|[2-9]\d|\d{3,}|17\.\d*[1-9]\d*)(?:\.\d+)?cm["'']'
    message: |
      Width exceeds the 17 cm page-fit reference (`dm.col2`). Review
      the intended page or slide placement; retain explicitly requested
      or template-required dimensions. This is not an API canvas limit.
    why: |
      Coordinated page figures benefit from consistent widths. Reduce or
      split only if the target page requires it; purpose defaults do not
      override the user's physical width/height.
    fix_suggestion: 'Confirm target page/content width; keep requested dimensions, or use dm.col1/dm.col2 when they fit.'


---
## AI plot templates index
AI Plot Templates
-----------------

Eighteen ready-to-use plot templates curated for AI coding assistants. Each
template is a small, self-contained script that sizes its canvas with
``figsize=dm.figsize_for(...)``, draws no chart title and uses the curated
``dc.*`` palette. They are
bundled in the wheel under ``dartwork_mpl/asset/prompt/05-templates/`` and
exposed through both the prompt utilities and the
:doc:`MCP server </integrations/mcp_server>`.

How to access these templates
=============================

.. code-block:: python

   import dartwork_mpl as dm

   # Read a template script as text
   bar_src = dm.get_prompt("05-templates/bar")

   # Or list everything available under prompts/
   print(dm.list_prompts())

Or via MCP from Claude / Cursor / Continue:

.. code-block:: text

   dartwork-mpl://templates/{plot_type}

where ``{plot_type}`` is one of ``bar``, ``bar_horizontal``,
``bar_grouped``, ``boxplot``, ``contour``, ``heatmap``, ``histogram``,
``line``, ``pie``, ``plot_3d``, ``polar``, ``scatter``, ``small_multiples``,
``stacked_bar``, ``tornado``, ``twin_axis``, ``violin``, or ``waterfall``.

The gallery entries below render each template so you can pick the right
shape at a glance, then copy the source from the page (or fetch it via
``dm.get_prompt``) into your project.
