Author grammar-of-graphics plots with the gribouille Typst library.

GitHub stars
284

Install

/plugin install gribouille@gribouille

Run it inside Claude Code after adding the marketplace with /plugin marketplace add mcanouil/gribouille.

Contents

Discovered from source

Skills 1

Authoring gribouille plots

Gribouille is a grammar-of-graphics plotting library for Typst. The API mirrors ggplot2 (R) and plotnine (Python). A plot layers geom-* over shared data and an aesthetic mapping.

Import

#import "@preview/gribouille:0.9.0": *

Pin the version to the installed one. Check it via llms.txt or Typst Universe.

Mental model

Pipeline, forward only:

data → stat → position → scale → coord → facet → theme → render
  • data: a dictionary of column arrays, or a built-in dataset (penguins, mpg, economics).
  • mapping: aes(...): column names to aesthetics (x, y, colour, fill, shape, size, alpha, linetype, label, …). Gribouille rejects unknown channels, including the US spelling color.
  • layers: a tuple of geom-*. Each geom can set its own stat, position, mapping, and key (legend glyph). Stat-backed geoms take stat: auto to build their default stat from the geom parameters.
  • scales: how values map to axes and palettes. See the scales section below.
  • coord, facet, labels, guides, theme: everything else.
  • Late binding: after-stat(...), after-scale(...), from-theme(...), stage(...).

Call shape

#plot(
  data: <dict-of-columns or dataset>,
  mapping: aes(x: "...", y: "...", colour: "...", ...),
  layers: (
    geom-point(...),
    geom-smooth(method: "lm", se: true),
    // more layers ...
  ),
  scales: scales(
    x: scale-continuous(),
    colour: scale-discrete(...),
    // more scales ...
  ),
  coord: coord-cartesian(),    // optional
  facet: facet-wrap("group"),  // optional
  labels: labels(title: "...", x: "...", y: "..."),
  guides: guides(...),         // optional; guides(default: none) hides all legends
  theme: theme-minimal(),
  alt: "...",                  // optional accessibility text
  width: 12cm,                 // default 10cm
  height: 9cm,                 // default 7cm
)

as-spec: true returns the raw spec instead of rendering, for compose() composition.

Scales

Scale constructors are aesthetic-agnostic. The aesthetic comes from the scales() key:

  • scales(colour: scale-viridis-d()), not scale-colour-viridis-d().
  • scales(x: scale-log10()), not scale-x-log10().

plot(scales:) accepts only the scales() dictionary. There is no positional array. The same constructor adapts to its key (axis for x/y, palette for colour/fill, output range for size/alpha/…). Unknown constructor arguments, unknown aesthetics, and positional arguments fail at binding. The error lists the valid keys.

Groups belong in aes()

Map a grouping variable in aes(). Gribouille then splits the data into one group for each value:

  • colour and fill apply the palette and draw a legend.
  • shape and linetype draw a legend with their own glyph.
  • group only splits the data, with no scale and no legend.

Do not use the native Typst .map() to make one layer for each group:

// Wrong: one layer for each species, with a hand-made colour.
layers: species.map(s => geom-point(
  data: rows.filter(r => r.species == s),
  colour: palette.at(s),
)),

// Right: one layer, and the species goes in the mapping.
mapping: aes(x: "flipper-len", y: "body-mass", colour: "species"),
layers: (geom-point(),),

If the data is wide (one column for each series), reshape it with pivot-longer. Then map the new key column:

#plot(
  data: pivot-longer(mpg, ("cty", "hwy"), names-to: "metric", values-to: "mpg"),
  mapping: aes(x: "displ", y: "mpg", colour: "metric"),
  layers: (geom-point(),),
)

Use .map(), .filter(), and .sorted() only to prepare the rows. For example, use .map() to derive a column. To aggregate rows for each group, use summarise or count.

Use the grammar before raw Typst

Try Gribouille first: geoms, stats, positions, scales, guides, labels, themes, and compose(). Use raw Typst only for what the grammar cannot express, and keep it to the minimum.

When you rewrite a figure, change how a part is drawn, not what the figure shows. Keep every element of the old figure: gridlines, the key in the subtitle, connector lines, the place of each header, and the width of the panel. Compare the new render with the old render, element by element.

You wantUseNot
Two plots side by side, a shared titlecompose(defer(plot, ...), labels: labels(title:, subtitle:, caption:))grid of plots with text(...) titles
Fill or stacked bars, stacked areasgeom-col or geom-bar with position: "fill" or "stack"; geom-area (stacks by default)geom-rect or place/rect bars, Typst fold with geom-ribbon
Axis ticks, labels, and gridlinesscale breaks, labels, breaks-width; theme panel-grid-major-x; labels(x:)geom-segment grids, geom-typst tick labels
Categories on rowsscale-discrete (limits, labels)numeric rows with scale-continuous(limits: (0.45, n + 0.55), breaks: ())
A log axisscale-log10(breaks:)log10(n) computed in the data
Quartiles, swarms, jittergeom-pointrange(stat: stat-summary(fun: "median-hilow")), geom-beeswarm, position-jittergeom-segment quartiles, hand-placed points
Number formats and summariesformat-comma, format-percent, median, quantiles, pivot-wideryour own thousands, pct, or a .find for each cell
Colour from a row valuemap a derived category, scale-manual(values:, limits:)a hand-written colour-of(...) with scale-identity()
Styled labelsgeom-text(font:, size:, colour:); theme element-textgeom-typst with text(font:, size:, fill:)[...]
Bold or italic labelsstrong[...] or emph[...] content in the label column, or label: typst("col") for Typst markup in a columngeom-typst with text(weight: "bold")[...]
Labels that do not overlaprepel: true, and segment: true with a nudge, on geom-text, geom-label, geom-typstan offset dictionary and one geom-typst for each anchor
Plots in table cellscompose(), or nanoplot(..., axis: true) in a Keisen columnone plot for each cell and a separate axis plot
Label colour on filled cellsafter-scale on the label colour (see below)a hand-made colour recipe for each cell
Extra layer dataa layer mapping, or inherit-aes: false with a full mappinga layer that relies on the inherited x and y
A header above the panelsecondary: sec-axis(breaks: (...), labels: (...)) on the scaleextra breaks on the bottom axis, or geom-typst headers
Room for a note outside the datalimits on that axis, then annotate(...)raw place

Layout and titles

// Wrong: raw layout and a hand-made title.
#grid(columns: 2,
  text(14pt)[Title],
  [],
  plot(data: penguins, mapping: aes(x: "bill-len", y: "bill-dep"), layers: (geom-point(),)),
  plot(data: penguins, mapping: aes(x: "species"), layers: (geom-bar(),)),
)

// Right: compose draws one title, subtitle, and caption.
#compose(
  defer(plot, data: penguins, mapping: aes(x: "bill-len", y: "bill-dep"), layers: (geom-point(),)),
  defer(plot, data: penguins, mapping: aes(x: "species"), layers: (geom-bar(),)),
  labels: labels(title: "Title", subtitle: "Subtitle", caption: "Caption"),
)

Pass fonts once with compose(theme:). The panels do not need a theme of their own.

Hand-drawn marks

// Wrong: a rectangle for each share, with the heights worked out by hand.
layers: (geom-rect(),),

// Right: the position does the work.
mapping: aes(x: "g", y: "n", fill: "s"),
layers: (geom-col(position: "fill"),),
scales: scales(y: scale-continuous(labels: format-percent())),

Fake axes

// Wrong: segments for the grid, geom-typst for the tick labels.
layers: (geom-point(), geom-segment(data: grid-rows), geom-typst(data: tick-rows)),

// Right: the scale owns the ticks, and the theme owns the grid.
scales: scales(
  x: scale-continuous(breaks: (180, 200, 220)),
  y: scale-continuous(breaks: breaks-width(1000), labels: format-comma()),
),
theme: theme-minimal() + theme(panel-grid-major-x: element-line(colour: red)),
labels: labels(x: "Flipper length (mm)"),

Label colour on filled cells

Pick a readable label colour from the fill with after-scale on the label colour. The function takes (value, ctx). The first argument is the text's own colour, not the fill. Rebuild the fill with ctx.resolve-colour and ctx.trained:

#let contrast = (_, ctx) => {
  let trained = ctx.trained.at("fill", default: none)
  let c = ((ctx.resolve-colour)(trained, ctx.palette))(ctx.row.v)
  if luma(c).components().first() > 50% { black } else { white }
}
#plot(
  data: (
    (k: "a", v: 1), (k: "b", v: 5), (k: "c", v: 9),
  ),
  mapping: aes(x: "k", y: "v", fill: "v"),
  layers: (
    geom-col(),
    geom-text(
      mapping: aes(label: "k", colour: after-scale(contrast)),
      position: position-nudge(y: -0.5),
      size: 14pt,
    ),
  ),
)

Here v is the column that the fill mapping uses.

Symbol inventory

What exists, by family (regenerate with lua tools/skill-inventory.lua). Arguments, defaults, and types still come from each symbol's .llms.md reference page.

  • Core: plot, compose, defer, aes, as-factor, as-numeric, typst, after-scale, after-stat, from-theme, stage.
  • Datasets: economics, mpg, penguins.
  • Labels: labels.
  • Guides: guide-legend, guide-axis, guide-axis-logticks, guide-axis-stack, guide-axis-theta, guide-custom, guides, draw-key-blank, draw-key-line, draw-key-path, draw-key-point, draw-key-rect.
  • Geoms: annotate, geom-point, geom-line, geom-path, geom-step, geom-area, geom-rect, geom-tile, geom-bin-2d, geom-hex, geom-contour, geom-contour-filled, geom-segment, geom-curve, geom-spoke, geom-polygon, geom-ellipse, geom-mark, geom-col, geom-bar, geom-histogram, geom-freqpoly, geom-density, geom-density-2d, geom-density-2d-filled, geom-smooth, geom-ribbon, geom-boxplot, geom-violin, geom-density-ridges, geom-errorbar, geom-errorbarh, geom-count, geom-linerange, geom-crossbar, geom-pointrange, geom-hline, geom-vline, geom-abline, geom-text, geom-typst, geom-label, geom-jitter, geom-beeswarm, geom-blank, geom-rug, geom-function, geom-dotplot, geom-quantile, geom-qq, geom-qq-line.
  • Stats: stat-identity, stat-count, stat-density, stat-density-2d, stat-density-2d-filled, stat-ydensity, stat-density-ridges, stat-sum, stat-function, stat-bin, stat-bin-2d, stat-bin-hex, stat-contour, stat-contour-filled, stat-bindot, stat-smooth, stat-boxplot, stat-summary, stat-summary-bin, stat-summary-2d, stat-summary-hex, stat-ecdf, stat-unique, stat-qq, stat-qq-line, stat-ellipse, stat-quantile, stat-manual, stat-connect, stat-align, stat-difference, stat-waffle.
  • Helpers: get-alt-text, arrow, format-comma, format-currency, format-log, format-lower, format-number, format-percent, format-scientific, format-title, format-upper, format-wrap, mean, mean-cl-boot, mean-cl-normal, mean-sd, mean-se, median, median-hilow, quantile, quantiles, cut-interval, cut-number, cut-width, resolution, qnorm, nanoplot.
  • Wrangle: count, summarise, distinct, drop-na, relocate, rename, select, slice-max, slice-min, pivot-longer, pivot-wider, anti-join, bind-cols, bind-rows, full-join, inner-join, left-join, semi-join.
  • Scales: scales, scale-area, scale-binned, scale-binned-area, scale-brewer, scale-continuous, scale-date, scale-datetime, scale-discrete, scale-distiller, scale-fermenter, scale-gradient, scale-gradient2, scale-gradientn, scale-grey, scale-hue, scale-identity, scale-log10, scale-manual, scale-okabe-ito, scale-radius, scale-reverse, scale-sqrt, scale-steps, scale-steps2, scale-stepsn, scale-time, scale-viridis-b, scale-viridis-c, scale-viridis-d, dup-axis, sec-axis, breaks-extended, breaks-log, breaks-pretty, breaks-quantile, breaks-width, brewer-palette, okabe-ito, colour-mix, expand-limits.
  • Coord: coord-cartesian, coord-fixed, coord-flip, coord-radial, coord-transform.
  • Positions: position-stack, position-dodge, position-fill, position-identity, position-jitter, position-jitterdodge, position-beeswarm, position-nudge.
  • Facets: facet-wrap, facet-grid, label-both, label-context, label-value, label-wrap, labeller.
  • Themes: theme-grey, theme-minimal, theme-classic, theme-void, theme-bw, theme-linedraw, theme-light, theme-dark, theme-brand, theme, element-blank, element-geom, element-line, element-rect, element-text, element-tick, element-typst, margin, theme-sub-axis, theme-sub-axis-bottom, theme-sub-axis-left, theme-sub-axis-right, theme-sub-axis-top, theme-sub-axis-x, theme-sub-axis-y, theme-sub-legend, theme-sub-panel, theme-sub-plot, theme-sub-strip, theme-get, theme-set.

Worked example

#import "@preview/gribouille:0.9.0": *

#let species-colours = (
  Adelie: rgb("#ff8c00"),
  Chinstrap: rgb("#008B8B"),
  Gentoo: rgb("#800080"),
)

#let species-scale = scale-discrete(
  limits: species-colours.keys(),
  palette: species-colours.values(),
)

#plot(
  data: penguins,
  mapping: aes(
    x: "flipper-len",
    y: "body-mass",
    colour: "species",
    fill: "species",
    shape: "species",
  ),
  layers: (
    geom-point(size: 2pt, alpha: 0.25, stroke: 0.5pt, colour: rgb("#ffffff")),
    geom-smooth(method: "lm", se: true, alpha: 0.2),
    geom-mark(method: "hull", expand: 5pt, alpha: 0.25),
  ),
  scales: scales(
    x: scale-continuous(),
    y: scale-continuous(labels: format-comma()),
    colour: species-scale,
    fill: species-scale,
  ),
  labels: labels(
    title: typst("Penguins *Dataset*"),
    x: "Flipper Length (mm)",
    y: "Body Mass (g)",
  ),
  guides: guides(default: none),
  theme: theme-minimal(),
  width: 12cm,
  height: 9cm,
)

Bind a shared scale once (species-scale) and reuse it for every aesthetic that carries the same palette.

Density and pattern fills

Kernel density estimation is native. The same KDE core backs geom-violin, geom-density-ridges, geom-density-2d, and geom-density-2d-filled:

#plot(
  data: penguins,
  mapping: aes(x: "body-mass", fill: "species"),
  layers: (geom-density(fill: auto, alpha: 0.4),),
)

Fills accept native Typst tiling paints, as fixed fill: values or through a palette. Legend swatches render the pattern:

#let stripes(base, ink) = tiling(size: (5pt, 5pt))[
  #place(box(width: 5pt, height: 5pt, fill: base))
  #place(line(start: (0%, 100%), end: (100%, 0%), stroke: 1pt + ink))
]

#plot(
  data: (g: ("a", "a", "b", "b"), n: (3, 5, 2, 4), k: ("x", "y", "x", "y")),
  mapping: aes(x: "g", y: "n", fill: "k"),
  layers: (geom-col(position: "dodge"),),
  scales: scales(fill: scale-manual(values: (
    stripes(rgb("#fde68a"), rgb("#b45309")),
    stripes(rgb("#bfdbfe"), rgb("#1d4ed8")),
  ))),
)

Gotchas

  • Aesthetics use British spelling: colour, not color. On error, aes() lists the valid channels.
  • Fill opacity defaults to 1 on geom-area, geom-ribbon, geom-polygon, geom-ellipse, and geom-mark. For translucency, pass alpha:.
  • stroke: accepts the native Typst 1.3pt + accent form (thickness and paint together). An explicit colour: wins over the embedded paint.
  • Unknown stat, scale transform, oob, or theme() element names fail fast instead of silently rendering as identity.
  • CSV string-numeric columns stay discrete. For a continuous scale, call as-numeric(data, "col").
  • scale-log10 takes no expand. Use scale-continuous(transform: "log10", expand: (0%, 0%)).
  • To hide breaks, write breaks: (), not breaks: none.
  • Data channels in aes() take column names, not constants. aes(x: 0) fails: add a constant column instead. The scalar channels nudge-x, nudge-y, xintercept, yintercept, slope, and intercept accept a constant.
  • Text geoms place a label with anchor: "west", not hjust. anchor is a layer parameter.
  • segment: true draws a leader only when the label moves: use nudge-x/nudge-y or repel: true. position-nudge moves the label but draws no leader.
  • geom-point(size:) is a radius, as in circle(radius:).
  • Rows outside a scale's limits are dropped by the default oob.
  • theme-void() has no plot inset, so the title and caption touch the edge. Use theme-void(plot-background: element-rect()).
  • Give height a fixed length unless the container has a set height.
  • geom-col with a discrete y draws nothing. For horizontal bars, use a discrete x and coord-flip().
  • A layer with its own data that lacks the inherited x and y columns draws nothing, with no error. Give the layer its own x and y mapping, or use inherit-aes: false with a full mapping.
  • A layer row with a new level adds an entry to an inherited colour legend. inherit-aes: false avoids it.
  • geom-rect has no linetype, and geom-typst has no clip.
  • labeller options take plain strings, as in label-both(separator: ": ").
  • Long theta labels of coord-radial can overlap or reach the plot edge.
  • Scales expand 5% on each side by default.
  • A bounded measure keeps its full domain: use limits: (-1, 1) for a correlation, not the data range.
  • Do not draw maps with points and coord-fixed: there are no geo geoms.
  • annotate() trains the scales, as in ggplot2. A note outside the data range widens the axis. Set limits on that axis to keep the old range.
  • geom-blank() trains the scales. Use it to extend an axis without limits.

When Gribouille misbehaves

Do not work around a Gribouille bug in silence. A silent workaround hides the bug, and then nobody fixes it.

  1. Isolate the problem. Reduce the plot to a minimal #plot() that still shows it. Add a control: the same data with a simpler layer such as geom-point, or the same plot without the coord, facet, or theme. Check each argument against its .llms.md page, so that a misuse is not reported as a bug. Reproduce the problem on the latest release from Typst Universe.

  2. Stop and tell the user before you write a workaround. Give the minimal reproduction, the expected output, and the actual output.

  3. Search mcanouil/gribouille for a duplicate. Start with one or two distinctive words, such as the geom name or the error text, then vary them.

    If an open issue matches, do not file a new issue. Draft a comment with only the facts that the thread does not have yet, such as a newer version or a smaller reproduction. Use the prose rules of step 5, then go to step 6. If there are no new facts, suggest a thumbs-up reaction, post nothing, and go to step 8. If a closed issue was fixed and the bug is back, write "Regression of #N." in the new issue.

  4. Route the report. Blank issues are turned off.

  5. Draft a bug report with the fields of the bug template, each as a ### <label> heading followed by the answer: "Before submitting", "Gribouille version", "Typst compiler version", "Installation source", "Bug description", "Minimal reproducible example", "Steps to reproduce", "Expected behaviour", "Actual behaviour", "Your environment", and the optional "Additional context".

    • For "Installation source", copy one option exactly: "Typst Universe", "Local package directory", "Git clone / source checkout", or "Other".
    • Put the reproduction in a typst code block, with the @preview/gribouille:<version> import.
    • Run typst --version yourself. Ask the user for the facts that you cannot find. Never post a placeholder.
    • Copy the "Before submitting" checkbox labels exactly from https://github.com/mcanouil/gribouille/blob/main/.github/ISSUE_TEMPLATE/bug.yml. Write each checkbox as - [x] or - [ ]. Tick a box only when it is true, and tick the search box only after step 3. Under the draft, list each box that you could not verify.
    • Claim only what you ran or what the user told you.
    • Keep the prose short and plain. Do not add headings of your own. Keep code and error output unchanged.
    • Do not mention the agent or the tools that wrote the text.

    For Discussions, use the fields of that form with the same rules. Ideas: "Before posting", "What problem does this solve?", "Proposed solution or desired behaviour", and the optional "Alternatives considered". Q&A: "Description".

  6. Show the draft to the user. Put the line **Draft for mcanouil/gribouille, not posted.** above it. Put the title and the body in one markdown code block, with a fence longer than any fence in the body. For a comment, put the issue number in place of the title.

  7. Post only after a clear go-ahead from the user, such as "post".

    • If gh auth status succeeds, write the body to a file and run gh issue create --repo mcanouil/gribouille --title "<title>" --body-file <file>. gh issue create does not apply the label of the form. If gh repo view mcanouil/gribouille --json viewerPermission reports TRIAGE or higher, add --label "Type: Bug :bug:". If not, tell the user that the issue has no label. Do not add assignees. Give the user the URL of the new issue.
    • For a comment on an open issue, run gh issue comment <n> --repo mcanouil/gribouille --body-file <file>.
    • If gh is not available, or the report goes to Discussions, give the user the draft and the link from step 4.
  8. Write a workaround only if the user agrees. Put a comment next to it that links the issue, so that the workaround can be removed when the bug is fixed:

    // Workaround for https://github.com/mcanouil/gribouille/issues/<n>: remove when fixed.
    

Reference protocol

The API is pre-1.0. Names and arguments change between releases. Do not recall a geom, stat, scale, or argument from memory. Confirm each against the machine-readable reference.

  1. Index: https://m.canouil.dev/gribouille/llms.txt lists every page and its .llms.md.
  2. Fetch the symbol's page, e.g., .../reference/geoms/geom-smooth.llms.md, .../reference/scales/scale-viridis-d.llms.md, .../reference/stats/stat-summary.llms.md. Every <page>.html has a sibling <page>.llms.md.
  3. Use only the arguments, defaults, and types documented there.

Families under reference/: core, geoms, stats, scales, coord, facets, positions, guides, labels, themes, helpers, datasets. Tutorials: get-started/, guides/, examples/.

Validate

Compile before claiming success:

typst compile plot.typ

Errors follow the shape <scope>: <problem>; got <value>. <hint>. Read the hint, then re-check the argument against its .llms.md page.

Sponsors

Details

Marketplace
mcanouil/gribouille
Category
Community