Plotting Utilities
Plotting helper functions for visualizing spike trains, firing rates, rasters,
and pairwise comparison matrices. Requires the plotting extra
(pip install spikelab[plotting]).
Plotting utilities for SpikeLab.
Provides plot_recording for assembling multi-panel figures from SpikeData
objects, plot_heatmap for standalone 2-D heatmaps, plot_distribution
for comparing per-unit metrics across conditions, plot_pvalue_matrix for
significance heatmaps (standalone or as inset), plot_scatter for pairwise
comparisons with optional regression, plot_lines for multi-trace line
plots, plot_burst_sensitivity for threshold sensitivity curves,
plot_scatter_with_marginals for scatter plots with marginal histograms,
plot_aligned_slice_single_unit for event-aligned single-unit raster plots,
and plot_spatial_network for MEA spatial network visualisation.
Requires matplotlib (optional dependency).
- spikelab.spikedata.plot_utils.plot_distribution(ax, metric_data, labels=None, colors=None, ylabel='', xlabel='', style='violin', show_median=True, show_quartiles=True, show_data=False, data_alpha=0.3, data_size=4, log_scale=False, font_size=None)[source]
Plot distributions of a per-unit metric across multiple groups/conditions.
- Parameters:
ax (matplotlib.axes.Axes) – Target axes (caller creates).
metric_data (dict[str, np.ndarray] or list[np.ndarray]) – Condition-labelled or ordered collection of per-unit value arrays. NaN values are stripped automatically before plotting.
labels (list[str] or None) – Ordered condition labels. If None, uses dict keys (for dict input) or integer indices (for list input).
colors (list[str] or None) – Per-condition colours. If None, uses the default matplotlib colour cycle.
ylabel (str) – Y-axis label.
xlabel (str) – X-axis label.
style (str) –
"violin"(default) or"boxplot".show_median (bool) – Overlay a median dot on each distribution.
show_quartiles (bool) – Overlay IQR lines (25th-75th percentile) on each distribution.
show_data (bool) – Overlay individual data points on each distribution, jittered horizontally to reduce overlap.
data_alpha (float) – Alpha transparency for overlaid data points.
data_size (float) – Marker size for overlaid data points.
log_scale (bool) – Use a log scale on the y-axis.
font_size (int or None) – Font size for labels and ticks. If None, uses current rcParams.
- Returns:
- The violin or boxplot artist dict returned by
matplotlib (
violinplotorboxplot).
- Return type:
parts (dict)
Notes
In violin mode, groups with fewer than 2 data points cannot produce a kernel density estimate. These groups are rendered as individual scatter points instead and excluded from the violin plot.
- spikelab.spikedata.plot_utils.plot_pvalue_matrix(pval_matrix, sig_matrix=None, labels=None, ax=None, parent_ax=None, inset_loc='upper left', inset_size='30%', inset_offset=0.08, cmap='viridis', sig_marker_color='red', sig_marker_size=2.5, show_colorbar=True, font_size=None)[source]
Display a pairwise p-value matrix as a
-log10(p)heatmap.Supports two rendering modes (mutually exclusive):
Standalone: pass
axto plot directly on existing axes.Inset: pass
parent_axto create a small inset axes on a parent plot (e.g. a violin or distribution plot).
Exactly one of
axorparent_axmust be provided.- Parameters:
pval_matrix (np.ndarray) – (K, K) p-value matrix. Diagonal entries should be NaN (they are rendered in black).
sig_matrix (np.ndarray or None) – (K, K) boolean – True where the comparison is significant. If None, computed as
pval_matrix < 0.05.labels (list[str] or None) – Tick labels for each group. If None, integer indices are used.
ax (matplotlib.axes.Axes or None) – Target axes for standalone mode.
parent_ax (matplotlib.axes.Axes or None) – Parent axes on which to create an inset.
inset_loc (str) – Location string for
inset_axes(e.g."upper left","lower left"). Only used in inset mode.inset_size (str) – Width and height of the inset as a percentage of the parent (e.g.
"30%"). Only used in inset mode.inset_offset (float) – Horizontal offset of the inset bounding box from the parent axes edge. Only used in inset mode.
cmap (str) – Matplotlib colormap name.
sig_marker_color (str) – Colour for significance markers.
sig_marker_size (float) – Marker size for significance dots.
show_colorbar (bool) – Show a
-log10(P)colorbar.font_size (int or None) – Font size for labels and ticks. If None, uses current rcParams.
- Returns:
- The axes the matrix was drawn on
(either
axor the newly created inset axes).
- Return type:
target_ax (matplotlib.axes.Axes)
- spikelab.spikedata.plot_utils.plot_scatter(ax, x, y, xlabel='', ylabel='', color_vals=None, color_label='', cmap='viridis', vmin=None, vmax=None, show_identity=False, show_colorbar=True, fit=None, show_ci=False, show_r2=False, marker_size=8, alpha=0.7, groups=None, group_labels=None, group_colors=None, show_legend=True, font_size=None)[source]
Scatter plot comparing two arrays with optional color coding and regression.
Supports two colouring modes (mutually exclusive):
Continuous: pass
color_valsfor a colormap-based colour scale with an optional colorbar.Discrete groups: pass
groups(integer index per point) to colour each group separately with its own legend entry.
When
groupsis provided,color_vals,cmap,vmin,vmax,color_label, andshow_colorbarare ignored.- Parameters:
ax (matplotlib.axes.Axes) – Target axes (caller creates).
x (np.ndarray) – X-axis values.
y (np.ndarray) – Y-axis values.
xlabel (str) – X-axis label.
ylabel (str) – Y-axis label.
color_vals (np.ndarray or str or None) – Per-point values for continuous color mapping. Pass the string
"density"to auto-compute KDE density and sort points so dense regions render on top (requires scipy). If None andgroupsis also None, all points are drawn in a uniform colour.color_label (str) – Colorbar label (continuous mode only).
cmap (str) – Matplotlib colormap name (continuous mode only).
vmin (float or None) – Colormap minimum (continuous mode only).
vmax (float or None) – Colormap maximum (continuous mode only).
show_identity (bool) – Plot the x = y identity line.
show_colorbar (bool) – Add a colorbar when color_vals is provided (continuous mode only).
fit (str or None) – Regression to overlay.
"linear"or None.show_ci (bool) – Show confidence interval band on the fit.
show_r2 (bool) – Annotate R-squared on the plot.
marker_size (float) – Scatter marker size.
alpha (float) – Scatter alpha.
groups (array-like or None) – Per-point integer group index for discrete colouring. Each unique value is rendered as a separate scatter series with its own colour and legend entry.
group_labels (list[str] or None) – Label for each unique group value, ordered by
np.unique(groups). If None, the group values are used as labels.group_colors (list[str] or None) – Colour for each unique group value, ordered by
np.unique(groups). If None, uses the default matplotlib colour cycle.show_legend (bool) – Show legend when
groupsis provided. Default True.font_size (int or None) – Font size for labels/ticks. If None, uses current rcParams.
- Returns:
- In continuous mode, the
single scatter artist (useful for shared colorbars). In group mode, a list of scatter artists (one per group).
- Return type:
sc (PathCollection or list[PathCollection])
Notes
When
color_vals="density", non-finite values in x and y are removed before computing the KDE. Any regression overlay (fit="linear") and the identity line are therefore computed on this filtered subset, not the original arrays.
- spikelab.spikedata.plot_utils.plot_scatter_with_marginals(gs_slot, fig, x, y, xlabel='', ylabel='', title=None, marginal_bins=60, marginal_color='0.4', show_zero_lines=False, height_ratios=None, width_ratios=None, **scatter_kwargs)[source]
Scatter plot with marginal histograms on the top and right edges.
Creates a 2x2 sub-GridSpec inside gs_slot (top-left: x histogram, bottom-left: scatter, bottom-right: y histogram, top-right: empty). All scatter options are forwarded to
plot_scatter().When a colorbar is shown (continuous
color_valswithshow_colorbar=True), it is placed to the right of the right marginal histogram rather than on the scatter axes.- Parameters:
gs_slot – A GridSpec slot (e.g.
gs[0]) to place the sub-layout in.fig (matplotlib.Figure) – Parent figure.
x (np.ndarray) – X-axis values.
y (np.ndarray) – Y-axis values.
xlabel (str) – X-axis label for the scatter.
ylabel (str) – Y-axis label for the scatter.
title (str or None) – Title placed above the top marginal histogram.
marginal_bins (int) – Number of histogram bins.
marginal_color (str) – Histogram bar colour.
show_zero_lines (bool) – Draw vertical/horizontal zero reference lines on the marginal histograms.
height_ratios (list or None) –
[hist, scatter]height ratios. Default[1, 4].width_ratios (list or None) –
[scatter, hist]width ratios. Default[4, 1].**scatter_kwargs – Additional keyword arguments forwarded to
plot_scatter()(e.g.color_vals,show_identity,marker_size,cmap).
- Returns:
The main scatter axes. ax_histx (matplotlib.axes.Axes): Top marginal histogram axes. ax_histy (matplotlib.axes.Axes): Right marginal histogram axes. sc: Return value from
plot_scatter().- Return type:
ax_scatter (matplotlib.axes.Axes)
- spikelab.spikedata.plot_utils.plot_manifold(ax, embedding, pc_x=0, pc_y=1, var_explained=None, bg_mask=None, bg_color='0.85', bg_alpha=0.05, bg_size=0.3, color_vals=None, color_label='', cmap='viridis', vmin=None, vmax=None, groups=None, group_labels=None, group_colors=None, marker_size=3, alpha=0.5, show_colorbar=True, show_legend=True, xlabel=None, ylabel=None, font_size=None)[source]
Plot a 2-D embedding (PCA, UMAP, etc.) with flexible point coloring.
Supports three foreground coloring modes (same as
plot_scatter()):Continuous: pass
color_valsfor colormap-scaled values.Discrete groups: pass
groupsfor per-group colours.Uniform: neither provided – all foreground points drawn in black.
An optional background mask renders selected points in a faint colour before the foreground, useful for separating non-event from event points (e.g. non-burst vs burst time bins).
- Parameters:
ax (matplotlib.axes.Axes) – Target axes (caller creates).
embedding (np.ndarray) – Shape
(T, >=2)embedding coordinates.pc_x (int) – Column index for the x-axis. Default 0.
pc_y (int) – Column index for the y-axis. Default 1.
var_explained (np.ndarray or None) – Explained variance ratio per component. When provided, axis labels are auto-generated as
"PC{n} (X.X%)"; overridden by explicitxlabel/ylabel.bg_mask (np.ndarray or None) – Boolean mask, shape
(T,). True for background points. These are drawn first inbg_color.bg_color (str) – Colour for background points.
bg_alpha (float) – Alpha for background points.
bg_size (float) – Marker size for background points.
color_vals (np.ndarray or str or None) – Per-point values for continuous colour mapping (foreground only). Pass
"density"for KDE-based density colouring.color_label (str) – Colorbar label (continuous mode).
cmap (str) – Matplotlib colourmap name (continuous mode).
vmin (float or None) – Colourmap minimum.
vmax (float or None) – Colourmap maximum.
groups (array-like or None) – Per-point integer group index for discrete colouring (foreground only).
group_labels (list[str] or None) – Labels per unique group value.
group_colors (list[str] or None) – Colours per unique group value.
marker_size (float) – Marker size for foreground points. Default 4.
alpha (float) – Alpha for foreground points.
show_colorbar (bool) – Add a colorbar (continuous mode only).
show_legend (bool) – Show a legend (group mode only).
xlabel (str or None) – X-axis label. Overrides auto-label from
var_explained.ylabel (str or None) – Y-axis label. Overrides auto-label from
var_explained.font_size (int or None) – Font size for labels and ticks. If None, uses current rcParams.
- Returns:
- The foreground scatter artist(s) – a single
PathCollection (continuous/uniform) or a
list[PathCollection](group mode). Useful for adding shared colorbars or custom legends.
- The foreground scatter artist(s) – a single
- Return type:
sc
- spikelab.spikedata.plot_utils.plot_lines(ax, traces, x=None, labels=None, colors=None, xlabel='', ylabel='', linewidth=1.5, show_legend=True, font_size=None)[source]
Plot one or more 1-D traces on a shared x-axis.
- Parameters:
ax (matplotlib.axes.Axes) – Target axes (caller creates).
traces (dict[str, np.ndarray] or list[np.ndarray]) – Line data. Dict keys are used as labels; for list input, supply
labelsseparately.x (np.ndarray or None) – Shared x-axis values. If None, integer indices (
0 … len-1) are used.labels (list[str] or None) – Per-trace labels. Required for list input; ignored for dict input (keys are used instead).
colors (list[str] or dict[str, str] or None) – Per-trace colours. For dict
traces, may be a dict keyed by the same labels or a list in the same order. If None, uses the default matplotlib colour cycle.xlabel (str) – X-axis label.
ylabel (str) – Y-axis label.
linewidth (float) – Line width for all traces.
show_legend (bool) – Show legend. Default True.
font_size (int or None) – Font size for labels and ticks. If None, uses current rcParams.
- Returns:
The line artists.
- Return type:
lines (list[Line2D])
- spikelab.spikedata.plot_utils.plot_percentile_bands(ax, metric_data, labels=None, normalize=False, summary='mean', bands=None, band_color='0.3', band_alphas=None, style='bands', line_color='0.5', line_alpha=0.3, line_width=0.5, summary_color='black', summary_linewidth=1.5, show_zero_line=True, xlabel='', ylabel='', ylim_range=None, show_legend=False, font_size=None)[source]
Plot percentile bands or individual lines across ordered groups/conditions.
For each unit a value is computed per condition. Optionally, values are normalized relative to the first group using symmetric normalization:
N = (x' - d0') / (x' + d0')wherex' = max(x, 0).- Parameters:
ax (matplotlib.axes.Axes) – Target axes (caller creates).
metric_data (dict[str, np.ndarray] or list[np.ndarray]) – Per-condition 1-D arrays of per-unit values. Dict keys or
labelsdefine the x-axis order.labels (list[str] or None) – Ordered condition labels. If None, uses dict keys (for dict input) or integer indices (for list input).
normalize (bool) – Apply symmetric normalization to the first group. Units with non-positive or NaN baseline values are excluded.
summary (str) – Summary line type:
"mean"(default) or"median".bands (list[tuple[int, int]] or None) – Percentile band definitions as
(lo, hi)pairs, ordered from widest to narrowest. Default is[(5, 95), (10, 90), (25, 75)].band_color (str) – Fill colour for all bands.
band_alphas (list[float] or None) – Alpha transparency per band. Must match length of
bands. Default is linearly increasing from 0.15 to 0.40.style (str) –
"bands"(default) draws shaded percentile regions;"lines"draws one line per unit.line_color (str) – Line colour when
style="lines".line_alpha (float) – Line alpha when
style="lines".line_width (float) – Line width when
style="lines".summary_color (str) – Colour for the summary line.
summary_linewidth (float) – Line width for the summary line.
show_zero_line (bool) – Draw a dashed horizontal line at y=0 when
normalize=True.xlabel (str) – X-axis label.
ylabel (str) – Y-axis label.
ylim_range (float or None) – Symmetric y-axis limits
(-val, val). If None andnormalize=True, derived from the 5th/95th percentile of the data.show_legend (bool) – Show legend.
font_size (int or None) – Font size for labels and ticks. If None, uses current rcParams.
- Returns:
- Keys
"summary"(Line2D), and either"bands" (list of PolyCollection) or
"lines"(list of Line2D).
- Keys
- Return type:
artists (dict)
- spikelab.spikedata.plot_utils.plot_burst_sensitivity(ax, thresholds, burst_counts, dist_values=None, labels=None, colors=None, xlabel='RMS mult.', ylabel='Number of bursts', show_legend=True, show_colorbar=True, cmap='hot', font_size=None)[source]
Plot burst detection sensitivity as line plots or heatmaps.
Automatically selects the visualisation based on the dimensionality of the burst count arrays:
1-D arrays (single-parameter sweep): one line per condition on a shared axes.
2-D arrays (two-parameter sweep over thresholds x distances, as returned by
SpikeData.burst_sensitivity()): one heatmap per condition viaplot_heatmap(). A single condition is plotted on ax; multiple conditions produce a row of subplots on a new figure.
- Parameters:
ax (matplotlib.axes.Axes or None) – Target axes. Used directly for 1-D line plots and single-condition 2-D heatmaps. For multi-condition 2-D heatmaps this parameter is ignored and a new figure is created (pass None explicitly in that case).
thresholds (np.ndarray) – 1-D array of threshold values (x-axis).
burst_counts (dict[str, np.ndarray] or np.ndarray) – Burst counts per condition. Dict mapping condition labels to arrays, or a bare
np.ndarrayfor a single unnamed condition. Arrays can be 1-D (line plot) or 2-D of shape(len(thresholds), len(dist_values))(heatmap).dist_values (np.ndarray or None) – 1-D array of distance parameter values. Required when burst counts are 2-D (used as y-axis tick labels on the heatmap). Ignored for 1-D line plots.
labels (list[str] or None) – Ordered condition labels. If None, uses dict keys.
colors (list[str] or None) – Per-condition line colours (line plots only). If None, uses the default matplotlib colour cycle.
xlabel (str) – X-axis label.
ylabel (str) – Y-axis label. For 2-D heatmaps, defaults to
"Min. burst dist. (bins)"when not explicitly changed from the default.show_legend (bool) – Whether to show a legend (line plots only).
show_colorbar (bool) – Whether to show a colorbar (heatmaps only).
cmap (str) – Colormap for heatmaps.
font_size (int or None) – Font size for labels/ticks. If None, uses current rcParams.
- Returns:
- For 1-D line plots:
list[Line2D]artists. For a single 2-D heatmap: the axes returned by
plot_heatmap(). For multiple 2-D heatmaps:(fig, axes_list)where axes_list contains one axes per condition.
- For 1-D line plots:
- Return type:
result
- spikelab.spikedata.plot_utils.plot_aligned_slice_single_unit(ax, spike_times_per_slice, color_vals=None, color_label='', cmap='viridis', time_offset=0, xlabel='Rel. time (ms)', ylabel='Burst', x_range=None, vlines=None, show_colorbar=True, marker_size=20, font_size=None, style='scatter', invert_y=False, linewidths=0.5)[source]
Raster plot of one unit’s spike times across multiple event-aligned slices.
Each row corresponds to one slice/burst, x-axis is time relative to the alignment point. Optionally colour-codes rows by a per-slice variable.
- Parameters:
ax (matplotlib.axes.Axes) – Target axes (caller creates).
spike_times_per_slice (list[np.ndarray]) – List of 1-D arrays, one per slice, containing spike times relative to the alignment point.
color_vals (np.ndarray or None) – Per-slice colour values. If None, all spikes are drawn in black.
color_label (str) – Colorbar label.
cmap (str) – Matplotlib colormap name.
time_offset (float) – Value subtracted from every spike time before plotting. Slices from
align_to_eventsare already event-centered (spike times in[-pre_ms, +post_ms]), so use the defaulttime_offset=0. Only set a non-zero value when spike times are not already centered on the event.xlabel (str) – X-axis label.
ylabel (str) – Y-axis label.
x_range (tuple or None) –
(xmin, xmax)for the x-axis. If None, auto-scales to the data.vlines (list[dict] or None) – Vertical reference lines. Each dict must contain
'x'(required) and may optionally include'color'(default'red'),'linestyle'(default'--'), and'linewidth'(default1.5).show_colorbar (bool) – Add a colorbar when color_vals is provided.
marker_size (float) – Scatter marker size (only used when
style="scatter").font_size (int or None) – Font size for labels/ticks. If None, uses current rcParams.
style (str) –
"scatter"for dot markers (default), or"eventplot"for vertical line markers.invert_y (bool) – If True, the first slice is plotted at the top and the last at the bottom. Default False (first slice at bottom).
linewidths (float) – Line width for eventplot markers (only used when
style="eventplot"). Default 0.5.
- Returns:
- The scatter artist when color_vals is
provided and
style="scatter", otherwise None.
- Return type:
sc (PathCollection or None)
- spikelab.spikedata.plot_utils.plot_heatmap(data_mat, ax=None, norm=False, vmin=None, vmax=None, cmap='hot', aspect='auto', origin='upper', extent=None, xlabel='Time (ms)', ylabel='Unit', xticks=None, yticks=None, vlines=None, hlines=None, show_colorbar=True, colorbar_label='Rate (Hz)', font_size=14, save_path=None)[source]
Plot a 2-D matrix as a heatmap.
- Parameters:
data_mat (np.ndarray) – 2-D array to display, shape
(rows, cols).ax (matplotlib.axes.Axes or None) – Target axes. If None a standalone figure is created.
norm (bool or str) – Row normalisation.
Falsefor none,'row'to scale each row to [0, 1].vmin (float or None) – Colormap minimum.
vmax (float or None) – Colormap maximum.
cmap (str) – Matplotlib colormap name.
aspect (str) – Aspect ratio passed to
imshow."auto"stretches to fill the axes,"equal"preserves square pixels.origin (str) – Origin for
imshow."upper"places row 0 at the top (default),"lower"places row 0 at the bottom.extent (tuple or None) –
(left, right, bottom, top)passed toimshow. If None, pixel indices are used.xlabel (str) – X-axis label.
ylabel (str) – Y-axis label.
xticks (tuple or None) –
(locations, labels)for x-axis ticks.yticks (tuple or None) –
(locations, labels)for y-axis ticks.vlines (list[dict] or None) – Vertical lines. Each dict may contain
'x','color','linestyle','linewidth'.hlines (list[dict] or None) – Horizontal lines (same keys as vlines but with
'y').show_colorbar (bool) – Whether to draw a colorbar.
colorbar_label (str) – Label for the colorbar.
font_size (int) – Font size for labels and ticks.
save_path (str or None) – If provided (and
axis None), save the figure to this path and close it.
- Returns:
(fig, ax)whenaxis None, otherwise justax.- Return type:
result
- spikelab.spikedata.plot_utils.plot_recording(sd, show_raster=True, show_pop_rate=False, show_fr_rates=False, show_model_states=False, pop_rate=None, pop_rate_params=None, fr_rates=None, fr_rate_sigma_ms=10.0, model_states=None, cont_prob=None, gplvm_result=None, time_range=None, sort_indices=None, raster_style='eventplot', raster_bin_size_ms=1.0, raster_vmax=5, burst_times=None, burst_edges=None, burst_colors=None, vmin_heatmap=None, vmax_heatmap=None, heatmap_clip_pct=80, norm_heatmap=False, model_states_cmap='viridis', model_states_vmin=0, model_states_vmax=1, axes=None, figsize=None, height_ratios=None, absolute_xticks=True, font_size=14, show=True, save_path=None)[source]
Assemble a multi-panel column figure from a SpikeData object.
Each panel is optional – the caller selects which panels to include and they are stacked vertically with a shared x-axis. Available panels (in display order):
Spike raster – eventplot or binned-count image.
Population rate – smoothed firing rate curve; if
cont_probis also provided it is overlaid on the same axes.Firing-rate heatmap – per-unit instantaneous rates as a colour map.
Model states – latent-state posterior from a GPLVM fit.
- Parameters:
sd (SpikeData) – Source spike data object.
show_raster (bool) – Include the spike raster panel.
show_pop_rate (bool) – Include the population-rate panel. Automatically enabled when
pop_rateorcont_probis provided.show_fr_rates (bool) – Include the firing-rate heatmap. Automatically enabled when
fr_ratesis provided.show_model_states (bool) – Include the model-states panel. Automatically enabled when
model_statesis provided.pop_rate (np.ndarray or None) – Pre-computed smoothed population rate in spikes per bin (as returned by
sd.get_pop_rate()), shape(T,). Automatically converted to Hz/unit for display. If None and panel is enabled, computed viasd.get_pop_rate().pop_rate_params (dict or None) – Keyword arguments forwarded to
sd.get_pop_rate()whenpop_rateis None. Defaults:square_width=8, gauss_sigma=8.fr_rates (np.ndarray or None) – Pre-computed per-unit instantaneous firing rates, shape
(U, T). If None andshow_fr_ratesis True, computed viasd.resampled_isi().fr_rate_sigma_ms (float) – Gaussian sigma in ms for
sd.resampled_isi()when auto-computing firing rates.model_states (np.ndarray or None) – Latent-state posterior, shape
(S, T)where S is the number of latent states. If None andshow_model_statesis True, extracted fromgplvm_result.cont_prob (np.ndarray or None) – Continuous-dynamics probability, shape
(T,). Overlaid on the population-rate panel. If None andgplvm_resultis provided, extracted automatically.gplvm_result (dict or None) – Result dictionary from
SpikeData.fit_gplvm(). Used to auto-extractmodel_statesandcont_probwhen those are not provided directly.time_range (tuple or None) –
(start_ms, end_ms)display window. None shows the full recording.sort_indices (np.ndarray or None) – Unit reordering indices applied to the raster and firing-rate heatmap.
raster_style (str) –
'eventplot'(default) or'imshow'. Controls how the raster panel is rendered. Both styles display unit 0 at the top, but achieve this differently:'imshow'usesorigin='upper'while'eventplot'inverts the y-axis. As a result, y-coordinates are reversed in eventplot mode (ylim goes from N to 0). Keep this in mind when overlaying custom artists.raster_bin_size_ms (float) – Bin size in ms for the raster (used for both eventplot and imshow styles). When
absolute_xticks=True, tick values are computed asbin_index * raster_bin_size_ms + offset, which is exact only whenraster_bin_size_ms=1.0.raster_vmax (int) – Maximum spike count for colormap when
raster_style='imshow'. Default is 5.burst_times (np.ndarray or None) – Burst peak positions as raster bin indices (as returned by
get_bursts), plotted as markers on the population-rate panel. With the defaultraster_bin_size_ms=1.0, bin indices equal milliseconds.burst_edges (np.ndarray or None) – Per-burst
[start_bin, end_bin]boundaries as raster bin indices, shape(B, 2). Plotted as shaded spans on the population-rate panel.burst_colors (array-like or None) – Per-burst color values, one per burst (length B, matching
burst_times/burst_edges). When provided, each burst span and peak marker is drawn in its assigned color. When None, spans default to blue and peaks to black.vmin_heatmap (float or None) – Colormap minimum for the FR heatmap.
vmax_heatmap (float or None) – Colormap maximum for the FR heatmap. When None, clipped to
heatmap_clip_pctpercentile of the data.heatmap_clip_pct (float or None) – Fraction of the data maximum (as a percentage) used as the colormap maximum when
vmax_heatmapis None. Default 80 (i.e. 80% of the max value). Set to None to use the absolute maximum.norm_heatmap (bool or str) – Row normalisation for the FR heatmap (
Falseor'row').model_states_cmap (str) – Colormap for the model-states panel.
model_states_vmin (float) – Colormap minimum for model states.
model_states_vmax (float) – Colormap maximum for model states.
axes (list or None) – Pre-created axes to plot onto instead of creating a new figure. Must be a list of
(ax_panel, ax_cbar)tuples, one per enabled panel, in display order (raster, pop_rate, fr_heatmap, model_states – only those that are enabled).ax_cbaris used for colorbars on heatmap/imshow panels; pass a hidden axes if no colorbar is needed for that panel. When provided, the function skips figure creation,tight_layout,show, andsave_path.figsizeandheight_ratiosare ignored. RaisesValueErrorif the length does not match the number of enabled panels.figsize (tuple or None) – Figure size
(width, height). Ignored whenaxesis provided.height_ratios (list or None) – Relative panel heights. Length must match the number of enabled panels.
absolute_xticks (bool) – If True, x-tick labels show absolute seconds from recording start. If False, labels are relative to the display window.
font_size (int) – Font size for labels and tick labels.
show (bool) – If True and
save_pathis None, callplt.show().save_path (str or None) – Save figure to this path and close it.
- Returns:
The assembled figure.
- Return type:
fig (matplotlib.Figure)
Notes
At least one panel must be enabled, otherwise
ValueErroris raised.When
gplvm_resultis provided,model_statesandcont_probare extracted from thedecode_ressub-dict (keysposterior_latent_margandposterior_dynamics_marg). Arrays with a different time resolution (e.g. GPLVM binned output) are automatically cropped to match the ms-basedtime_range.
- spikelab.spikedata.plot_utils.plot_spatial_network(ax, positions, matrix, edge_threshold=None, top_pct=None, node_size_range=(2, 20), node_cmap='viridis', node_linewidth=0.2, edge_color='red', edge_linewidth=0.6, edge_alpha_range=(0.15, 1.0), scale_bar_um=500, font_size=None)[source]
Plot a spatial network of units on their MEA positions.
Units are drawn as scatter markers sized by their mean pairwise value (row mean excluding diagonal) and coloured by the same metric. Edges are drawn between unit pairs whose matrix value exceeds a threshold or falls in the top percentile, with alpha proportional to edge strength.
Exactly one of edge_threshold or top_pct must be provided.
- Parameters:
ax (matplotlib.axes.Axes) – Target axes.
positions (np.ndarray) – Unit positions, shape
(N, 2)with columns[x, y]in micrometres.matrix (np.ndarray) – Symmetric
(N, N)pairwise matrix (e.g. correlation, STTC). Diagonal values are ignored.edge_threshold (float or None) – Minimum matrix value to draw an edge.
top_pct (float or None) – Percentage of top edges to draw (e.g.
1.0draws the top 1 %).node_size_range (tuple) –
(min_size, max_size)in points squared for the scatter markers.node_cmap (str) – Matplotlib colourmap for node colour.
node_linewidth (float) – Outline width of node markers.
edge_color (str) – Colour for network edges.
edge_linewidth (float) – Line width for network edges.
edge_alpha_range (tuple) –
(min_alpha, max_alpha)for edge transparency, scaled by edge strength.scale_bar_um (float) – Length of the spatial scale bar in micrometres. Set to 0 or None to omit.
font_size (int or None) – Font size for scale bar label. If None, uses the current rcParams default.
- Returns:
- The scatter artist,
useful for adding a colorbar.
- Return type:
scatter (matplotlib.collections.PathCollection)