Plots API¶
Plot¶
Base class of every plot. Its formatting methods (.axes(), .legend(),
.xticks(), .style(), .size(), .paper(), .layout(), …) return a styled
copy; .render(), .show() and .save() draw it with the active backend.
Every plot class below inherits them.
Plot
¶
Bases: _Formattable, ABC, Generic[FigureT]
Abstract base for all cplots plot types.
Subclasses declare their associated data type via the data_type class
keyword and must implement :meth:_build_spec.
Example
class MyPlot(Plot, data_type=MyPlotData): ... def _build_spec(self) -> PlotSpec: ... return PlotSpec(traces=[...])
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
¶
Layer a style over this one (fields win over style; set fields accumulate).
Example::
plot.style(cplots.PUBLICATION).style(palette=("k", "r"))
paper
¶
Size and font of a journal format: "PRD", "PRD-2col", "MNRAS", "A4".
spec
¶
The plot specification with :meth:axes, :meth:legend, :meth:style etc. applied.
The style is not yet resolved against the global/context style; that happens at render time.
axes
¶
axes(*, xlabel: str | None = None, ylabel: str | None = None, xlim: tuple[float, float] | None = None, ylim: tuple[float, float] | None = None, xscale: Scale | None = None, yscale: Scale | None = None, aspect: Literal['equal', 'auto'] | None = None, secondary_x: SecondaryAxisSpec | None = None, secondary_y: SecondaryAxisSpec | None = None) -> Self
Axis labels, limits, scales and aspect. Arguments left as None are unchanged.
secondary_x adds a top x-axis and secondary_y a right y-axis (matplotlib
only); see :class:~cplots.SecondaryAxisSpec and :func:~cplots.multipole_axis.
Example::
pk.axes(xlabel=r"$k\,[h/{\rm Mpc}]$", xlim=(1e-3, 1), yscale="log")
legend
¶
legend(show: bool = True, *, loc: LegendLoc = 'best', ncol: int = 1, frame: bool | None = None, outside: bool = False, title: str = '') -> Self
Legend placement and appearance; legend(False) hides it.
xticks
¶
xticks(values: Sequence[float] | None = None, *, labels: Sequence[str] | None = None, count: int | None = None, minor: bool | None = None, format: str | None = None) -> Self
Ticks of the x-axis: positions (values, optionally labels), count,
minor ticks on/off, and a label format spec such as ".2f" or ".0e".
Repeated calls update only the arguments given.
yticks
¶
yticks(values: Sequence[float] | None = None, *, labels: Sequence[str] | None = None, count: int | None = None, minor: bool | None = None, format: str | None = None) -> Self
Ticks of the y-axis; see :meth:xticks.
layout
¶
matplotlib layout engine: "constrained" (default), "tight", or None.
colorbar
¶
Change colourbar settings (:class:~cplots.core.spec.ColorbarSpec fields).
Ignored by plots without a colour mapping. Example: .colorbar(loc="bottom").
latex
¶
Pass label strings to the backend as raw LaTeX (see PlotSpec.latex_labels).
show
¶
Render and display the plot interactively.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | None
|
Backend name ( |
None
|
**kwargs
|
Any
|
Forwarded to the backend's |
{}
|
save
¶
Render and save the plot to a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Destination file path. The format is inferred from the
extension (e.g. |
required |
backend
|
str | None
|
Backend name. Defaults to the active context/global backend. |
None
|
**kwargs
|
Any
|
Forwarded to the backend's |
{}
|
render
¶
Return the native figure object for the resolved backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend
|
str | None
|
Backend name. Defaults to the active context/global backend. |
None
|
Returns:
| Type | Description |
|---|---|
FigureT
|
The native figure object (e.g. |
FigureT
|
|
residuals
¶
residuals(reference: int | str | NDArray[Any] = 0, *, reference_x: NDArray[Any] | None = None, mode: Literal['absolute', 'relative', 'ratio'] = 'relative', ylabel: str | None = None, include_reference: bool = False) -> XYPlot
Return a new plot showing residuals relative to a reference trace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference
|
int | str | NDArray[Any]
|
Which trace to use as the reference. An |
0
|
reference_x
|
NDArray[Any] | None
|
X-grid of an external reference array. Only used when reference is a numpy array and its x-grid differs from the traces in this plot. |
None
|
mode
|
Literal['absolute', 'relative', 'ratio']
|
Residual type.
|
'relative'
|
ylabel
|
str | None
|
Y-axis label for the residuals plot. Defaults to a sensible string derived from the original y-label and mode. |
None
|
include_reference
|
bool
|
When True and the reference is an existing trace, include it in the output (it will appear as a flat line at 0 for relative/absolute or 1 for ratio). |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
An |
XYPlot
|
class: |
XYPlot
|
over the original x-axis (label, scale, limits), style, figsize, and the |
|
XYPlot
|
traces' own colours and line styles. |
with_residuals
¶
with_residuals(reference: int | str | NDArray[Any] = 0, *, reference_x: NDArray[Any] | None = None, mode: Literal['absolute', 'relative', 'ratio'] = 'relative', heights: tuple[float, float] = (3, 1), include_reference: bool = False, hspace: float | None = None) -> ResidualFigure
Return a two-panel figure: this plot on top, residuals below.
The two panels share an x-axis so zoom and pan stay in sync (matplotlib).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reference
|
int | str | NDArray[Any]
|
Reference for residual computation — same semantics as
:meth: |
0
|
reference_x
|
NDArray[Any] | None
|
X-grid of an external reference array. |
None
|
mode
|
Literal['absolute', 'relative', 'ratio']
|
Residual type — same semantics as :meth: |
'relative'
|
heights
|
tuple[float, float]
|
Relative heights |
(3, 1)
|
include_reference
|
bool
|
Include the reference trace in the residuals panel when it is one of the existing traces. |
False
|
hspace
|
float | None
|
Vertical space between the two panels. For matplotlib this
is a fraction of the average axis height (e.g. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
ResidualFigure
|
class: |
ResidualFigure
|
|
plot¶
plot
¶
plot(x: NDArray[Any] | list[NDArray[Any]], y: NDArray[Any] | list[NDArray[Any]], **kwargs: Any) -> XYPlot
Convenience alias for XYPlot
Returns an XYPlot instance — not a rendered figure — so callers can
chain .show(), .render(), or .save().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
NDArray[Any] | list[NDArray[Any]]
|
X-axis data. A single array is broadcast to all traces; a list provides per-trace arrays. |
required |
y
|
NDArray[Any] | list[NDArray[Any]]
|
Y-axis data. A single array produces one trace; a list produces one trace per element. |
required |
**kwargs
|
Any
|
Forwarded verbatim to |
{}
|
Returns:
| Type | Description |
|---|---|
XYPlot
|
An |
Example:
>>> import numpy as np
>>> import cplots as plt
>>> x = np.linspace(0, 2 * np.pi, 100)
>>> fig=plt.plot(x, np.sin(x), ylabel="sin(x)")
>>> fig.render() # or fig.show()
XYPlot¶
XYPlot
¶
XYPlot(x: NDArray[Any] | list[NDArray[Any]], y: NDArray[Any] | list[NDArray[Any]], *, labels: str | list[str] = '', xlabel: str = '', ylabel: str = '', title: str = '', xscale: Scale = 'linear', yscale: Scale = 'linear', style: Style | None = None, figsize: tuple[float, float] | None = None, latex_labels: bool = False, ref_lines: Sequence[tuple[float, str, dict[str, Any]]] = (), annotations: Sequence[tuple[float, float, str, dict[str, Any]]] = ())
Bases: Plot[Any]
Generic x/y line plot for arbitrary data.
Accepts a single trace or multiple traces when y is a list.
A single x array is broadcast across all traces.
Example:
>>> # Single trace
>>> XYPlot(x, y, ylabel="f(x)")
>>> # Multiple traces, shared x
>>> XYPlot(x, [y1, y2], labels=["sin", "cos"])
>>> # Multiple traces, individual x arrays
>>> XYPlot([x1, x2], [y1, y2], labels=["A", "B"])
>>> # Horizontal reference lines (grey and dashed unless styled), one with text
>>> XYPlot(x, y, ref_lines=[(1.0, "", {"text": "1σ"}), (4.0, "limit", {"color": "r"})])
>>> # Text at a point
>>> XYPlot(x, y, annotations=[(0.5, 2.0, "peak", {"ha": "center"})])
Create an XYPlot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
NDArray[Any] | list[NDArray[Any]]
|
X-axis data. A single array is broadcast to all traces; a list provides per-trace arrays. |
required |
y
|
NDArray[Any] | list[NDArray[Any]]
|
Y-axis data. A single array produces one trace; a list produces one trace per element. |
required |
labels
|
str | list[str]
|
Legend label(s). A single string is reused for all traces; a list must match the number of traces. |
''
|
xlabel
|
str
|
X-axis label. Supports LaTeX when |
''
|
ylabel
|
str
|
Y-axis label. |
''
|
title
|
str
|
Plot title. |
''
|
xscale
|
Scale
|
X-axis scale — |
'linear'
|
yscale
|
Scale
|
Y-axis scale. |
'linear'
|
style
|
Style | None
|
Visual :class: |
None
|
figsize
|
tuple[float, float] | None
|
Figure size |
None
|
latex_labels
|
bool
|
Pass label strings raw to the backend (for MathJax). |
False
|
ref_lines
|
Sequence[tuple[float, str, dict[str, Any]]]
|
|
()
|
annotations
|
Sequence[tuple[float, float, str, dict[str, Any]]]
|
|
()
|
Methods:¶
PKSpectrum¶
PKSpectrum
¶
PKSpectrum(k_or_data: NDArray[Any] | list[NDArray[Any]] | PKData | list[PKData], pk: NDArray[Any] | list[NDArray[Any]] | None = None, *, redshift: float = 0.0, **kwargs: Any)
Bases: PowerSpectrumBase
Matter power spectrum P(k). Log-log axes.
Raw arrays get the unit-free labels $k$ and $P(k)$; PKData from the
CLASS/CAMB adapters carries labels with units (h/Mpc or 1/Mpc).
Accepts either raw arrays or a PKData object (e.g. from
ClassOutput.pk()).
Examples:
# From raw arrays
PKSpectrum(k, pk, labels="z=0").show()
# Multiple redshifts on the same axes
PKSpectrum(k, [pk0, pk1], labels=["z=0", "z=1"]).show()
# From ClassOutput
PKSpectrum(out.pk(z=0.0), labels="z=0").show()
# Secondary top axis showing corresponding multipole ℓ ≈ k · χ
# chi is the comoving distance in the same units as k (e.g. Mpc/h)
PKSpectrum(k, pk, secondary_x_axis=multipole_axis(chi=13890)).show()
PrimordialSpectrum¶
PrimordialSpectrum
¶
PrimordialSpectrum(k_or_data: NDArray[Any] | list[NDArray[Any]] | PKData | list[PKData], ps: NDArray[Any] | list[NDArray[Any]] | None = None, *, redshift: float = 0.0, **kwargs: Any)
Bases: PowerSpectrumBase
Primordial scalar power spectrum P_s(k). Log-log axes, x in 1/Mpc.
Accepts either raw arrays or a PKData object (e.g. from
ClassOutput.primordial()).
Examples:
# From ClassOutput
PrimordialSpectrum(out.primordial()).show()
# From raw arrays
PrimordialSpectrum(k, ps, labels="n_s=0.96").show()
# Multiple spectra (list of PKData)
PrimordialSpectrum([out.primordial(), other.primordial()]).show()
ClSpectrum¶
ClSpectrum
¶
ClSpectrum(ell_or_data: NDArray[Any] | list[NDArray[Any]] | dict[str, ClData], cl: NDArray[Any] | list[NDArray[Any]] | None = None, **kwargs: Any)
Bases: PowerSpectrumBase
CMB angular power spectrum C_ell. Linear x, log y.
Accepts either raw arrays or a dict[str, ClData] returned by
ClassOutput.cl().
Examples:
# From raw arrays
ClSpectrum(ell, cl_tt, labels="TT").show()
# Multiple components from raw arrays
ClSpectrum(ell, [cl_tt, cl_ee], labels=["TT", "EE"]).show()
# From ClassOutput (single or multiple spectra)
ClSpectrum(out.cl(spectra=["tt", "ee"])).show()
# Secondary top axis showing corresponding wavenumber k ≈ ℓ / χ
# chi is the comoving distance in the same units as k (e.g. Mpc/h)
ClSpectrum(ell, cl_tt, secondary_x_axis=wavenumber_axis(chi=13890)).show()
PowerSpectrumBase¶
PowerSpectrumBase
¶
PowerSpectrumBase(x: NDArray[Any] | list[NDArray[Any]], y: NDArray[Any] | list[NDArray[Any]], *, labels: str | list[str] = '', xlabel: str = '', ylabel: str = '', title: str = '', style: Style | None = None, figsize: tuple[float, float] | None = None, latex_labels: bool = False, secondary_x_axis: SecondaryAxisSpec | None = None, secondary_y_axis: SecondaryAxisSpec | None = None)
Bases: Plot[Any], ABC
Shared rendering logic for power spectrum plots.
Subclasses fix default axis scales and labels via class variables; callers may override labels via constructor keyword arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
NDArray[Any] | list[NDArray[Any]]
|
X-axis data. A single array is broadcast to all traces; a list provides per-trace arrays. |
required |
y
|
NDArray[Any] | list[NDArray[Any]]
|
Y-axis data. A single array produces one trace; a list produces one trace per element. |
required |
labels
|
str | list[str]
|
Legend label(s). A string is broadcast; a list provides per-trace labels. |
''
|
xlabel
|
str
|
Override the default x-axis label. |
''
|
ylabel
|
str
|
Override the default y-axis label. |
''
|
title
|
str
|
Panel title. |
''
|
style
|
Style | None
|
Visual :class: |
None
|
figsize
|
tuple[float, float] | None
|
Figure size |
None
|
latex_labels
|
bool
|
Pass labels through to the backend without stripping LaTeX markup. |
False
|
secondary_x_axis
|
SecondaryAxisSpec | None
|
Optional top x-axis specification. Build one with
:func: |
None
|
secondary_y_axis
|
SecondaryAxisSpec | None
|
Optional right y-axis specification
(:class: |
None
|
BackgroundEvolution¶
BackgroundEvolution
¶
BackgroundEvolution(redshift_or_data: NDArray[Any] | BackgroundSource | Mapping[str, BackgroundSource], quantities: Mapping[str, NDArray[Any]] | Sequence[str] | None = None, *, labels: dict[str, str] | None = None, units: Mapping[str, str] | None = None, z: ArrayLike | None = None, styles: Mapping[str, Mapping[str, Any]] | None = None, ylabel: str | None = None, title: str = '', style: Style | None = None, latex_labels: bool = False)
Bases: Plot[Any]
Background cosmological quantities plotted against redshift, on one panel.
Accepts, as first argument:
- a redshift array plus a
{name: values}dict (the plain-array form); - a :class:
~cplots.core.data.BackgroundData; - an :class:
~cplots.Observablesadapter, or any solver result that :func:cplots.as_observablesrecognises (classy.Class,CAMBdata, an eft4pyBackgroundGrid…), withquantitiesa list of names; - a
{label: source}mapping of any of the above, to overlay several codes. Each source gets its own line style and each quantity its own colour, and every source is converted to the first one's units (or units).
For quantities of different kinds (rates, distances, densities…) on separate
panels, use :class:BackgroundPanels.
Example:
>>> BackgroundEvolution(z, {"H": Hz}, labels={"H": r"$H(z)$"}).show()
>>> BackgroundEvolution(
... {"eft4py": grid, "hi_class": cosmo}, ["w_de"], latex_labels=True
... ).show()
Create a BackgroundEvolution plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redshift_or_data
|
NDArray[Any] | BackgroundSource | Mapping[str, BackgroundSource]
|
A redshift array, or one or several background sources (see the class docstring). |
required |
quantities
|
Mapping[str, NDArray[Any]] | Sequence[str] | None
|
With a redshift array, the |
None
|
labels
|
dict[str, str] | None
|
Display labels keyed by quantity name, overriding the auto-generated ones. |
None
|
units
|
Mapping[str, str] | None
|
Requested units keyed by quantity name, e.g.
|
None
|
z
|
ArrayLike | None
|
Redshift grid on which adapters evaluate (or resample). |
None
|
styles
|
Mapping[str, Mapping[str, Any]] | None
|
Per-source matplotlib-style overrides, keyed by source
label, e.g. |
None
|
ylabel
|
str | None
|
Y-axis label. |
None
|
title
|
str
|
Plot title. |
''
|
style
|
Style | None
|
Visual :class: |
None
|
latex_labels
|
bool
|
Pass label strings raw to the backend (for MathJax). |
False
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If a redshift array comes with a list of names. |
KeyError
|
If a source lacks a requested quantity. |
ValueError
|
If sources' units cannot be reconciled. |
Methods:¶
BackgroundPanels¶
BackgroundPanels
¶
BackgroundPanels(data: BackgroundSource | Mapping[str, BackgroundSource], quantities: Sequence[str] | None = None, *, units: Mapping[str, str] | None = None, z: ArrayLike | None = None, styles: Mapping[str, Mapping[str, Any]] | None = None, ncols: int = 2, figsize: tuple[float, float] | None = None, sharex: bool = True, title: str = '', style: Style | None = None, latex_labels: bool = False)
Bases: FigureRenderable
Background quantities on one panel per kind of quantity.
Quantities are grouped by their physical dimension (rates, distances,
densities, dimensionless…) from :mod:cplots.core.quantities; unknown names
get a panel each. Each panel is a :class:BackgroundEvolution, so the inputs,
overlays and unit handling are the same.
Multi-panel figures render with matplotlib, plotly and altair.
Example:
>>> BackgroundPanels(
... {"eft4py": grid, "hi_class": cosmo},
... ["H", "dA", "dL", "w_de", "alpha_M"],
... units={"H": "km/s/Mpc"},
... ).show()
Create the panels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
BackgroundSource | Mapping[str, BackgroundSource]
|
One background source or a |
required |
quantities
|
Sequence[str] | None
|
Quantity names to plot (default: all of a
|
None
|
units
|
Mapping[str, str] | None
|
Requested units keyed by quantity name. |
None
|
z
|
ArrayLike | None
|
Redshift grid on which adapters evaluate (or resample). |
None
|
styles
|
Mapping[str, Mapping[str, Any]] | None
|
Per-source matplotlib-style overrides, keyed by source label. |
None
|
ncols
|
int
|
Panels per row. |
2
|
figsize
|
tuple[float, float] | None
|
Overall figure size. Defaults to 4.5 x 3.5 inches per panel. |
None
|
sharex
|
bool
|
Share the redshift axis across panels. |
True
|
title
|
str
|
Title of the first panel. |
''
|
style
|
Style | None
|
Visual :class: |
None
|
latex_labels
|
bool
|
Pass label strings raw to the backend (for MathJax). |
False
|
ThermodynamicsEvolution¶
ThermodynamicsEvolution
¶
ThermodynamicsEvolution(redshift_or_data: NDArray[Any] | BackgroundSource | Mapping[str, BackgroundSource], quantities: Mapping[str, NDArray[Any]] | Sequence[str] | None = None, *, labels: dict[str, str] | None = None, units: Mapping[str, str] | None = None, z: ArrayLike | None = None, styles: Mapping[str, Mapping[str, Any]] | None = None, ylabel: str | None = None, title: str = '', style: Style | None = None, latex_labels: bool = False)
Bases: BackgroundEvolution
Thermodynamics quantities plotted against redshift on a log x-axis.
Designed for quantities such as the visibility function g(z), ionisation
fraction x_e(z), and optical depth κ(z) that span many orders of magnitude
in redshift. Identical to BackgroundEvolution in every other respect.
Example:
ThermodynamicsEvolution(out.thermodynamics()).show()
TrianglePlot¶
TrianglePlot
¶
TrianglePlot(samples: Any, parameter_names: list[str] | None = None, *, labels: list[str] | None = None, weights: Any = None, truths: dict[str, float] | None = None, title: str = '', style: Style | None = None, latex_labels: bool = False, engine: str = 'getdist', missing: Literal['error', 'skip'] = 'error')
Bases: Plot[Any]
MCMC posterior triangle (corner) plot from one or several sample chains.
Rendering is delegated to a pluggable engine= that wraps a third-party
triangle plot library. Three engines are built in:
"getdist"(default) — wraps the getdist library; install withpip install cplots[getdist]."chainconsumer"— wraps ChainConsumer via narwhals; install withpip install cplots[chainconsumer]."anesthetic"— wraps anesthetic; install withpip install cplots[anesthetic].
A chain is an (N, D) array (columns named by parameter_names), a
:class:~cplots.core.data.TriangleData, or anything
:func:~cplots.data.adapters.to_plot_data adapts to one (e.g. a getdist
MCSamples). Several chains are overlaid, with a legend, when
samples is a list/tuple of chains or a {label: chain} dict.
The spec holds a single :class:~cplots.core.spec.TriangleTrace. Only the
matplotlib backend draws it, and only as a standalone figure (not as a
:class:~cplots.Figure panel).
Example::
# One chain, default engine (getdist)
TrianglePlot(
samples, # shape (N, D)
["omega_m", "sigma_8"],
labels=[r"\Omega_m", r"\sigma_8"],
truths={"omega_m": 0.3},
).show()
# Several chains, labelled by the dict keys
TrianglePlot(
{"NUTS": nuts_samples, "MH": TriangleData(mh_samples, names, weights=w)},
names,
).show()
# Explicit alternative engine
TrianglePlot(samples, [...], engine="anesthetic").show()
Create a TrianglePlot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples
|
Any
|
One chain, a sequence of chains (including an
|
required |
parameter_names
|
list[str] | None
|
Parameters to plot, as stable identifiers (no
LaTeX); also the column names of array chains, so required
when any chain is an array. When |
None
|
labels
|
list[str] | None
|
Optional LaTeX display labels (without |
None
|
weights
|
Any
|
Importance weights: an |
None
|
truths
|
dict[str, float] | None
|
Optional mapping from parameter name to fiducial value. Fiducial lines are drawn on matching parameters. |
None
|
title
|
str
|
Plot title. |
''
|
style
|
Style | None
|
Visual :class: |
None
|
latex_labels
|
bool
|
Deprecated; use |
False
|
engine
|
str
|
Triangle rendering engine name. Built-in values are
|
'getdist'
|
missing
|
Literal['error', 'skip']
|
What to do when a chain lacks a plotted parameter:
|
'error'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If an array chain has no |
TypeError
|
If a chain cannot be converted to |
PosteriorBands¶
PosteriorBands
¶
PosteriorBands(z_or_data: NDArray[Any] | PosteriorBandsData, samples: NDArray[Any] | None = None, *, weights: NDArray[Any] | None = None, levels: tuple[float, ...] = (68.27, 95.45), alphas: tuple[float, ...] = (0.4, 0.2), show_median: bool = True, color: str | None = None, data_color: str | None = None, x_obs: NDArray[Any] | None = None, y_obs: NDArray[Any] | None = None, y_err: NDArray[Any] | None = None, xlabel: str = '$z$', ylabel: str = '', xscale: Scale = 'linear', yscale: Scale = 'linear', title: str = '', style: Style | None = None, figsize: tuple[float, float] | None = None, latex_labels: bool = False, max_samples: int | None = None, seed: int = 0, envelope: bool = False, envelope_style: Mapping[str, Any] | None = None, envelope_bins: int | None = None, level_label: str = '{level:.4g}% CI')
Bases: Plot[Any]
Predictive posterior bands from MCMC samples of an observable y(z).
Renders shaded confidence intervals (and optionally a median line) derived from an ensemble of observable predictions, with optional overlay of measurement data points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z_or_data
|
NDArray[Any] | PosteriorBandsData
|
Redshift grid of shape (N_z,), or a pre-built
:class: |
required |
samples
|
NDArray[Any] | None
|
Observable values for each MCMC sample, shape (N_samples, N_z). Required when z_or_data is an array. |
None
|
weights
|
NDArray[Any] | None
|
Importance weights for each sample, shape (N_samples,). None assumes uniform weights (standard MCMC chains). |
None
|
levels
|
tuple[float, ...]
|
Confidence levels to display as bands, in percent.
Default |
(68.27, 95.45)
|
alphas
|
tuple[float, ...]
|
Fill opacity for each confidence level, matched by position to levels. Inner (narrower) bands should be more opaque. |
(0.4, 0.2)
|
show_median
|
bool
|
Whether to draw the median as a solid line. |
True
|
color
|
str | None
|
Colour of all bands, the median and the envelope. None uses the first colour of the style palette for all of them. |
None
|
data_color
|
str | None
|
Colour of the observed data points. None uses the second palette colour. |
None
|
x_obs
|
NDArray[Any] | None
|
X-values of observed data points, shape (N_obs,). |
None
|
y_obs
|
NDArray[Any] | None
|
Y-values of observed data points, shape (N_obs,). |
None
|
y_err
|
NDArray[Any] | None
|
Uncertainties for the observed data. Shape (N_obs,) for symmetric or (2, N_obs) for asymmetric [lower, upper] errors. |
None
|
xlabel
|
str
|
X-axis label. |
'$z$'
|
ylabel
|
str
|
Y-axis label. |
''
|
xscale
|
Scale
|
X-axis scale ( |
'linear'
|
yscale
|
Scale
|
Y-axis scale. |
'linear'
|
title
|
str
|
Plot title. |
''
|
style
|
Style | None
|
Visual :class: |
None
|
figsize
|
tuple[float, float] | None
|
Figure size |
None
|
latex_labels
|
bool
|
Pass axis labels raw to the backend (for MathJax). |
False
|
max_samples
|
int | None
|
If set and the chain has more rows, quantiles are computed from a weighted bootstrap subsample of this size instead of the full chain. Intended for heavily autocorrelated MCMC chains whose effective sample size is far below the row count — band estimates are statistically unchanged while sorting cost drops sharply. None (default) uses every sample. |
None
|
seed
|
int
|
Random seed for the |
0
|
envelope
|
bool
|
Also draw the per-x minimum and maximum of the samples as thin dashed curves (e.g. the worst cases next to the bands). |
False
|
envelope_bins
|
int | None
|
Draw the envelope from the extremes in this many intervals of x (log-spaced if x > 0) instead of at every x, for dense grids. |
None
|
envelope_style
|
Mapping[str, Any] | None
|
Matplotlib keyword arguments for the envelope curves, over
|
None
|
level_label
|
str
|
Legend text of each band, formatted with |
'{level:.4g}% CI'
|
PosteriorBandsGroup¶
PosteriorBandsGroup
¶
PosteriorBandsGroup(x: NDArray[Any], groups: list[BandGroup] | tuple[BandGroup, ...], *, levels: tuple[float, ...] = (68.27, 95.45), alphas: tuple[float, ...] = (0.4, 0.2), show_median: bool = True, ref_curves: Sequence[tuple[Any, str, dict[str, Any]]] = (), ref_lines: Sequence[tuple[float, str, dict[str, Any]]] = (), ref_points: Sequence[tuple[Any, Any, str, dict[str, Any]]] = (), annotations: Sequence[tuple[float, float, str, dict[str, Any]]] = (), band_labels: bool = True, level_label: str = '{level:.4g}% CI', xlabel: str = '$z$', ylabel: str = '', xscale: Scale = 'linear', yscale: Scale = 'linear', title: str = '', style: Style | None = None, figsize: tuple[float, float] | None = None, latex_labels: bool = False)
Bases: Plot[Any]
Credible bands of several sample sets on a shared x grid, with overlays.
Multi-group generalization of :class:PosteriorBands: each
:class:BandGroup gets its own bands/median/color/legend entry, and the
plot accepts generic reference decorations (curves, horizontal lines,
scatter points). Quantiles reuse :func:weighted_quantiles, one shared
sort pass per group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
NDArray[Any]
|
Shared x grid, shape (N_x,). |
required |
groups
|
list[BandGroup] | tuple[BandGroup, ...]
|
The sample sets to band, as :class: |
required |
levels
|
tuple[float, ...]
|
Confidence levels in percent, default 1σ and 2σ. |
(68.27, 95.45)
|
alphas
|
tuple[float, ...]
|
Fill opacity per level, matched by position to levels. |
(0.4, 0.2)
|
show_median
|
bool
|
Draw each group's median on its innermost band. |
True
|
ref_curves
|
Sequence[tuple[Any, str, dict[str, Any]]]
|
|
()
|
ref_lines
|
Sequence[tuple[float, str, dict[str, Any]]]
|
|
()
|
ref_points
|
Sequence[tuple[Any, Any, str, dict[str, Any]]]
|
|
()
|
annotations
|
Sequence[tuple[float, float, str, dict[str, Any]]]
|
|
()
|
band_labels
|
bool
|
If False, suppress all band legend entries. |
True
|
level_label
|
str
|
Legend text of each band of a single unlabelled group, formatted
with |
'{level:.4g}% CI'
|
xlabel
|
str
|
X-axis label. |
'$z$'
|
ylabel
|
str
|
Y-axis label. |
''
|
xscale
|
Scale
|
X-axis scale ( |
'linear'
|
yscale
|
Scale
|
Y-axis scale. |
'linear'
|
title
|
str
|
Plot title. |
''
|
style
|
Style | None
|
Visual :class: |
None
|
figsize
|
tuple[float, float] | None
|
Figure size |
None
|
latex_labels
|
bool
|
Pass axis labels raw to the backend (for MathJax). |
False
|
BandGroup
dataclass
¶
BandGroup(samples: NDArray[Any], weights: NDArray[Any] | None = None, color: str | None = None, label: str = '', envelope: bool = False, envelope_style: Mapping[str, Any] | None = None, envelope_bins: int | None = None)
One sample set's curves plus styling for :class:PosteriorBandsGroup.
Attributes:
| Name | Type | Description |
|---|---|---|
samples |
NDArray[Any]
|
Observable values per MCMC sample, shape (N_samples, N_x). |
weights |
NDArray[Any] | None
|
Importance weights, shape (N_samples,). None = uniform. |
color |
str | None
|
Color for this group's bands, median and envelope. None uses the palette colour at the group's position (first group, first colour). |
label |
str
|
Legend label, drawn once on the group's innermost band ("" suppresses the entry). |
envelope |
bool
|
Also draw the group's per-x minimum and maximum as thin dashed curves, in the group's colour. |
envelope_style |
Mapping[str, Any] | None
|
Matplotlib keyword arguments for those curves. |
envelope_bins |
int | None
|
Draw the envelope from the extremes in this many intervals of x (log-spaced if x > 0) instead of at every x, for dense grids. |
XYZColored¶
XYZColored
¶
XYZColored(x: NDArray[Any] | list[NDArray[Any]], y: list[NDArray[Any]], z: list[float], *, labels: str | list[str] = '', xlabel: str = '', ylabel: str = '', clabel: str = '', title: str = '', xscale: Scale = 'linear', yscale: Scale = 'linear', colormap: str = DEFAULT_COLORMAP, clim: tuple[float, float] | None = None, colorbar: bool | Mapping[str, Any] = True, alpha: float = 1.0, style: Style | None = None, figsize: tuple[float, float] | None = None, latex_labels: bool = False)
Bases: Plot[Any]
XY plot where each curve is color-coded by a scalar Z value.
Useful for sweeping a parameter (redshift, mass, etc.) and visualizing how curves change continuously across it.
Examples:
# Shared x, one z value per curve
XYZColored(x, [y0, y1, y2], z=[0.0, 0.5, 1.0], clabel="redshift")
# Per-curve x arrays
XYZColored([x0, x1], [y0, y1], z=[0.3, 1.5], colormap="plasma")
Create an XYZColored plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
NDArray[Any] | list[NDArray[Any]]
|
X-axis data. A single array is broadcast to all traces; a list provides per-trace arrays. |
required |
y
|
list[NDArray[Any]]
|
List of y-axis arrays, one per trace. |
required |
z
|
list[float]
|
Scalar color values, one per trace. Controls the colormap mapping (e.g. redshift values for a redshift sweep). |
required |
labels
|
str | list[str]
|
Legend label(s). A single string is reused for all traces. |
''
|
xlabel
|
str
|
X-axis label. |
''
|
ylabel
|
str
|
Y-axis label. |
''
|
clabel
|
str
|
Colorbar label. |
''
|
title
|
str
|
Plot title. |
''
|
xscale
|
Scale
|
X-axis scale — |
'linear'
|
yscale
|
Scale
|
Y-axis scale. |
'linear'
|
colormap
|
str
|
Named colormap (e.g. |
DEFAULT_COLORMAP
|
clim
|
tuple[float, float] | None
|
Colour-scale limits |
None
|
colorbar
|
bool | Mapping[str, Any]
|
|
True
|
alpha
|
float
|
Line transparency for every curve, in |
1.0
|
style
|
Style | None
|
Visual :class: |
None
|
figsize
|
tuple[float, float] | None
|
Figure size |
None
|
latex_labels
|
bool
|
Pass label strings raw to the backend (for MathJax). |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Methods:¶
XYZColoredGrid¶
XYZColoredGrid
¶
XYZColoredGrid(panels: list[XYZColored], *, nrows: int | None = None, ncols: int | None = None, shared_colorbar: bool = False, clabel: str = '', colormap: str | None = None, clim: tuple[float, float] | None = None, colorbar: Mapping[str, Any] | None = None, figsize: tuple[float, float] | None = None, style: Style | None = None, latex_labels: bool = False, hspace: float | None = None, wspace: float | None = None)
Bases: FigureRenderable
Grid of XYZColored plots with optional shared colorbar.
Parameters¶
panels:
List of XYZColored plot objects — one per grid cell.
nrows, ncols:
Grid dimensions. If omitted, auto-layout to a roughly square grid.
shared_colorbar:
When True, suppress per-panel colorbars and render one shared colorbar
spanning the whole figure, normalised globally across all Z values.
When False (default), each panel retains its own colorbar.
clabel:
Colorbar label used when shared_colorbar=True. Falls back to the
first panel's colorbar label when omitted.
colormap:
Colormap name for the shared colorbar. Falls back to the first
panel's colormap when omitted. Only used when shared_colorbar=True.
clim:
Colour-scale limits (vmin, vmax) applied to every panel (and to the shared colourbar).
None uses the data range. A symmetric (-m, m) centres a diverging colormap on zero.
colorbar:
:class:~cplots.core.spec.ColorbarSpec fields applied to every colourbar drawn
(each panel's, or the shared one), e.g. {"label_loc": "bottom", "pad": 0.05}.
figsize:
Overall figure size (width, height) in inches.
style:
Visual :class:~cplots.Style applied to all panels.
latex_labels:
Propagate raw LaTeX strings to all panels.
Examples¶
panels = [
XYZColored(k, [pk_z0, pk_z1, pk_z2], z, ylabel="P(k)", xscale="log", yscale="log"),
XYZColored(k, [dk_z0, dk_z1, dk_z2], z, ylabel="D(k)", xscale="log", yscale="log"),
]
# Per-panel colorbars (default)
XYZColoredGrid(panels, figsize=(12, 4)).show()
# Single shared colorbar
XYZColoredGrid(panels, shared_colorbar=True, clabel="redshift").show()
ResidualFigure¶
ResidualFigure
¶
ResidualFigure(plot: Plot[Any], reference: int | str | NDArray[Any] = 0, *, reference_x: NDArray[Any] | None = None, mode: Literal['absolute', 'relative', 'ratio'] = 'relative', heights: tuple[float, float] = (3, 1), include_reference: bool = False, hspace: float | None = None)
Bases: FigureRenderable
Two-panel figure: main observable on top, residuals below on a shared x-axis.
Produced by :meth:~cplots.core.base.Plot.with_residuals. Use
:meth:show, :meth:save, or :meth:render to display the result with
any registered backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plot
|
Plot[Any]
|
The source plot object. |
required |
reference
|
int | str | NDArray[Any]
|
Reference for residual computation. An |
0
|
reference_x
|
NDArray[Any] | None
|
X-grid of an external reference array. Only used when reference is a numpy array and its x-grid differs from the traces in plot. |
None
|
mode
|
Literal['absolute', 'relative', 'ratio']
|
Residual type.
|
'relative'
|
heights
|
tuple[float, float]
|
Relative heights |
(3, 1)
|
include_reference
|
bool
|
When True and the reference is an existing trace, include it in the residuals panel (appears as a flat line at 0 for relative/absolute or 1 for ratio). |
False
|
hspace
|
float | None
|
Vertical gap between the two panels, as a fraction of the mean
axes height (matplotlib |
None
|
PhasePortrait¶
PhasePortrait
¶
PhasePortrait(f: VectorField, bounds: Sequence[tuple[float, float]], *, seeds: SeedStrategy | ArrayLike | None = None, direction: Literal['forward', 'backward', 'both'] = 'both', arclength: float | None = None, resolution: int = 200, method: str = 'auto', color_by: Literal['speed', 'arclength'] | Callable[[NDArray[Any]], float] | None = 'speed', arrows: bool = True, fixed_points: ArrayLike | Sequence[FixedPoint] | Literal['auto'] | None = None, nullclines: bool = False, nullcline_resolution: int = 200, spacing: float | None = None, axis_labels: Sequence[str] = (), clabel: str | None = None, **options: Any)
Bases: Plot[Any]
2D or 3D phase portrait: streamlines of an autonomous system dx/dt = f(x).
The system is arbitrary: pass any callable, a vector field sampled on a
grid (:meth:from_grid) or curves you have already computed
(:meth:from_trajectories). The dimension (2 or 3) follows from bounds.
Integration happens once, in the constructor, independent of the rendering
backend.
Examples:
>>> f = lambda x: [x[1], -x[0] - 0.3 * x[1]]
>>> PhasePortrait(f, bounds=[(-3, 3), (-3, 3)], axis_labels=("x", "v")).show()
>>> g = lambda x: [-x[1], x[0], -0.2 * x[2]]
>>> PhasePortrait(g, [(-2, 2)] * 3, seeds=seeds.sphere((0, 0, 0), 1.5, 40)).show(
... backend="plotly")
Integrate streamlines of f and prepare the plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
VectorField
|
Vector field |
required |
bounds
|
Sequence[tuple[float, float]]
|
|
required |
seeds
|
SeedStrategy | ArrayLike | None
|
Seed strategy from :mod: |
None
|
direction
|
Literal['forward', 'backward', 'both']
|
Integrate |
'both'
|
arclength
|
float | None
|
Max arclength per direction (default: half the box diagonal). |
None
|
resolution
|
int
|
Vertices per box diagonal. |
200
|
method
|
str
|
Integrator, see :func: |
'auto'
|
color_by
|
Literal['speed', 'arclength'] | Callable[[NDArray[Any]], float] | None
|
|
'speed'
|
arrows
|
bool
|
Draw a direction arrowhead on every curve. |
True
|
fixed_points
|
ArrayLike | Sequence[FixedPoint] | Literal['auto'] | None
|
|
None
|
nullclines
|
bool
|
2D only. Draw the curves where |
False
|
nullcline_resolution
|
int
|
Grid points per axis used to locate the nullclines. |
200
|
spacing
|
float | None
|
2D only. Lay the curves out evenly (Jobard-Lefer): the target
distance between neighbours as a fraction of the box diagonal, e.g.
|
None
|
axis_labels
|
Sequence[str]
|
Axis labels, one per dimension. |
()
|
clabel
|
str | None
|
Colourbar label; defaults to the |
None
|
**options
|
Any
|
Fields of :class: |
{}
|
Methods:¶
from_grid
classmethod
¶
Build a portrait from a vector field sampled on a regular grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
VectorFieldData | tuple[Any, ...]
|
A :class: |
required |
**kwargs
|
Any
|
Forwarded to the constructor (bounds default to the grid extent). |
{}
|
from_trajectories
classmethod
¶
from_trajectories(data: TrajectoryData | Sequence[ArrayLike], *, arrows: bool = True, fixed_points: ArrayLike | Sequence[FixedPoint] | None = None, axis_labels: Sequence[str] = (), **options: Any) -> PhasePortrait
Build a portrait from curves you already integrated (no integration done).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
TrajectoryData | Sequence[ArrayLike]
|
A :class: |
required |
arrows
|
bool
|
Draw a direction arrowhead on every curve. |
True
|
fixed_points
|
ArrayLike | Sequence[FixedPoint] | None
|
Optional |
None
|
axis_labels
|
Sequence[str]
|
Axis labels (ignored if data carries its own). |
()
|
**options
|
Any
|
See the constructor. |
{}
|
PortraitStyle
dataclass
¶
PortraitStyle(title: str = '', colormap: str = DEFAULT_COLORMAP, colorbar: bool | Mapping[str, Any] = True, color: str | None = None, linewidth: float = 1.2, alpha: float = 1.0, equal_aspect: bool = False, arrow_size: float = 1.0, camera: CameraSpec | None = None, clim: tuple[float, float] | None = None, style: Style | None = None, figsize: tuple[float, float] | None = None, latex_labels: bool = False)
Appearance options of a :class:PhasePortrait (its **options keywords).
Attributes:
| Name | Type | Description |
|---|---|---|
title |
str
|
Plot title. |
colormap |
str
|
Colormap for per-vertex colouring ( |
colorbar |
bool | Mapping[str, Any]
|
Draw the colourbar when the curves are coloured ( |
color |
str | None
|
Flat curve colour when |
linewidth |
float
|
Curve width in points. |
alpha |
float
|
Curve opacity. |
equal_aspect |
bool
|
Equal data-unit scaling on all axes. |
arrow_size |
float
|
Multiplier on the arrowhead size; must be positive. |
camera |
CameraSpec | None
|
3D only: a :class: |
clim |
tuple[float, float] | None
|
Colour-scale limits |
style |
Style | None
|
Visual :class: |
figsize |
tuple[float, float] | None
|
Figure size |
latex_labels |
bool
|
Pass label strings raw to the backend (for MathJax). |
ScatterTriangle¶
ScatterTriangle
¶
ScatterTriangle(points: ArrayLike, values: ArrayLike, parameter_names: Sequence[str], *, labels: Sequence[str] | None = None, reference: ArrayLike | None = None, bounds: Sequence[tuple[float, float]] | Mapping[str, tuple[float, float]] | None = None, colormap: str = DEFAULT_COLORMAP, cscale: Literal['linear', 'log'] = 'linear', clim: tuple[float, float] | None = None, clabel: str = '', colorbar: bool | Mapping[str, Any] = True, diagonal: Literal['binned', 'hist', 'none'] | None = 'binned', bins: int = 12, marker_size: float = 8.0, reference_style: Mapping[str, Any] | None = None, title: str = '', style: Style | None = None, figsize: tuple[float, float] | None = None)
Bases: Plot[Any]
Lower-triangle grid of pairwise scatters, each point coloured by a value.
Shows where in a parameter space a quantity is large: e.g. an emulator's error over a test design (with the training design as a grey reference), a likelihood over a grid, or a figure of merit over a survey design. Points are drawn in increasing value order, so the largest values sit on top. The diagonal shows the value against each parameter (binned median and 95th percentile), a histogram of the parameter, or nothing.
Only the matplotlib backend draws it, as a whole figure (it cannot be a panel of
a :class:~cplots.Figure).
Examples::
ScatterTriangle(theta, errors, ["h", "omega_b", "omega_cdm"],
labels=[r"$h$", r"$\omega_b$", r"$\omega_{cdm}$"],
reference=theta_train, cscale="log", clabel="error").save("err.pdf")
Create a ScatterTriangle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points
|
ArrayLike
|
Point coordinates, shape |
required |
values
|
ArrayLike
|
One value per point, shape |
required |
parameter_names
|
Sequence[str]
|
Names of the |
required |
labels
|
Sequence[str] | None
|
Axis labels ( |
None
|
reference
|
ArrayLike | None
|
A second point set |
None
|
bounds
|
Sequence[tuple[float, float]] | Mapping[str, tuple[float, float]] | None
|
Axis limits: |
None
|
colormap
|
str
|
Named colormap (default :data: |
DEFAULT_COLORMAP
|
cscale
|
Literal['linear', 'log']
|
|
'linear'
|
clim
|
tuple[float, float] | None
|
Colour limits |
None
|
clabel
|
str
|
Colourbar label. |
''
|
colorbar
|
bool | Mapping[str, Any]
|
|
True
|
diagonal
|
Literal['binned', 'hist', 'none'] | None
|
|
'binned'
|
bins
|
int
|
Bins of the diagonal panels. |
12
|
marker_size
|
float
|
Marker area in points^2. |
8.0
|
reference_style
|
Mapping[str, Any] | None
|
Matplotlib keyword arguments for the reference markers. |
None
|
title
|
str
|
Figure title. |
''
|
style
|
Style | None
|
Visual :class: |
None
|
figsize
|
tuple[float, float] | None
|
Figure size in inches. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If shapes disagree, or a log scale gets no positive value. |