Skip to content

Figure API

Figure

Figure(nrows: int = 1, ncols: int = 1, *, figsize: tuple[float, float] | None = None, widths: list[float] | None = None, heights: list[float] | None = None, style: Style | None = None, sharex: bool = False, sharey: bool = False, latex_labels: bool = False, hspace: float | None = None, wspace: float | None = None, colorbar: Mapping[str, Any] | None = None)

Bases: FigureRenderable

Compose multiple Plot objects into a multi-panel figure.

Two usage styles:

Simple grids::

Figure.grid([
    [PKSpectrum(k, pk), BackgroundEvolution(z, qty)],
    [XYPlot(x, y)],  # auto-spans 2 columns
]).show()

Complex layouts with explicit spanning::

fig = Figure(nrows=2, ncols=3, widths=[2, 1, 1], sharex=True)
fig.add(PKSpectrum(k, pk), row=0, col=0, colspan=2)
fig.add(XYPlot(x, y),      row=0, col=2)
fig.add(XYPlot(x2, y2),    row=1, col=0, colspan=3)
fig.show()

Layouts can also be composed with operators — (p1 | p2) / p3 — which build on the same grid; see :mod:cplots.layout.

A :class:~cplots.TrianglePlot cannot be a panel (its engine draws its own figure); render it on its own.

Create a Figure layout container.

Parameters:

Name Type Description Default
nrows int

Number of rows in the grid.

1
ncols int

Number of columns in the grid.

1
figsize tuple[float, float] | None

Overall figure size (width, height) in inches.

None
widths list[float] | None

Relative column widths (length must equal ncols).

None
heights list[float] | None

Relative row heights (length must equal nrows).

None
style Style | None

Visual :class:~cplots.Style of the figure. Each panel's own style is layered on top; None inherits the active style.

None
sharex bool

Share x-axis across panels in the same column.

False
sharey bool

Share y-axis across panels in the same row.

False
latex_labels bool

Propagate raw LaTeX strings to all panels.

False
hspace float | None

Vertical space between rows. For matplotlib this is a fraction of the average axis height (e.g. 0.3); for altair it is in pixels (e.g. 20). None uses the backend default.

None
wspace float | None

Horizontal space between columns. Same unit convention as hspace.

None
colorbar Mapping[str, Any] | None

:class:~cplots.core.spec.ColorbarSpec fields set on every colour-mapped panel, e.g. {"loc": "bottom", "label_loc": "top"}. None leaves each panel's own colourbar untouched; panels without a colour scale are never changed.

None

Methods:

to_bytes
to_bytes(fmt: str = 'png', *, dpi: float | None = 150, backend: str | None = None, **kwargs: Any) -> bytes

The rendered figure encoded as fmt ("png", "pdf", "svg", ...).

For HTML reports, notebooks and web apps. With matplotlib the figure is drawn into memory and closed afterwards, so calling this in a loop accumulates no figures; other backends go through their save() (which for images may need extra packages, e.g. kaleido for plotly). kwargs are passed to the save call.

to_base64
to_base64(fmt: str = 'png', *, dpi: float | None = 150, backend: str | None = None, **kwargs: Any) -> str

:meth:to_bytes as base64, e.g. for <img src="data:image/png;base64,...">.

style
style(style: Style | None = None, /, **fields: Any) -> Self

Layer a style over this one (fields win over style; set fields accumulate).

Example::

plot.style(cplots.PUBLICATION).style(palette=("k", "r"))
size
size(width: float, height: float) -> Self

Set the figure size in inches.

paper
paper(name: str) -> Self

Size and font of a journal format: "PRD", "PRD-2col", "MNRAS", "A4".

spec
spec() -> FigureSpec

The figure specification with :meth:layout, :meth:style etc. applied.

Styles are not yet resolved against the global/context style; that happens at render time.

layout
layout(*, widths: list[float] | None = None, heights: list[float] | None = None, sharex: bool | None = None, sharey: bool | None = None, hspace: float | None = None, wspace: float | None = None, engine: LayoutEngine | None | _Unset = _UNSET) -> Self

Grid settings: column widths / row heights (relative), axis sharing, spacing.

widths and heights refer to the columns and rows of the final grid. hspace/wspace are a fraction of the average axes size for matplotlib and pixels for altair; setting either switches matplotlib to fixed spacing. engine picks matplotlib's layout engine: "constrained" (the default, which keeps labels and colourbars from overlapping), "tight", or None/"none" for fixed subplot parameters.

show
show(backend: str | None = None, **kwargs: Any) -> None

Render the figure and display it interactively.

Parameters:

Name Type Description Default
backend str | None

Backend name ("matplotlib", "plotly", "altair"). Defaults to the active context/global backend.

None
**kwargs Any

Forwarded to the backend's show() method.

{}
save
save(path: str | PathLike[str], backend: str | None = None, **kwargs: Any) -> None

Render the figure and save it to a file.

Parameters:

Name Type Description Default
path str | PathLike[str]

Destination file path. The format is inferred from the extension (e.g. .png, .pdf, .svg).

required
backend str | None

Backend name. Defaults to the active context/global backend.

None
**kwargs Any

Forwarded to the backend's save() method.

{}
render
render(backend: str | None = None) -> Any

Render the figure and return the native figure object.

Parameters:

Name Type Description Default
backend str | None

Backend name. Defaults to the active context/global backend.

None

Returns:

Type Description
Any

The native figure object (e.g. matplotlib.figure.Figure,

Any

plotly.graph_objects.Figure, or altair.Chart).

add
add(plot: Plot[Any], *, row: int, col: int, rowspan: int = 1, colspan: int = 1) -> Figure

Add a plot at the given grid position. Returns self for chaining.

grid classmethod
grid(rows: list[list[Plot[Any] | None]], *, figsize: tuple[float, float] | None = None, widths: list[float] | None = None, heights: list[float] | None = None, style: Style | None = None, sharex: bool = False, sharey: bool = False, latex_labels: bool = False, hspace: float | None = None, wspace: float | None = None, colorbar: Mapping[str, Any] | None = None) -> Figure

Build a Figure from a list-of-lists of Plot objects.

Rows with fewer plots than the maximum row length are auto-spanned evenly. The number of plots in each row must evenly divide the maximum row length, or a ValueError is raised.

Example::

Figure.grid([
    [p1, p2],   # 2 columns
    [p3],       # p3 spans both columns automatically
])

colorbar overrides every colour-mapped panel's own colourbar settings when given::

Figure.grid([[fig_tau, fig_chi2]], colorbar={"loc": "bottom"})