pt.legend
Coordinates & layout
Minimal call
import math
xs = [i * 0.1 for i in range(64)]
waves = {"t": xs, "sin": [math.sin(x) for x in xs],
"cos": [math.cos(x) for x in xs]}
a = pt.chart(waves, aes(x="t"), data_width=260, data_height=170,
xlabel="t")
a.add_line(aes(y="sin"), label="sin(t)")
a.add_line(aes(y="cos"), label="cos(t)", linestyle="--")
c = a | pt.legend(a)
Docstring
Create a layout-level legend.
With no `sources`, the legend harvests entries from every leaf in
its parent layout. With sources, it harvests only from those.
Multiple sources are grouped by source chart, with each chart's
`title` rendered as a section header. `names={chart: "Override"}`
replaces a header text; `names={chart: None}` hides the header
while keeping the entries. `group_by_chart=False` flattens all
entries into a single unsectioned list (useful when small-multiples
genuinely share a series).
`valign=` controls where the content sits vertically when the
legend leaf gets more space than its content needs (siblings taller,
or explicit `canvas_height=`). `"middle"` (default) centers it;
`"top"` pins it to the top edge.
`ncols=N` wraps each discrete entry list into N columns, filled
down-then-across (matplotlib's `ncols`, ggplot2's `guide_legend(
ncol=)`) — the fix for a long categorical legend outgrowing its
siblings. Headers and gradient strips span the full width; each
grouped guide block wraps independently.
`reverse=True` flips the discrete entry order within each section
(matplotlib's `reverse`) — the fix when stacked marks read bottom-up
but the legend reads top-down.
`entries=[{"label": ..., "color": ...}, ...]` appends free-form
manual rows not harvested from any artist (an annotation color, an
external reference). Each dict needs `label` and `color`; optional
`alpha`. Manual rows render as standard rect swatches after the
harvested sections.
Legend leaves have no data axes, so the dimensional surface is
canvas-only: pass `canvas_width=` / `canvas_height=` to override the
content-driven auto-size. `gap=N` overrides the default 6 px
separation between this legend and its source neighbor (falls back
to `spec.json:layout.legend_gap` when unset).