toad.plotting.Plotter

class toad.plotting.Plotter(td)

Bases: object

Plotting utilities for TOAD objects.

The Plotter class provides methods for creating publication-ready visualizations of TOAD data, including maps, timeseries, and statistical plots.

Parameters:

td – TOAD object containing the data to plot

__init__(td)

Methods

__init__(td)

cluster_map(, *, ax, color, cmap, ...)

Plot one or multiple clusters on a map.

cluster_occurrence_rate_map(*[, ...])

Map the fraction of input clusterings that ever labelled each cell.

cluster_overview(**kwargs)

Deprecated function: use td.plot.overview() instead.

cluster_shift_times_violins([var, ...])

Transition-time event samples for a single 3D cluster label field (not consensus).

consensus_map([consensus_var, cluster_ids, ...])

Plot consensus cluster footprints on a map (same layout ideas as cluster_map()).

consensus_overview([consensus_var, ...])

Two-panel figure: consensus map (left) and shift-time view (right).

consensus_rate_map([consensus_var, ...])

Map member-support consensus rate from a consensus run (time-collapsed).

consensus_shift_times_medians([...])

Per-input median transition time vs median-of-medians summary (from consensus_summary()).

consensus_shift_times_violins([...])

Transition-time samples per consensus cluster: half-violin + scatter or full violins.

consensus_timeseries(cluster_id[, ...])

Overlay per-input-cluster timeseries for one consensus cluster (no map).

map(...)

Create map plots with standard features.

max_shift_map([var, cluster_ids, ax, ...])

Plot a map showing the value in the time dimension where the absolute value of the shift is maximal, keeping sign.

overview([var, cluster_ids, map_style, mode])

Create an overview plot with map and timeseries for clusters.

shift_dist([figsize, yscale, bins])

Plot histograms showing the distribution of shifts for each shift variable.

time_of_max_shift_map([var, cluster_ids, ...])

Plot a map showing the time at which the maximal shift occurs for a given variable.

timeseries([var, cluster_ids, ...])

Plot time series from clusters or all data.

cluster_map(var: str | None = None, cluster_ids: int | List[int] | ndarray | range | None = range(9), *, ax: Axes | None = None, color: str | Tuple | List[str | Tuple] | None = None, cmap: str | ListedColormap = default_cmap, map_cmap_other: str | Colormap | None = default_cmap_other, include_all_clusters: bool = True, subplots: Literal[False] = False, ncols: int = 3, figsize: Tuple[float, float] | None = None, map_style: MapStyle | dict | None = None, **kwargs: Any) Tuple[FigureBase | None, Axes | None]
cluster_map(var: str | None = None, cluster_ids: int | List[int] | ndarray | range | None = range(9), *, ax: Axes | None = None, color: str | Tuple | List[str | Tuple] | None = None, cmap: str | ListedColormap = default_cmap, map_cmap_other: str | Colormap | None = default_cmap_other, include_all_clusters: bool = True, subplots: Literal[True], ncols: int = 3, figsize: Tuple[float, float] | None = None, map_style: MapStyle | dict | None = None, **kwargs: Any) Tuple[FigureBase | None, ndarray | None]

Plot one or multiple clusters on a map.

Parameters:
  • var (str | None) –

    Base variable name (e.g. ‘temperature’, will look for

    ’temperature_cluster’) or custom cluster variable name. If None, TOAD will attempt to infer which variable to use.

    A ValueError is raised if the variable cannot be uniquely determined.

  • cluster_ids (int | List[int] | ndarray | range | None) – Single cluster ID or list of cluster IDs to plot. Defaults to range(9) (clusters 0-8) if not provided.

  • map_style (MapStyle | dict | None) – Map style configuration. Can be a MapStyle object, a dict with MapStyle fields, or None (uses defaults). If dict, missing keys use defaults. Controls projection, grid, borders, and cluster visualization options (plot_contour, plot_fill, add_labels, contour_linewidth).

  • ax (Axes | None) – Matplotlib axes to plot on. Creates new figure if None. Cannot be used with subplots=True.

  • color (str | Tuple | List[str | Tuple] | None) – Color for cluster visualization. Can be: - A single color (str, hex, RGB tuple) to use for all clusters. - A list of colors to use for each cluster. Overrides cmap.

  • cmap (str | ListedColormap) – Colormap for multiple clusters. Used only if color is None.

  • map_cmap_other (str | Colormap | None) – Colormap for remaining clusters. Can be: - A string (e.g., “jet”, “cividis”) to use a built-in colormap. - A matplotlib colormap object.

  • include_all_clusters (bool) – If True, plot all clusters on the map. If False, only plot selected clusters. Defaults to True.

  • subplots (bool) – If True, plot each cluster on its own subplot. Defaults to False.

  • figsize (Tuple[float, float] | None) – Figure size when subplots=True. Defaults to (12, 3 * nrows).

  • ncols (int) – Number of columns in subplot grid when subplots=True. Defaults to 3.

  • **kwargs (Any) – Additional arguments passed to xarray.plot methods (e.g., plot, plot.contour).

Returns:

Tuple of (figure, axes). Figure is None if ax was provided. When subplots=True, axes is a numpy array of axes.

Raises:
  • ValueError – If no clusters found for given variable, or if ax is provided with subplots=True.

  • TypeError – If cluster_ids is not an int, list, ndarray, range, or None, or if cmap is not a string or ListedColormap.

Return type:

Tuple[FigureBase | None, Axes | ndarray | None]

cluster_occurrence_rate_map(*, cluster_vars=None, ax=None, map_style=None, cmap='cividis', **kwargs)

Map the fraction of input clusterings that ever labelled each cell.

Uses toad.postprocessing.aggregation.Aggregation.cluster_occurrence_rate(). 1 means every included clustering assigned a non-noise label there at some time; 0 cells are masked out. Timing and cluster id are not compared across inputs (see that method for details).

Parameters:
  • cluster_vars (list[str] | None) – Label variables to aggregate; default all TOAD.cluster_vars.

  • ax (Axes | None) – Axes to draw on; if None, a new figure is created via map().

  • map_style (MapStyle | dict | None) – Passed to map() when ax is None.

  • cmap (str | Colormap | None) – Colormap for the rate field.

  • **kwargs (Any) – Extra arguments forwarded to xarray.DataArray.plot() or plot.pcolormesh (e.g. vmin, vmax).

Returns:

Figure and axes; figure is None if ax was provided.

Return type:

Tuple[FigureBase | None, matplotlib.axes.Axes]

cluster_overview(**kwargs)

Deprecated function: use td.plot.overview() instead.

Parameters:

kwargs (Any)

cluster_shift_times_violins(var=None, cluster_ids=range(0, 9), *, show_scatter=True, ax=None, figsize=None, cmap='tab20b', width=0.75, bw_method=0.18, show_sum=False, show_total=True, total_color='#666666', show_legend=True, ylabel=None, kde_side='right', point_size=15.0, point_alpha=0.75, jitter_half_span=None, seed=None, tight_layout=True, **kwargs)

Transition-time event samples for a single 3D cluster label field (not consensus).

Uses the same per-voxel time convention as consensus_shift_times_violins() but for one clustering result (native cluster ids in that map). Resolves var with TOAD.get_clusters() (base or cluster name).

For consensus timing restricted to one input model’s voxels, prefer consensus_shift_times_violins() with source_input_cluster_var=... instead.

Parameters:
  • var (str | None)

  • cluster_ids (int | List[int] | ndarray | range | None)

  • show_scatter (bool)

  • ax (Axes | None)

  • figsize (Tuple[float, float] | None)

  • cmap (str | ListedColormap)

  • width (float)

  • bw_method (float)

  • show_sum (bool)

  • show_total (bool)

  • total_color (str)

  • show_legend (bool)

  • ylabel (str | None)

  • kde_side (Literal['left', 'right'])

  • point_size (float)

  • point_alpha (float)

  • jitter_half_span (float | None)

  • seed (int | None)

  • tight_layout (bool)

  • kwargs (Any)

Return type:

Tuple[FigureBase | None, Axes]

consensus_map(consensus_var=None, cluster_ids=range(0, 9), *, ax=None, color=None, cmap='tab20b', subplots=False, ncols=3, figsize=None, map_style=None, colorbar_shrink=0.38, colorbar_pad=0.025, colorbar_aspect=28.0, colorbar_orientation='horizontal', colorbar_location=None, colorbar_label=None, **kwargs)

Plot consensus cluster footprints on a map (same layout ideas as cluster_map()).

Uses (consensus == id).any(time) as a 2D mask per consensus cluster id. Labels are disabled for consensus maps (centroid logic is not tied to Stats). When subplots=False, a horizontal colorbar below the map shows the numeric range of the plotted consensus cluster ids (one colour per id).

Parameters:
  • consensus_var (str | None) – Name of the consensus labels variable on td.data. If None and exactly one consensus variable exists, it is used.

  • cluster_ids (int | List[int] | ndarray | range | None) – Consensus cluster id(s) to plot. Defaults to range(9); missing ids are skipped with a warning.

  • ax (Axes | None) – Same role as cluster_map() (without map_cmap_other / include_all_clusters).

  • color (str | Tuple | List[str | Tuple] | None) – Same role as cluster_map() (without map_cmap_other / include_all_clusters).

  • cmap (str | ListedColormap) – Same role as cluster_map() (without map_cmap_other / include_all_clusters).

  • subplots (bool) – Same role as cluster_map() (without map_cmap_other / include_all_clusters).

  • ncols (int) – Same role as cluster_map() (without map_cmap_other / include_all_clusters).

  • figsize (Tuple[float, float] | None) – Same role as cluster_map() (without map_cmap_other / include_all_clusters).

  • map_style (MapStyle | dict | None) – Same role as cluster_map() (without map_cmap_other / include_all_clusters).

  • **kwargs (Any) –

    Same role as cluster_map() (without map_cmap_other / include_all_clusters).

  • colorbar_shrink (float) – Horizontal colorbar length as a fraction of the parent axes span (matplotlib shrink; only when subplots=False). Smaller is shorter.

  • colorbar_pad (float) – Space between the map and the colorbar (axes fraction).

  • colorbar_aspect (float) – Width/height ratio of the colorbar strip (larger = shorter bar).

  • colorbar_orientation (Literal['horizontal', 'vertical']) – "horizontal" (default, below map) or "vertical".

  • colorbar_location (str | None) – For horizontal bars, "left" left-aligns the bar under the map with the label to its right; default centres the bar. For vertical bars, passed to matplotlib location (e.g. "left").

  • colorbar_label (str | None) – Label under the discrete cluster-id colorbar. Default is "consensus cluster id" (not the variable name).

Returns:

(fig, ax) or (fig, axs) when subplots=True.

Return type:

Tuple[FigureBase | None, Axes | ndarray | None]

consensus_overview(consensus_var=None, cluster_ids=None, *, kind='medians', spread='std', figsize=None, width_ratios=(1.25, 1.0), wspace=0.28, cmap='tab20b', colorbar_shrink=0.38, colorbar_pad=0.025, colorbar_aspect=28.0, colorbar_label=None, map_style=None, show_legend=True, ylabel=None, seed=None, show_sum=False, show_total=True, total_color='#666666', bw_method=0.18, **kwargs)

Two-panel figure: consensus map (left) and shift-time view (right).

Left: consensus_map() on the same cluster_ids as the right panel (defaults to every id with data for the chosen kind). Right: consensus_shift_times_medians() when kind="medians" (per-input medians and median-of-medians) or consensus_shift_times_violins() when kind="violins" (pooled sample violins).

Parameters:
  • consensus_var (str | None) – Consensus labels variable; inferred if unique.

  • cluster_ids (int | List[int] | ndarray | range | None) – Subset of consensus cluster ids. Same filtering as the corresponding shift-time plot; default is every id present in the shift data for kind.

  • kind (Literal['medians', 'violins']) – "medians" (default) or "violins" for the right-hand panel.

  • spread (Literal['iqr', 'std']) – Median-plot inter-model spread ("iqr" or "std"). Ignored when kind="violins".

  • show_legend (bool) – Forwarded to the shift-time panel.

  • ylabel (str | None) – Forwarded to the shift-time panel.

  • seed (int | None) – Forwarded to the shift-time panel.

  • show_sum (bool) – Used when kind="violins" only; passed to consensus_shift_times_violins() (pooled columns).

  • show_total (bool) – Used when kind="violins" only; passed to consensus_shift_times_violins() (pooled columns).

  • total_color (str) – Used when kind="violins" only; passed to consensus_shift_times_violins() (pooled columns).

  • bw_method (float) – Violin KDE bandwidth (Axes.violinplot); kind="violins" only.

  • figsize (Tuple[float, float] | None) – Overall figure size; default (12, 5.2).

  • width_ratios (Tuple[float, float]) – GridSpec column width ratios (map, right panel).

  • wspace (float) – Spacing between panels (Figure.subplots_adjust).

  • cmap (str | ListedColormap) – Map panel (see consensus_map() for colorbar_label). The medians panel also uses the same cmap for summary diamond fill unless you pass summary_cluster_cmap in **kwargs (None disables colouring). The violins panel uses cmap for per-cluster colours.

  • colorbar_shrink (float) – Map panel (see consensus_map() for colorbar_label). The medians panel also uses the same cmap for summary diamond fill unless you pass summary_cluster_cmap in **kwargs (None disables colouring). The violins panel uses cmap for per-cluster colours.

  • colorbar_pad (float) – Map panel (see consensus_map() for colorbar_label). The medians panel also uses the same cmap for summary diamond fill unless you pass summary_cluster_cmap in **kwargs (None disables colouring). The violins panel uses cmap for per-cluster colours.

  • colorbar_aspect (float) – Map panel (see consensus_map() for colorbar_label). The medians panel also uses the same cmap for summary diamond fill unless you pass summary_cluster_cmap in **kwargs (None disables colouring). The violins panel uses cmap for per-cluster colours.

  • colorbar_label (str | None) – Map panel (see consensus_map() for colorbar_label). The medians panel also uses the same cmap for summary diamond fill unless you pass summary_cluster_cmap in **kwargs (None disables colouring). The violins panel uses cmap for per-cluster colours.

  • map_style (MapStyle | dict | None) – Map panel (see consensus_map() for colorbar_label). The medians panel also uses the same cmap for summary diamond fill unless you pass summary_cluster_cmap in **kwargs (None disables colouring). The violins panel uses cmap for per-cluster colours.

  • **kwargs (Any) – Extra args for the active shift-time function (medians- or violins-specific; e.g. model_point_size / errorbar_capsize, or show_scatter / width). ax and figsize are ignored.

Returns:

(figure, map_axes, shift_axes). The map axes may be a cartopy GeoAxes; the third element is the right-hand (medians or violins) axes.

Return type:

Tuple[FigureBase, Any, Axes]

consensus_rate_map(consensus_var=None, *, time_reduce='max', ax=None, map_style=None, cmap='cividis', vmin=0.0, vmax=1.0, add_colorbar=True, colorbar_orientation=None, colorbar_location=None, colorbar_shrink=None, colorbar_pad=None, colorbar_aspect=None, colorbar_label=None, cbar_kwargs=None, **kwargs)

Map member-support consensus rate from a consensus run (time-collapsed).

Uses the companion field {consensus_var}_rate: at each spacetime cell this is (supporting inputs) / (total inputs) on native event voxels, including voxels below the consensus threshold. The map collapses time with max (default) or mean over finite values, then masks cells where the result is zero (no input ever detected an event there).

Parameters:
  • consensus_var (str | None) – Consensus labels variable; inferred when unique.

  • time_reduce (Literal['max', 'mean']) – "max" (peak agreement at any time) or "mean" over timesteps with data.

  • ax (Axes | None) – Axes to draw on; if None, a new figure is created via map().

  • map_style (MapStyle | dict | None) – Passed to map() when ax is None.

  • cmap (str | Colormap | None) – Colormap for the consensus rate field.

  • vmin (float) – Color scale bounds; default [0, 1].

  • vmax (float) – Color scale bounds; default [0, 1].

  • add_colorbar (bool) – Whether to draw a colorbar (default True).

  • colorbar_orientation (Literal['horizontal', 'vertical'] | None) – "horizontal" or "vertical". If None, xarray uses its default (vertical on the right).

  • colorbar_location (str | None) – For horizontal bars, "left" left-aligns the bar under the map with the label to its right. Otherwise passed to matplotlib location.

  • colorbar_shrink (float | None) – Passed to the colorbar (matplotlib shrink, pad, aspect). Omitted when None.

  • colorbar_pad (float | None) – Passed to the colorbar (matplotlib shrink, pad, aspect). Omitted when None.

  • colorbar_aspect (float | None) – Passed to the colorbar (matplotlib shrink, pad, aspect). Omitted when None.

  • colorbar_label (str | None) – Colorbar label; default "Consensus rate".

  • cbar_kwargs (dict[str, Any] | None) – Extra keyword arguments merged into the colorbar kwargs (after colorbar_* parameters).

  • **kwargs (Any) – Extra arguments forwarded to xarray.DataArray.plot() or plot.pcolormesh (except add_colorbar and cbar_kwargs).

Returns:

(fig, ax); figure is None if ax was provided.

Return type:

Tuple[FigureBase | None, Axes]

consensus_shift_times_medians(consensus_var=None, cluster_ids=None, *, spread='std', ax=None, figsize=None, model_point_size=18.0, model_point_alpha=0.5, model_point_color='#1a1a1a', spread_line_lw=4.0, spread_line_color='#0d0d0d', errorbar_elinewidth=1.75, errorbar_capsize=3.5, errorbar_capthick=1.2, summary_marker='D', summary_marker_size=65.0, summary_cluster_cmap='tab20b', categorical_cluster_axis=None, jitter_half_span=0.18, seed=None, show_legend=True, ylabel=None, tight_layout=True)

Per-input median transition time vs median-of-medians summary (from consensus_summary()).

One point per input cluster_var at that map’s spatial median transition time in the cluster; the large marker is median_median_shift_time. Inter-model spread defaults to symmetric error bars at median_median_shift_time ± std_median_shift_time (table columns) when those table values are finite. If not, the same IQR line as spread="iqr" (quartiles of per-input medians) is used. With spread="iqr", spread is always that vertical segment between the 25th and 75th percentiles of model medians.

Parameters:
  • consensus_var (str | None) – Consensus labels variable; inferred if unique.

  • cluster_ids (int | List[int] | ndarray | range | None) – Subset of consensus cluster ids; default plots every id present in the shift-time dataset.

  • spread (Literal['iqr', 'std']) – "std" (default) — errorbar from table when possible, else IQR of per-input medians; "iqr" — always a thick vertical line between quartiles of model medians.

  • ax (Axes | None) – Axis or new figure size.

  • figsize (Tuple[float, float] | None) – Axis or new figure size.

  • model_point_size (float) – Per-model scatter.

  • model_point_alpha (float) – Per-model scatter.

  • model_point_color (str) – Per-model scatter.

  • spread_line_lw (float) – IQR / fallback line width and colour (spread="iqr" or std fallback when table std is missing).

  • spread_line_color (str) – IQR / fallback line width and colour (spread="iqr" or std fallback when table std is missing).

  • errorbar_elinewidth (float) – errorbar styling (spread="std" only).

  • errorbar_capsize (float) – errorbar styling (spread="std" only).

  • errorbar_capthick (float) – errorbar styling (spread="std" only).

  • summary_marker (Literal['D', 'o']) – Summary median marker.

  • summary_marker_size (float) – Summary median marker.

  • summary_cluster_cmap (str | ListedColormap | None) – Fill colour of each summary diamond from this colormap (same sampling as consensus_map()). Defaults to default_cmap (tab20b); pass None for white faces with a black edge.

  • categorical_cluster_axis (bool | None) – If True, x positions are 0..n-1 with tick labels showing cluster ids (useful for sparse ids like 1,4,6). If False, x matches cluster id numerically. If None, use categorical mode when cluster ids are not a contiguous block (so there are no large empty gaps between ticks).

  • jitter_half_span (float) – Half-width of horizontal jitter for model points (x data units).

  • seed (int | None) – RNG seed for jitter.

  • show_legend (bool) – Whether to add a short legend.

  • ylabel (str | None) – Y-axis label; default _transition_time_ylabel().

  • tight_layout (bool) – If False, skip Figure.tight_layout (for embedding in a multi-panel figure; call consensus_overview() instead).

Return type:

Tuple[FigureBase | None, Axes]

consensus_shift_times_violins(consensus_var=None, cluster_ids=range(0, 9), *, show_scatter=True, ax=None, figsize=None, cmap='tab20b', source_input_cluster_var=None, width=0.75, bw_method=0.18, show_sum=False, show_total=True, total_color='#666666', show_legend=True, ylabel=None, kde_side='right', point_size=15.0, point_alpha=0.75, jitter_half_span=None, seed=None, tight_layout=True, **kwargs)

Transition-time samples per consensus cluster: half-violin + scatter or full violins.

Visualises the same pooled consensus_shift_time_distribution() samples that feed pooled_median_shift_time in toad.postprocessing.Aggregation.consensus_summary() (per-cluster columns), plus optional pooled groups (sum / total). Complement consensus_shift_times_medians() for median-of-medians from the table.

Uses toad.postprocessing.Aggregation.consensus_shift_time_distributions(). For a single input map’s events only, pass source_input_cluster_var to match that column in the long table (per-input timing within consensus groups).

  • show_scatter=True (default): half KDE on one side of each tick, fixed-width jittered sample points on the other; IQR and median are not clipped so they straddle the spine. Requires matplotlib ≥ 3.10 (Axes.violinplot(..., side=...)).

  • show_scatter=False: standard symmetric violins with IQR bar and median clipped to each body (see _style_violin_bodies_iqr_median()).

Optional pooled columns (sum / total) use total_color; when both are True, sum is drawn first, then total.

Parameters:
  • consensus_var (str | None) – Consensus labels variable; inferred if there is exactly one.

  • cluster_ids (int | List[int] | ndarray | range | None) – Subset of consensus cluster ids. If None, plots all ids with samples.

  • show_scatter (bool) – If True (default), half-violin + jittered scatter; if False, full violins.

  • ax (Axes | None) – Axes to draw on; creates a new figure if None.

  • figsize (Tuple[float, float] | None) – Figure size when creating a new figure.

  • cmap (str | ListedColormap) – Colormap used to pick face colours per cluster.

  • source_input_cluster_var (str | None) – If set, only transition times that came from this input clustering (cluster_var name in the long table) are used.

  • width (float) – Violin width passed to Axes.violinplot (scatter mode uses half of this per side).

  • bw_method (float) – KDE bandwidth factor passed to Axes.violinplot.

  • show_sum (bool) – Pooled columns (same as before).

  • show_total (bool) – Pooled columns (same as before).

  • total_color (str) – Pooled columns (same as before).

  • show_legend (bool) – If True (default), add a legend (three entries with scatter, two without).

  • ylabel (str | None) – Y-axis label; default _transition_time_ylabel().

  • kde_side (Literal['left', 'right']) – For show_scatter=True only: "left" puts KDE left of the tick, jitter right; "right" swaps.

  • point_size (float) – Scatter markers when show_scatter=True (ignored otherwise).

  • point_alpha (float) – Scatter markers when show_scatter=True (ignored otherwise).

  • jitter_half_span (float | None) – Half-width of horizontal jitter in x data units; default width / 8.

  • seed (int | None) – RNG seed for jitter when show_scatter=True.

  • tight_layout (bool) – If True (default), call fig.tight_layout before returning. Set False when drawing into a composite figure (e.g. consensus_overview()).

  • **kwargs (Any) – Extra arguments forwarded to Axes.violinplot.

Return type:

Tuple[FigureBase | None, Axes]

consensus_timeseries(cluster_id, consensus_var=None, *, var=None, cluster_vars=None, aggregation='raw', percentile=None, normalize=None, keep_full_timeseries=True, ax=None, cmap='tab20b', alpha=1.0, linewidth=1.0, add_legend=True, legend_input_label='cluster_var', legend_include_n_cells=True, legend_autosize=True, legend_fontsize_max=None, legend_fontsize_min=4.0, subplots=False, figsize=None, show_ylabels=False, plot_shift_indicator=False, shift_indicator_size=5.0)

Overlay per-input-cluster timeseries for one consensus cluster (no map).

Wraps toad.postprocessing.Aggregation.consensus_cluster_timeseries(). When subplots=False, all input cluster trajectories are drawn on one axis; when subplots=True, one axis per input cluster_var (shared time axis). Legend entries and subplot titles are prefixed with (N), where N is the number of grid cells in the 2D extraction mask (toad.postprocessing.Aggregation.consensus_extraction_mask_2d()).

Parameters:
  • cluster_id (int) – Consensus cluster id to extract.

  • consensus_var (str | None) – Consensus labels variable; inferred if unique.

  • var (str | None) – Forwarded to consensus_cluster_timeseries.

  • cluster_vars (List[str] | None) – Forwarded to consensus_cluster_timeseries.

  • aggregation (Literal['raw', 'mean', 'sum', 'std', 'median', 'percentile', 'max', 'min'] | str) – Forwarded to consensus_cluster_timeseries.

  • percentile (float | None) – Forwarded to consensus_cluster_timeseries.

  • normalize (Literal['max', 'max_each'] | None | str) – Forwarded to consensus_cluster_timeseries.

  • keep_full_timeseries (bool) – Forwarded to consensus_cluster_timeseries.

  • ax (Axes | None) – Single axis; used only when subplots=False. Ignored when subplots=True.

  • cmap (str | ListedColormap) – Colormap for line colors (tab-like sampling).

  • alpha (float) – Line styling. With aggregation="raw", one legend entry per input cluster_var (all per-cell lines share colour and label).

  • linewidth (float) – Line styling. With aggregation="raw", one legend entry per input cluster_var (all per-cell lines share colour and label).

  • add_legend (bool) – Line styling. With aggregation="raw", one legend entry per input cluster_var (all per-cell lines share colour and label).

  • legend_input_label (Literal['cluster_var', 'member_id', 'realisation']) – "cluster_var" (default) uses the full input variable name; "member_id" uses a CMIP-style member id parsed from the name (e.g. r1i1p1f1 from mlotst_r1i1p1f1_dts_cluster); "realisation" uses only the realisation index (e.g. r1, r2).

  • legend_include_n_cells (bool) – If True (default), prefix each legend entry with (N) where N is the number of grid cells in the extraction mask.

  • legend_autosize (bool) – If True (default) and subplots=False, shrink legend font size until the legend box fits inside the axes (helps many/long labels).

  • legend_fontsize_max (float | None) – Bounds for autosizing (points); max defaults to :rc:`legend.fontsize`.

  • legend_fontsize_min (float) – Bounds for autosizing (points); max defaults to :rc:`legend.fontsize`.

  • subplots (bool) – If True, one subplot per contributing input clustering variable.

  • figsize (Tuple[float, float] | None) – Used when creating a figure.

  • show_ylabels (bool) – If True, set a default y label on each subplot when subplots=True.

  • plot_shift_indicator (bool) – If True (and aggregation="raw" with per-cell cell_xy data), overlay dots at timesteps where each cell falls inside a native cluster window for that input cluster_var (union of native ids on the consensus extraction footprint; uses the same masking idea as timeseries()). Ignored for aggregated trajectories (single line per input).

  • shift_indicator_size (float) – Marker size in points for shift dots.

Return type:

Tuple[FigureBase | None, Axes | ndarray | None]

map(nrows: Literal[1] = 1, ncols: Literal[1] = 1, *, figsize: Tuple[float, float] | None = None, height_ratios: List[float] | None = None, width_ratios: List[float] | None = None, subplot_spec: Any = None, map_style: MapStyle | dict | None = None) Tuple[FigureBase, Axes]
map(nrows: int, ncols: int = 1, *, figsize: Tuple[float, float] | None = None, height_ratios: List[float] | None = None, width_ratios: List[float] | None = None, subplot_spec: Any = None, map_style: MapStyle | dict | None = None) Tuple[FigureBase, ndarray]

Create map plots with standard features.

Parameters:
  • nrows (int) – Number of rows in subplot grid

  • ncols (int) – Number of columns in subplot grid

  • figsize (Tuple[float, float] | None) – Figure size (width, height) in inches. If None, not set (matplotlib default).

  • height_ratios (List[float] | None) – List of height ratios for subplots

  • width_ratios (List[float] | None) – List of width ratios for subplots

  • subplot_spec (Any | None) – A gridspec subplot spec to place the map in

  • map_style (MapStyle | dict | None) – Map style configuration. Can be a MapStyle object, a dict with MapStyle fields, or None (uses defaults). If dict, missing keys use defaults. The projection is set via map_style.projection.

Returns:

Tuple of (figure, axes). If nrows=1 and ncols=1, returns a single Axes. Otherwise, returns a numpy array of axes.

Return type:

Tuple[FigureBase, Axes | ndarray]

max_shift_map(var=None, *, cluster_ids=None, ax=None, map_style=None, cmap='RdBu_r', **kwargs)

Plot a map showing the value in the time dimension where the absolute value of the shift is maximal, keeping sign.

Parameters:
  • var (str | None) – Name of the variable for which to compute the maximum shift. If None, TOAD will attempt to infer which variable to use. A ValueError is raised if the variable cannot be uniquely determined.

  • cluster_ids (int | list[int] | range | None) – Optional integer or list of integers specifying which cluster IDs to analyze. If None, analyzes all clusters. If specified, only analyzes grid cells belonging to the given cluster(s).

  • ax (Axes | None) – Matplotlib axes to plot on. Creates new figure if None.

  • map_style (MapStyle | dict | None) – Configuration for the map style. Can be a MapStyle instance or a dictionary containing style settings. Defaults to None.

  • cmap (str | Colormap | None) – Colormap to use for the plot. Can be a string name of a colormap recognized by matplotlib, or an actual Colormap object. Defaults to ‘RdBu_r’.

  • kwargs (Any)

Returns:

The created matplotlib Figure (None if ax was provided) and Axes objects.

Return type:

Tuple[FigureBase | None, matplotlib.axes.Axes]

Notes

For each location, this plots the value along the time axis whose absolute value is maximal. Locations with all-NaN values will be masked out.

overview(var=None, cluster_ids=range(0, 6), map_style=None, mode='timeseries', **kwargs)

Create an overview plot with map and timeseries for clusters.

This is a convenience method that creates a combined visualization showing both the spatial distribution of clusters on a map and their corresponding timeseries. It automatically enables subplots and map display.

Parameters:
  • var (str | None) – Base variable or cluster variable. If None, TOAD will attempt to infer which variable to use. A ValueError is raised if the variable cannot be uniquely determined.

  • cluster_ids (int | List[int] | ndarray | range | None) – ID or list of IDs of clusters to plot. Defaults to range(6) (clusters 0-5).

  • map_style (MapStyle | dict | None) – Map style configuration. Can be a MapStyle object, a dict with MapStyle fields, or None (uses defaults). If dict, missing keys use defaults.

  • mode (Literal['timeseries', 'aggregated']) – Visualization mode. “timeseries” shows individual trajectories, “aggregated” shows statistical summaries (median, range, IQR).

  • **kwargs (Any) – Additional arguments passed to timeseries() method.

Returns:

Tuple of (figure, dict) with keys ‘map’ and ‘timeseries’. - ‘map’: Axes for the map plot - ‘timeseries’: List of axes for timeseries subplots (one per cluster)

Return type:

Tuple[FigureBase | None, dict]

shift_dist(figsize=None, yscale='log', bins=20)

Plot histograms showing the distribution of shifts for each shift variable.

Parameters:
  • figsize (tuple | None) – Figure size (width, height) in inches. If None, defaults to (12, 2 * number of shift variables).

  • yscale (str) – Scale for the y-axis. Defaults to “log”.

  • bins – Number of bins for the histogram. Defaults to 20.

Returns:

Tuple of (figure, axes). Axes is a numpy array of axes (one per shift variable).

td: TOAD
time_of_max_shift_map(var=None, *, cluster_ids=None, ax=None, map_style=None, cmap='turbo', shift_threshold=0.5, shift_direction='both', **kwargs)

Plot a map showing the time at which the maximal shift occurs for a given variable.

Parameters:
  • var (str | None) – Name of the variable for which to compute the time of maximum shift. If None, TOAD will attempt to infer which variable to use. A ValueError is raised if the variable cannot be uniquely determined.

  • cluster_ids (int | list[int] | range | None) – Optional integer or list of integers specifying which cluster IDs to analyze. If None, analyzes all clusters. If specified, only analyzes grid cells belonging to the given cluster(s).

  • ax (Axes | None) – Matplotlib axes to plot on. Creates new figure if None.

  • map_style (MapStyle | dict | None) – Configuration for the map style. Can be a MapStyle instance or a dictionary containing style settings. Defaults to None.

  • cmap (str | Colormap | None) – Colormap to use for the plot. Can be a string name of a colormap recognized by matplotlib, or an actual Colormap object. Defaults to ‘turbo’.

  • shift_threshold (float) – Threshold value for shift magnitude above which a transition is detected. This value is passed to compute_transition_time. Defaults to 0.5.

  • shift_direction (Literal['both', 'positive', 'negative'] | str) – Sign of shifts to map ("both", "positive", or "negative"). Passed to TimeStats.compute_transition_time(). Defaults to "both".

  • kwargs (Any)

Returns:

The created matplotlib Figure (None if ax was provided) and Axes objects.

Return type:

Tuple[FigureBase | None, matplotlib.axes.Axes]

timeseries(var=None, cluster_ids=None, *, timeseries_var=None, ax=None, color=None, cmap='tab20b', normalize=None, add_legend=True, plot_trajectories=True, max_trajectories=1000, trajectories_sample_seed=0, trajectory_ids=None, trajectories_alpha=0.5, trajectories_linewidth=0.5, full_timeseries=True, highlight_color=None, highlight_alpha=0.5, highlight_linewidth=0.5, plot_shift_indicator=False, shift_indicator_size=5.0, plot_dts=False, plot_median=False, plot_mean=False, median_linewidth=3, mean_linewidth=3, plot_trajectory_range=False, plot_trajectory_std=False, trajectory_range_alpha=0.2, trajectory_std_alpha=0.4, plot_cluster_duration=True, cluster_duration_color=None, cluster_duration_alpha=0.25, plot_map=False, map_var=None, map_cmap_other=<matplotlib.colors.ListedColormap object>, map_include_all_clusters=True, subplots=False, ncols=1, figsize=None, wspace=0.1, hspace=0.1, show_ylabels=False, shared_ylabel=None, shared_ylabel_pad=0.03, shared_ylabel_fontsize=None, vertical=False, width_ratios=(1.0, 1.0), height_ratios=None, map_style=None, **plot_kwargs)

Plot time series from clusters or all data.

This function allows flexible plotting of individual trajectories, aggregated statistics (median/mean), shaded regions (full range and IQR), and shift duration indicators. If no clusters are provided, plots all timeseries from the dataset.

Can optionally create separate subplots for each cluster, and optionally include a map showing cluster spatial locations alongside the timeseries.

Parameters:
  • var (str | None) – Base variable or cluster variable. If None, TOAD will attempt to infer which variable to use. A ValueError is raised if the variable cannot be uniquely determined.

  • cluster_ids (int | List[int] | ndarray | range | None) – ID or list of IDs of clusters to plot. If None, plots all timeseries from the dataset (no clustering). Cannot be None if plot_map=True.

  • timeseries_var (str | None) – Variable name to plot (if different from var). Defaults to var.

  • ax (Axes | None) – Matplotlib axes to plot on. Creates new figure if None. Ignored if subplots=True or plot_map=True.

  • color (str | None) – Single color to use for all plotted clusters. Overrides cmap.

  • cmap (str | ListedColormap) – Colormap to use if plotting multiple clusters and color is None.

  • normalize (Literal['max', 'max_each'] | None | str) – Method to normalize timeseries (‘max’, ‘max_each’). Defaults to None.

  • add_legend (bool) – If True, add a legend indicating cluster IDs.

  • plot_trajectories (bool) – If True, plot individual cell trajectories.

  • max_trajectories (int) – Maximum number of individual trajectories to plot (per cluster if clusters provided, or total if plotting all data). Ignored when trajectory_ids is set.

  • trajectories_sample_seed (int) – Seed for the random number generator used to sample trajectories. Defaults to 0.

  • trajectory_ids (List[int] | None) – Exact integer indices of cells to plot. Overrides max_trajectories and trajectories_sample_seed. Out-of-range indices are silently skipped.

  • trajectories_alpha (float) – Alpha transparency for individual time series lines. Defaults to 0.5.

  • trajectories_linewidth (float) – Linewidth for individual time series lines. Defaults to 0.5.

  • full_timeseries (bool) – If True, plot the full timeseries for each cell. If False, only plot the segment belonging to the cluster.

  • highlight_color (str | None) – Color to highlight the actual cluster segment when full_timeseries is True.

  • highlight_alpha (float) – Alpha for the cluster highlight segment.

  • highlight_linewidth (float) – Line width for the cluster highlight segment.

  • plot_shift_indicator (bool) – If True, overlay a dot on each trajectory at every timestep where that cell is assigned to the cluster (i.e. where the shift is detected). Only applies when clusters are provided.

  • shift_indicator_size (float) – Marker size (in points) for the shift detection dots. Defaults to 5.0.

  • plot_dts (bool) – If True, plot shifts variable in timeseries instead of base variable.

  • plot_median (bool) – If True, plot the median timeseries curve.

  • plot_mean (bool) – If True, plot the mean timeseries curve.

  • median_linewidth (float) – Linewidth for the median curve.

  • mean_linewidth (float) – Linewidth for the mean curve.

  • plot_trajectory_range (bool) – If True, plot the full range (min to max) as a shaded area.

  • plot_trajectory_std (bool) – If True, plot the 68% interquartile range (16th to 84th percentile) as a shaded area.

  • trajectory_range_alpha (float) – Alpha transparency for the full range shaded area.

  • trajectory_std_alpha (float) – Alpha transparency for the IQR shaded area.

  • plot_cluster_duration (bool) – If True, adds horizontal shading indicating the cluster’s temporal extent (start to end). Only applies when clusters are provided.

  • cluster_duration_color (str | None) – Color for shift duration shading. Uses cluster color if None.

  • cluster_duration_alpha (float) – Alpha for the shift duration shading.

  • plot_map (bool) – If True, include a map showing cluster spatial locations alongside timeseries. Defaults to False.

  • map_var (str | None) – Variable name whose data to plot in the map. Defaults to var if None. Only used if plot_map=True.

  • map_cmap_other (str | Colormap | None) – Colormap for remaining clusters on map. Only used if plot_map=True.

  • map_include_all_clusters (bool) – If True, plot all clusters on the map. If False, only plot selected clusters. Only used if plot_map=True.

  • subplots (bool) – If True, create one subplot per cluster. Defaults to False. If plot_map=True and multiple clusters, subplots are automatically enabled.

  • ncols (int) – Number of columns for subplot grid when subplots=True. Defaults to 1.

  • figsize (Tuple[float, float] | None) – Figure size (width, height) in inches. Used when subplots=True or plot_map=True.

  • wspace (float) – Width space between timeseries subplots (if ncols > 1).

  • hspace (float) – Height space between timeseries rows.

  • show_ylabels (bool) – If True, show y-axis label on the timeseries plots. Only relevant for subplots.

  • shared_ylabel (str | None) – If set, draw one rotated y-label beside the timeseries column instead of per-panel labels. Pass "auto" to use the first panel’s inferred label or variable metadata. Ignored when subplots=False.

  • shared_ylabel_pad (float) – Horizontal gap between the shared label and the leftmost subplot (figure fraction).

  • shared_ylabel_fontsize (float | None) – Font size for the shared label; defaults to axes.labelsize.

  • vertical (bool) – If True, arrange map above timeseries plots. Otherwise, map is placed to the left. Only used if plot_map=True.

  • width_ratios (Tuple[float, float]) – Tuple of relative widths for map vs. timeseries section (used in horizontal layout). Only used if plot_map=True.

  • height_ratios (Tuple[float, float] | None) – Optional tuple of relative heights for map vs. timeseries section (used in vertical layout). Only used if plot_map=True.

  • **plot_kwargs (Any) – Additional arguments passed to xarray.plot for each trajectory.

  • map_style (MapStyle | dict | None)

  • **plot_kwargs

Returns:

Tuple of (figure, axes). - If plot_map=False and single plot: (figure, Axes) - If plot_map=False and subplots=True: (figure, List[Axes]) - If plot_map=True: (figure, dict) with keys ‘map’ and ‘timeseries’ Figure is None if ax was provided and subplots=False and plot_map=False.

Raises:

ValueError – If no timeseries found for a given cluster ID, if nothing is set to plot, if cluster_ids is None when plot_map=True, or if plotting all data when plot_map=True.

Return type:

Tuple[FigureBase | None, Axes | List[Axes] | dict | None]