Skip to content

Plots / display / figure saving: cicada_tools.display

from cicada_analysis.cicada_tools.display.<module> import <function>


display.core_plots (Core plots display functions)

Constant BREWER_COLORS: list of 23 hex colours, the ColorBrewer Paired palette (12) then RdYlBu (11).

  • save_figure

save_figure(figure, results_path, figname, save_formats=('pdf', 'png'), dpi=300, tight_layout=True, close=True, bbox_inches=None) -> None

Save a matplotlib figure to disk in one or more formats, then optionally close it (only this figure). Sets PDF/PS/SVG font embedding for Illustrator compatibility. The file name is made safe for every OS (safe_file_name) and shortened to fit the Windows path limit. Every figure of CICADA is saved through it.

With interactive figures on (set_interactive_figures(True), done by CicadaAnalysis.run_analysis from the interactive_figures parameter, for the run's thread only), also writes <figname>.mplfig, the figure pickled, which the GUI's Interactive viewing tab opens with zoom and pan. A figure that cannot be pickled is reported and skipped.

Parameter Type Default Description
figure matplotlib Figure Figure (or seaborn grid)
results_path str Output directory (created if absent)
figname str Base filename without extension
save_formats tuple ('pdf', 'png') Save formats e.g. ('pdf', 'png', 'svg')
dpi int 300 Resolution, or 'figure' for the figure's own
tight_layout bool True Apply tight layout
close bool True Close figure after saving
bbox_inches any None Bounding box

Returns: None

During a run with a figure style (FigureStyle.applied), every figure is first finished with finish_figure (a tight layout is applied only to a figure without its own layout engine, e.g. not to a constrained one).

  • finish_figure

finish_figure(figure, max_ticks=None, show_titles=True, rasterize_dense=False) -> None

What a figure style sets that matplotlib settings cannot, applied by save_figure during a run (set_figure_finish / reset_figure_finish, for the run's thread only): at most max_ticks ticks on the axes with automatic ticks (ticks chosen by the plot, log axes and categories kept), the titles removed when show_titles is False, and with rasterize_dense the images and meshes rasterized, and the lines and collections of a panel when they have more than DENSE_POINTS (1000) points together (e.g. a raster drawn one row at a time).

  • add_colorbar

add_colorbar(fig, mappable, ax, label="", width_mm=3.0, text_size=None, color=None) -> Colorbar

Colour bar of mappable right of ax (an Axes, or several: one bar for them), about width_mm wide, its label and ticks of size text_size and colour color (None: the matplotlib settings).

  • style_axes

style_axes(ax, v_line=False, xlim=None, ylim=None, xlabel=None, ylabel=None, despine=False, **style) -> None

Set the limits and labels given (None leaves them as they are), remove the top and right borders if despine, then apply the style keys given (FIGURE_STYLE: background of the axes and figure, tick and label sizes and colours, borders) to one axes, leaving the others as they are; v_line adds a dashed line at 0.

Parameter Type Default Description
ax Axes Axes to style
v_line bool False Add vertical line at 0
xlim tuple None X-axis limits
ylim tuple None Y-axis limits
xlabel str None X-axis label
ylabel str None Y-axis label
despine bool False Remove top and right borders
**style dict Additional style keys

Returns: None

  • split_into_separate_figures

split_into_separate_figures(data, columns, file_name) -> list

Returns (rows, file name) per figure: one figure per combination of the values of columns.

Parameter Type Description
data any Data to split
columns list Columns to split by
file_name str Base file name

Returns: list — List of (rows, file_name) tuples

  • create_and_configure_plot

create_and_configure_plot(n_lines, n_cols, size_fig, background_color) -> tuple

Create a uniform matplotlib figure grid with tight layout and a solid background.

Parameter Type Description
n_lines int Number of lines (rows)
n_cols int Number of columns
size_fig tuple Figure size
background_color str Background color

Returns: tuple — Configured figure and axes

  • get_colormap

get_colormap(cmap='hotcold') -> matplotlib.colors.Colormap

Return a named colormap, NaN values drawn in transparent black. Besides the matplotlib names: 'hotcold' (default), diverging cyan–blue–violet → dark grey → red–orange–yellow, for data centred at zero; 'cyanmagenta', diverging cyan–white–magenta; 'whitemagenta', white → magenta; 'grays', matplotlib Greys.

Parameter Type Default Description
cmap str 'hotcold' Colormap name

Returns: matplotlib.colors.Colormap — Requested colormap

  • is_light_color

is_light_color(color) -> bool

Return True if color is perceptually light (brightness > 0.5)

Parameter Type Description
color any Color to check

Returns: bool — True if light color

  • add_scale_bar

add_scale_bar(ax, length, label, color, fontproperties=None, axis='x', shown=None, loc=2, anchor=(0., 1.), label_top=True, zorder=None) -> AnchoredSizeBar | None

Scale bar of length data units along axis ('x': time, 'y': signal), with a thickness that is a fixed fraction of the axes (whatever the number of cells or the window). Not drawn, with a message, when longer than shown (the time window or signal range shown). Used by the trace (imaging_plots) and spike (ephys_plots) rasters.

Parameter Type Default Description
ax Axes Axes to add scale bar to
length float Length in data units
label str Scale bar label
color str Scale bar color
fontproperties FontProperties None Font properties
axis str 'x' Axis ('x' or 'y')
shown float None Don't draw if longer than this
loc int 2 Location code
anchor tuple (0., 1.) Anchor point
label_top bool True Label on top
zorder int None Z-order

Returns: AnchoredSizeBar | None — Scale bar or None

  • bands_legend_handles

bands_legend_handles(intervals, colors, labels, alpha=0.5) -> list

Legend entries of the bands (see add_bands_legend): a line for a group whose intervals all have start = stop (events without duration), a patch for bands; groups without interval left out.

Parameter Type Default Description
intervals list Per group, [(start, stop)]
colors list Per group, its colour as an RGB(A) sequence (only the first 3 values are used)
labels list Per group, its name
alpha float 0.5 Opacity of the entries

Returns: list — matplotlib Line2D / Patch handles

  • add_bands_legend

add_bands_legend(ax, intervals, colors, labels, alpha=0.5, font_size=8, outside_top=None, text_color="black") -> None

Legend of the bands drawn over a display (CicadaEventsBase.overlay_bands): one entry per group with intervals, a line for events without duration, a patch for bands (bands_legend_handles). Nothing is drawn when no group has an interval.

Parameter Type Default Description
ax Axes Axes (or figure) the legend is drawn on
intervals list Per group, [(start, stop)]
colors list Per group, its color
labels list Per group, its name
alpha float 0.5 Opacity of the entries (as the bands)
font_size int 8 Size of the legend
outside_top float None None: inside, upper right; else right of the axes, its top at this height (axes fraction)
text_color str "black" Color of the entries' names when outside (no frame then)

Returns: None


display.figure_style (One figure style for every plugin)

Sizes in mm, fonts and lines in pt. Constants: PRESETS (default: a journal column, 89 mm, 7 pt text; presentation: the same width, larger text, lines and ticks), CUSTOM ('custom': values typed), OKABE_ITO (the colours of the categories and the default colours of new groups in the GUI), THEMES (light, dark; custom: background_color / foreground_color), COLORMAPS, DIVERGING_COLORMAPS, FIGURE_ELEMENTS / STANDARD_ELEMENTS (what a plugin's figures may have; CicadaAnalysis.add_figure_style_args_for_gui offers the options of those it draws).

  • FigureStyle

FigureStyle(preset="default", columns=1, width_mm=89.0, panel_aspect=1.0, dpi=300, ...) -> FigureStyle
FigureStyle.from_values(values) -> FigureStyle
style.figure_size(n_rows=1, n_cols=1, panel_aspect=None) -> (width, height)   # inches
style.rc() -> dict
style.applied()   # context manager
style.psth_values(n_rows=1, n_cols=1, panel_aspect=None) -> dict

Frozen dataclass of the style values (CicadaAnalysis.figure_style(**kwargs) builds it from a plugin's parameters). from_values: from parameter values, a preset other than custom setting its sizes, fonts, lines and ticks over them. figure_size: a figure of n_rows x n_cols panels at the style's width, panels of panel_aspect (height / width) separated by panel_spacing_mm. rc: the matplotlib settings. applied: the style during a run (AnalysisArgumentsHandler.run_analysis): its matplotlib settings, the xkcd sketch mode, and finish_figure on every saved figure; all put back afterwards. psth_values: the keyword arguments of the PSTH plots (core_plots.FIGURE_STYLE keys, figure size, dpi, formats). Properties background, foreground (from the theme) and reference_color (the reference line colour, else the text colour).


display.distribution_plots (Distribution plots utils)

  • plot_box_plots

plot_box_plots(data_dict, title, filename, y_label, ...) -> None

Box/strip plot wrapper. See function signature for display kwargs.

Parameter Type Description
data_dict dict Data dictionary
title str Plot title
filename str Output filename
y_label str Y-axis label

Returns: None

  • plot_hist_distribution

plot_hist_distribution(distribution_data, ...) -> None

Plot a 1D numeric distribution as a histogram, with optional scatter markers overlaid above bins.

Parameter Type Description
distribution_data any Distribution data

Returns: None

  • categorical_plot

categorical_plot(kind, ax, **kwargs) -> Axes

Seaborn categorical plot ('strip', 'swarm', 'violin', 'box', 'bar', 'boxen') of a long table on an existing axes (data=, x=, y=, hue=, palette=...); unlike sns.catplot, it draws on ax. Strip jitter and bar bootstrap use a fixed seed (CATEGORICAL_PLOT_SEED), numpy's global random state put back: same figure at every run.

Parameter Type Description
kind str Plot kind
ax Axes Target axes
**kwargs dict Additional arguments

Returns: Axes — Seaborn categorical plot axes

  • plot_groups

plot_groups(table, value, y_label, path, file_name, x=None, hue=None, separate=(), levels=(), palette=None, ...) -> None

Categorical plots of one value per observation (e.g. cell) by groups (table columns): x on the x axis, hue in colour, one figure per combination of the separate columns; all the rows, then one figure per value of each levels column (e.g. 'session', 'mouse'). Titles name the groups of each figure; palette ({group: colour}) colours the hue groups, else the x groups; style takes style_axes keys; do_stats compares the x groups within each hue group (stats.compare_groups). Used by CicadaGroupsBase.plot_group_distributions.

Parameter Type Default Description
table pd.DataFrame Data table
value str Value column
y_label str Y-axis label
path str Output path
file_name str Output filename
x str None X-axis column
hue str None Hue column
separate tuple () Separate columns
levels tuple () Level columns
palette dict None Color palette

Returns: None


display.raster_plots (Raster plots util)

  • plot_raster

plot_raster(spike_nums=None, ...) -> None

Plot a binary raster (cells × frames). See function signature for display kwargs. This function has >90 parameters.

Returns: None


display.graph_plots (Graph visualization util)

  • plot_graph

plot_graph(graph, ...) -> None

Plot a NetworkX graph. Supports ForceAtlas2 layout, custom node/edge colors, and figure saving.

Parameter Type Description
graph networkx.Graph Graph to plot
with_fa2 bool Use ForceAtlas2 layout

Returns: None

  • plot_connectivity_graphs

plot_connectivity_graphs(session_id_list, ...) -> None

Plot a collection of connectivity graphs, one per key in graphs_dict.

Parameter Type Description
session_id_list list Session IDs

Returns: None

  • build_jittered_scatter_positions

build_jittered_scatter_positions(xs, ys, jitter=150, seed=0) -> dict

Node positions for a graph layout from (xs[i], ys[i]), every point jittered by a random offset in [-jitter, jitter] on x and y; points on the same coordinate (rounded to 3 decimals) are also spread along x, jitter apart, so co-located nodes stay distinguishable.

Parameter Type Default Description
xs np.ndarray x of each node
ys np.ndarray y of each node
jitter float 150 Jitter, in the units of the coordinates
seed int 0 Seed of the jitter (the same layout at every run)

Returns: dict — {node index: (x, y)}

  • build_probe_depth_positions

build_probe_depth_positions(depths, probe_names, col_height=2.0, seed=0) -> dict

Schematic node layout when no real coordinates are available: one column per probe (sorted by name), the columns placed evenly on a circle (radius max(1.5, 0.6 × n_probes), the first at the top; a single probe at the origin), each node down its probe's column by its depth, min-max normalised over all nodes. Jitter on x only: ±0.2, plus a 0.1 spread for nodes at the same depth.

Parameter Type Default Description
depths list Depth of each node
probe_names list Probe of each node
col_height float 2.0 Length of a column (normalised depth 1)
seed int 0 Seed of the jitter (the same layout at every run)

Returns: dict — {node index: (x, y)}


display.connectivity_plots (Connectivity figures)

Figures of the connectivity analyses: peri-SCE triggered averages ("Christmas tree"), spike-triggered population rate (stPR), cross-correlograms of detected pairs, and pairwise similarity. The computations are in cicada_tools.connectivity. Not re-exported by cicada_tools.display: import from the module (cicada_analysis.cicada_tools.display.connectivity_plots).

  • plot_christmas_tree_heatmap

plot_christmas_tree_heatmap(mean_psth, time_axis_s, time_lags_dict, cells_list, data_id, path_results, save_formats="pdf") -> None

Heatmap of peri-SCE triggered averages, rows sorted/normalized by each unit's preferred time lag.

Parameter Type Default Description
mean_psth np.ndarray Mean PSTH
time_axis_s np.ndarray Time axis in seconds
time_lags_dict dict Time lags dictionary
cells_list list Cell list
data_id str Data identifier
path_results str Results path
save_formats str "pdf" Save formats

Returns: None

  • plot_christmas_tree_crosscorr

plot_christmas_tree_crosscorr(mean_psth, time_axis_s, time_lags_dict, cells_list, data_id, path_results, cells_groups=None, groups_colors=None, ...) -> None

Per-cell (or per-group mean ± SEM) peri-SCE cross-correlogram traces around SCE onset.

Parameter Type Default Description
mean_psth np.ndarray Mean PSTH
time_axis_s np.ndarray Time axis in seconds
time_lags_dict dict Time lags dictionary
cells_list list Cell list
data_id str Data identifier
path_results str Results path
cells_groups list None Cell groups
groups_colors dict None Group colors

Returns: None

  • plot_stpr_scatter

plot_stpr_scatter(coupling, delay_s, valid, data_id, path_results, cells_groups=None, groups_colors=None, ...) -> None

Scatter of coupling strength vs. delay (stPR analogue of the "Christmas tree" plot).

Parameter Type Default Description
coupling np.ndarray Coupling values
delay_s np.ndarray Delay values in seconds
valid np.ndarray Validity flags
data_id str Data identifier
path_results str Results path
cells_groups list None Cell groups
groups_colors dict None Group colors

Returns: None

  • plot_stpr_heatmap

plot_stpr_heatmap(time_axis_s, stpr, delay_s, valid, coupling, data_id, path_results, ...) -> None

Z-scored heatmap of stPR curves sorted by delay.

Parameter Type Description
time_axis_s np.ndarray Time axis in seconds
stpr np.ndarray stPR matrix
delay_s np.ndarray Delay values
valid np.ndarray Validity flags
coupling np.ndarray Coupling values
data_id str Data identifier
path_results str Results path

Returns: None

  • plot_stpr_heatmap_grid

plot_stpr_heatmap_grid(entries, data_id, path_results, max_cols=4, ...) -> None

Grid of plot_stpr_heatmap-style panels (one per group/cross-area pair) sharing a single colorbar. entries: list of (label, stpr, time_axis_s, delay_s, valid) tuples.

Parameter Type Default Description
entries list List of tuples
data_id str Data identifier
path_results str Results path
max_cols int 4 Maximum columns

Returns: None

  • plot_pair_ccg

plot_pair_ccg(ia, ib, spike_times_list, bin_size_ms=0.4, max_lag_ms=100.0, hollow_ms=10.0, sigma_ms=20.0, syn_window=(1.0, 4.0), node_label="unit", show_significance=True) -> matplotlib.figure.Figure

Cross-correlogram plot for one unit/cell pair, shared between the ephys (Buzsáki-style) and imaging (Bonifazi-style) detection methods; use show_significance=False for imaging.

Parameter Type Default Description
ia int First unit index
ib int Second unit index
spike_times_list list Spike times per unit
bin_size_ms float 0.4 Bin size in ms
max_lag_ms float 100.0 Maximum lag in ms
hollow_ms float 10.0 Hollow window in ms
sigma_ms float 20.0 Sigma in ms
syn_window tuple (1.0, 4.0) Synaptic window in ms
node_label str "unit" Node label
show_significance bool True Show significance

Returns: matplotlib.figure.Figure — CCG figure

  • plot_similarity_matrix

plot_similarity_matrix(data, filename=None, ..., vmin=0, vmax=1, sep_lines=None, sep_labels=None, ax=None) -> matplotlib.figure.Figure | None

Seaborn heatmap of a similarity matrix (or a dict of {name: matrix} for a multi-panel grid); supports block separator lines/labels and drawing onto an existing ax.

Parameter Type Default Description
data np.ndarray or dict Similarity matrix or dict of matrices
filename str None Output filename
vmin float 0 Minimum value for colormap
vmax float 1 Maximum value for colormap
sep_lines list None Separator line positions
sep_labels list None Separator labels
ax Axes None Existing axes

Returns: matplotlib.figure.Figure | None — Figure or None

  • plot_similarity_vs_distance

plot_similarity_vs_distance(distances, similarities, path, filename, y_label, style='Scatter plot', bin_size=30, color=(0.3, 0.3, 0.3, 1.), marker_size=None, figsize=(10, 8), dpi=100, save_formats='pdf') -> None

Similarity of each pair of cells against the distance between them: one point per pair ('Scatter plot'), or, for any other style ('Bar plot'), the mean (bar) and SD (error bar) of the pairs in each distance bin [k × bin_size, (k + 1) × bin_size), NaN ignored, the y label then "Mean <y_label>". The x label is "Distance (µm)". Text, axes and background follow the matplotlib settings. Saved in path as filename.<format>.

Parameter Type Default Description
distances array-like Distance of each pair
similarities array-like Similarity of each pair
path str Folder of the figure
filename str File name without extension
y_label str Y label
style str 'Scatter plot' 'Scatter plot' or 'Bar plot'
bin_size float 30 Width of the distance bins (bar plot)
color tuple (0.3, 0.3, 0.3, 1.) Colour of the points or bars
marker_size float None Size of the points (pt); None: the matplotlib settings
figsize tuple (10, 8) Figure size (inches)
dpi int 100 Resolution
save_formats str | list 'pdf' Format(s) of the figure

Returns: None — the figure is saved


display.psth_plots (PSTH plotting)

  • plot_psth_lines

plot_psth_lines(summary, x='time', row=None, col=None, hue=None, style=None, palette=None, ...) -> None

PSTH lines and bands from a stats.line_and_band table, in panels sharing a width_fig x height_fig figure (share_y: y shared within a row, or not): one line per hue level (colour) and style level (line style), legend outside. Shared by the PSTH plugins.

Parameter Type Default Description
summary any Line and band table
x str 'time' X-axis column
row str None Row column
col str None Column column
hue str None Hue column
style str None Style column
palette dict None Color palette

Returns: None

  • plot_raster_and_psth

plot_raster_and_psth(rasters, summary, ...) -> None

One unit's raster (one row per event) above its PSTH lines and bands.

Parameter Type Description
rasters any Raster data
summary any Summary data

Returns: None

  • common_y_limits

common_y_limits(tables) -> tuple

(bottom, top) covering the line and band of every table, for figures sharing one y scale: 0 at the bottom unless values are negative (then 10% of the range below the lowest); a positive top raised by 20%, else 10% of the range above it. When that gives no range (all values 0, or all the same negative value): (bottom, bottom + 1).

Parameter Type Description
tables list[pd.DataFrame] line_and_band tables (line, low, high)

Returns: tuple — (bottom, top) floats

  • line_table

line_table(time, line, low=None, high=None, **columns) -> pd.DataFrame

One line (and its band) as a line_and_band table, for plot_psth_lines / plot_raster_and_psth.

Parameter Type Default Description
time np.ndarray Time of each point
line np.ndarray Value of each point
low np.ndarray None Lower band edge; None: no band (NaN)
high np.ndarray None Upper band edge; None: no band (NaN)
**columns Constant columns, e.g. source="data" for the hue

Returns: pd.DataFrame — time, line, low, high and the given columns

  • plot_trials_superimposed

plot_trials_superimposed(time, trials, colormap='Purples', x_label='Time (s)', y_label='', title='', width_fig=15, height_fig=8, dpi=300, xkcd_mode=False, save_path=None, save_formats='pdf', file_name='trials', **figure_style) -> None

One line per trial (e.g. a cell's trace around each event), coloured along colormap from 0.55 to its end so that no trial is drawn in the colormap's near-white start.

Parameter Type Default Description
time np.ndarray Time of each point, relative to the event
trials np.ndarray (n_trials, n_points)
colormap str 'Purples' Colormap name
x_label str 'Time (s)' X label
y_label str '' Y label
title str '' Figure title, shown when the style's show_titles is on
width_fig float 15 Figure width (inches)
height_fig float 8 Figure height (inches)
dpi int 300 Resolution
xkcd_mode bool False xkcd style
save_path str None Folder of the figure
save_formats str | list 'pdf' Format(s) of the figure
file_name str 'trials' File name without extension
**figure_style Keys of FIGURE_STYLE (missing ones from it)

Returns: None — the figure is saved

  • psth_legend_counts

psth_legend_counts(session_rows, figure_rows, hue, separate, group_columns=('cell_group',), count_column='n_cells', count_name='cells') -> dict

Legend text of each line colour of a population PSTH figure, "<level>\nN=<mice>, n=<sessions>\n<cells> <count_name>, <events> events", for the labels of plot_psth_lines. The counts are restricted to the figure's separate groups (and its session or mouse when it has those columns).

Parameter Type Default Description
session_rows pd.DataFrame Session PSTHs counted (e.g. data, not surrogates), one row per time bin, with mouse_id, session_id, event_group, epoch_group, the group_columns, count_column, n_events and the hue / separate columns
figure_rows pd.DataFrame Rows of the figure
hue str | None Column of the line colours
separate list[str] Columns of the groups drawn in separate figures
group_columns tuple ('cell_group',) Columns of the cell (unit) groups
count_column str 'n_cells' Number of cells (units) per session PSTH
count_name str 'cells' Word in the legend

Returns: dict — {hue level: text}, key None without hue


display.cells_map_utils (Cell contours and maps)

  • cells_table

cells_table(n_cells, centers, cells_to_hide=(), cells_groups=None, cells_groups_colors=None, values=None)

The cells of a cells map as drawn: one row per cell with its centre, whether it is shown, the groups it is drawn in and its colour.

Parameter Type Default Description
n_cells int Number of cells
centers dict[int, tuple] Centre (x, y) of each cell (CellsCoord.center_coord)
cells_to_hide list[int] () Cells not drawn
cells_groups list[list[int]] None The groups coloured, in their drawing order
cells_groups_colors list None Colour of each group
values array-like None The value each cell is coloured by (e.g. its number of transients)

Returns: DataFrame — columns cell, x, y, shown, groups (;-joined indices), color (hex, of the last group drawn), and value when given

  • CellsCoord

CellsCoord(coords=None, pixel_masks=None, nb_lines=None, nb_col=None, from_matlab=False, invert_xy_coord=False)

Class. The contours, centres and polygons of the cells of an imaging field, from contour coordinates or pixel masks (one of the two is required; with pixel masks only, the contours come from their convex hull). The list given as coords is modified in place (shifted, swapped).

Parameter Type Default Description
coords list[np.ndarray] None Per cell, a (2, n_points) array of x and y contour coordinates
pixel_masks list None Per cell, its pixels as (line, column[, weight]); the weight is ignored
nb_lines int None Image height
nb_col int None Image width; unless both nb_lines and nb_col are given, both come from the largest coordinate + 2
from_matlab bool False Coordinates indexed from 1 (MATLAB): 1 is subtracted
invert_xy_coord bool False Swap x and y

Main attributes: n_cells, nb_lines, nb_col, coords (contours), pixel_masks (per cell a (2, n_pixels) array), center_coord ({cell: (x, y)}, centroid of the contour), cells_polygon ({cell: shapely Polygon}), intersect_cells ({cell: cells it overlaps}).

  • compute_distance_from_center

compute_distance_from_center(center_dict) -> np.ndarray

Euclidean distance between the centres of every pair of cells, in the units of the centres (pixels; the Pairwise similarity plugin multiplies it by the pixel size).

Parameter Type Description
center_dict dict {cell: (x, y)} with the cells numbered 0 to n - 1 (e.g. CellsCoord.center_coord)

Returns: np.ndarray — symmetric (n_cells, n_cells), 0 on the diagonal