visplot#

class cryocat.analysis.visplot.BaseBuilder(input_data, column_names_x=None, colors=None, separate_graphs=False, same_range_for_separate=True, opacity=None, grid_spec='column', color_type='palette')#

Bases: object

Base class for Plotly figure builders.

Handles data loading, color resolution, grid layout, and the single/subplot dispatch. Concrete subclasses must implement plot_subplots(), plot_single(), and build_trace().

Parameters:
input_datapandas.DataFrame or numpy.ndarray

Data to plot.

column_names_xlist of str, optional

Column names. Resolved automatically when None.

colorsstr or list of str, optional

Palette name, colorscale name, or explicit list of color strings.

separate_graphsbool, default=False

When True, each column is rendered in its own subplot.

same_range_for_separatebool, default=True

Share axis range across subplots.

opacityfloat, optional

Trace opacity. Defaults to 1.0 (separate) or 0.65 (overlaid).

grid_specstr, default=”column”

Subplot layout: "row", "column", "auto", or "RxC".

color_type{‘palette’, ‘colorscale’}, default=”palette”

Whether colors should be resolved as a discrete palette or a continuous colorscale.

build_trace(*args, **kwargs)#

Construct a single Plotly trace for one data column.

Returns:
plotly.basedatatypes.BaseTraceType
change_to_separate_graphs(message='', opacity=None, grid_spec='column')#

Switch the builder to separate-subplot mode in place.

Parameters:
messagestr, default=””

Warning text to print before switching (empty → silent).

opacityfloat, optional

Override trace opacity. Defaults to 1.0.

grid_specstr, default=”column”

Subplot layout specification (forwarded to _parse_grid()).

plot_graph(*args, **kwargs)#

Build and return the figure, dispatching to subplots or single mode.

Calls plot_subplots() when self.separate_graphs is True, otherwise calls plot_single(). Default layout is applied after building.

Returns:
plotly.graph_objects.Figure
plot_single(*args, **kwargs)#

Build a figure with all data columns overlaid on one axes.

Returns:
plotly.graph_objects.Figure
plot_subplots(*args, **kwargs)#

Build a figure with one subplot per data column.

Returns:
plotly.graph_objects.Figure
process_second_axis_data(second_axis_data, column_names_y, x_id='x')#

Load and align a second (Y) axis onto self.y_axis / self.y_id.

When second_axis_data is None, the original x_axis is promoted to y_axis and x_axis is replaced with a sequential index (useful for line / scatter plots against an implicit index).

Parameters:
second_axis_dataarray-like or pandas.DataFrame or None

Data for the Y axis. None triggers the index-as-x fallback.

column_names_ylist of str or None

Column names for second_axis_data.

x_idstr, default=”x”

Column label used for the synthetic index axis.

Returns:
bool

True when the Y data was broadcast (tiled) to match the number of X columns.

update_graph_layout(**layout_setup)#

Apply layout overrides to the current figure.

Parameters:
**layout_setup

Keyword arguments forwarded directly to fig.update_layout.

Raises:
Warning

When called before plot_graph().

update_layout_settings(**layout_setup)#

Update self.default_layout with overrides, keeping old values.

class cryocat.analysis.visplot.Defaults(template: 'str' = 'plotly_white', height: 'int' = 500, width: 'int | None' = None, showlegend: 'bool' = True, margin: 'dict' = <factory>, font_family: 'str' = 'Arial, sans-serif', font_size: 'int' = 14, colorway: 'str | list[Color]' = 'Plotly', colorscale: 'str | Colorscale | list[Color]' = 'Viridis', extra_layout: 'dict' = <factory>)#

Bases: object

colorscale = 'Viridis'#
colorway = 'Plotly'#
extra_layout#
font_family = 'Arial, sans-serif'#
font_size = 14#
height = 500#
margin#
showlegend = True#
template = 'plotly_white'#
to_layout_kwargs()#

Convert defaults into fig.update_layout kwargs (resolving names).

width = None#
class cryocat.analysis.visplot.Hist2DBuilder(input_data, column_names_x=None, second_axis_data=None, column_names_y=None, nbinsx=40, nbinsy=40, x_range=None, y_range=None, hist_type='count', hist_norm=None, same_scale=False, colors=None, separate_graphs=False, same_range_for_separate=True, opacity=None, grid_spec='column')#

Bases: BaseBuilder

Builder for 2-D histograms using plotly.graph_objects.Histogram2d.

Parameters:
input_datapandas.DataFrame or numpy.ndarray

X-axis data.

column_names_xlist of str, optional

Column labels for input_data.

second_axis_dataarray-like or pandas.DataFrame, optional

Y-axis data. When None, the sequential index is used.

column_names_ylist of str, optional

Column labels for second_axis_data.

nbinsxint, default=40

Number of bins along the X axis.

nbinsyint, default=40

Number of bins along the Y axis.

x_rangetuple of float, optional

(min, max) for the X axis.

y_rangetuple of float, optional

(min, max) for the Y axis.

hist_typestr, default=”count”

Aggregation function (Plotly histfunc).

hist_normstr or None, optional

Normalisation string passed to Plotly histnorm.

same_scalebool, default=False

Use a shared colorscale across all subplots.

colorsstr or list, optional

Colorscale specification.

separate_graphsbool, default=False

One subplot per data column pair.

same_range_for_separatebool, default=True

Share axis ranges across subplots.

opacityfloat, optional

Trace opacity.

grid_specstr, default=”column”

Subplot grid layout.

build_trace(x, y, name, xbins, ybins)#

Construct a plotly.graph_objects.Histogram2d trace.

Parameters:
xarray-like

X-axis data.

yarray-like

Y-axis data.

namestr

Trace name shown in the legend.

xbinsdict

Bin specification {start, end, size} for the X axis.

ybinsdict

Bin specification {start, end, size} for the Y axis.

Returns:
plotly.graph_objects.Histogram2d
plot_single(*args, **kwargs)#

Build a figure with a single 2-D histogram.

Returns None when more than one column pair is present (use plot_subplots() instead).

Returns:
plotly.graph_objects.Figure or None
plot_subplots(*args, **kwargs)#

Build a subplot figure with one 2-D histogram per column pair.

Returns:
plotly.graph_objects.Figure
prepare_trace_kwargs(showscale=None, coloraxis=None, colorbar=None)#

Update self.trace_kwargs for the next batch of traces.

Parameters:
showscalebool, optional

Override showscale in trace kwargs.

coloraxisstr, optional

Plotly coloraxis reference (e.g. "coloraxis"). When set, removes the per-trace colorscale key.

colorbardict, optional

Colorbar layout dict to attach to each trace.

class cryocat.analysis.visplot.HistBuilder(input_data, column_names_x=None, bins=20, hist_type='count', hist_norm='', opacity=None, colors=None, x_range=None, separate_graphs=False, same_range_for_separate=True, same_scale=False, grid_spec='column')#

Bases: BaseBuilder

Builder for 1-D histograms using plotly.graph_objects.Histogram.

Parameters:
input_datapandas.DataFrame or numpy.ndarray

Data to histogram.

column_names_xlist of str, optional

Column labels.

binsint, default=20

Number of bins.

hist_type{‘count’, ‘sum’, ‘avg’, ‘min’, ‘max’}, default=”count”

Aggregation function passed to Plotly histfunc.

hist_normstr, default=””

Normalisation: "percent", "probability", "density", "probability density", or "" for raw counts.

opacityfloat, optional

Trace opacity.

colorsstr or list of str, optional

Color palette specification.

x_rangetuple of float, optional

(min, max) for the x axis.

separate_graphsbool, default=False

One subplot per column.

same_range_for_separatebool, default=True

Share x-axis range across subplots.

same_scalebool, default=False

Share y-axis scale across subplots.

grid_specstr, default=”column”

Subplot grid layout.

build_trace(y, name, color, x_range, xbins)#

Construct a plotly.graph_objects.Histogram trace.

Parameters:
yarray-like

Data values for this histogram.

namestr

Legend label.

colorstr

Bar fill color.

x_rangetuple of float

(min, max) used to clip the display range.

xbinsdict

Bin specification {start, end, size} passed to Plotly.

Returns:
plotly.graph_objects.Histogram
plot_single()#

Build a figure with all histograms overlaid.

Returns:
plotly.graph_objects.Figure
plot_subplots()#

Build a subplot figure with one histogram per data column.

Returns:
plotly.graph_objects.Figure
class cryocat.analysis.visplot.KDEBuilder(input_data, column_names_x=None, second_axis_data=None, column_names_y=None, nbinsx=200, nbinsy=200, x_range=None, y_range=None, hist_type='count', hist_norm=None, same_scale=False, colors=None, same_range_for_separate=True, opacity=None, grid_spec='column')#

Bases: Hist2DBuilder

Builder for 2-D kernel density estimate contour plots.

Extends Hist2DBuilder by replacing the binned histogram with a Gaussian KDE evaluated on a regular grid. Always runs in separate_graphs=True mode.

Parameters:
input_datapandas.DataFrame or numpy.ndarray

X-axis data.

column_names_xlist of str, optional

Column labels.

second_axis_dataarray-like or pandas.DataFrame, optional

Y-axis data.

column_names_ylist of str, optional

Column labels for second_axis_data.

nbinsxint, default=200

Grid resolution along the X axis.

nbinsyint, default=200

Grid resolution along the Y axis.

x_rangetuple of float, optional

(min, max) for the X axis (ignored; KDE derives its own limits).

y_rangetuple of float, optional

(min, max) for the Y axis (ignored; KDE derives its own limits).

hist_typestr, default=”count”

Passed to the parent Hist2DBuilder (not used in KDE rendering).

hist_normstr or None, optional

Passed to the parent Hist2DBuilder (not used in KDE rendering).

same_scalebool, default=False

Normalise all subplots to the same z range.

colorsstr or list, optional

Colorscale specification.

same_range_for_separatebool, default=True

Share axis ranges across subplots.

opacityfloat, optional

Trace opacity.

grid_specstr, default=”column”

Subplot grid layout.

build_trace(x_grid, y_grid, z_grid, zmax)#

Construct a filled plotly.graph_objects.Contour trace.

Parameters:
x_gridnumpy.ndarray

Grid points along X.

y_gridnumpy.ndarray

Grid points along Y.

z_gridnumpy.ndarray

KDE density values, shape (nbinsy, nbinsx).

zmaxfloat

Upper bound for the color scale.

Returns:
plotly.graph_objects.Contour
compute_kde(x_axis, y_axis)#

Evaluate a 2-D Gaussian KDE on a regular grid.

Parameters:
x_axisarray-like

X data.

y_axisarray-like

Y data.

Returns:
xgnumpy.ndarray

Grid points along X.

ygnumpy.ndarray

Grid points along Y.

zgnumpy.ndarray

KDE density values, shape (nbinsy, nbinsx).

zmaxfloat

Maximum non-negligible density value (used to set the color scale upper bound).

x_rangetuple of float

Padded (min, max) for the X axis.

y_rangetuple of float

Padded (min, max) for the Y axis.

list_max(same_scale=False)#
normalize_ranges(ranges)#

Optionally collapse per-panel axis ranges to a single global range.

Parameters:
rangeslist of tuple of float

Per-panel (min, max) pairs.

Returns:
list of tuple of float

Same length as ranges. All entries are identical when self.same_range_for_separate is True.

padded_limits(v, frac=0.05, min_pad=0.0, bw=None, k_bw=3.0)#

Return padded (min, max) limits for a data vector.

Parameters:
varray-like

1-D data.

fracfloat, default=0.05

Padding as a fraction of the data span.

min_padfloat, default=0.0

Minimum absolute padding regardless of data span.

bwfloat or None, optional

KDE bandwidth. When provided, k_bw * bw is also considered as a candidate padding value.

k_bwfloat, default=3.0

Multiplier applied to bw.

Returns:
lofloat

Lower limit.

hifloat

Upper limit.

plot_single(*args, **kwargs)#

Build a figure with a single KDE contour.

Returns None when more than one column pair is present.

Returns:
plotly.graph_objects.Figure or None
plot_subplots(*args, **kwargs)#

Build a subplot figure with one KDE contour per column pair.

Returns:
plotly.graph_objects.Figure
class cryocat.analysis.visplot.ScatterBuilder(input_data, column_names_x=None, second_axis_data=None, column_names_y=None, line_mode='markers', x_range=None, y_range=None, colors=None, separate_graphs=False, same_range_for_separate=True, opacity=None, grid_spec='column')#

Bases: BaseBuilder

Builder for scatter / line plots using plotly.graph_objects.Scatter.

Parameters:
input_datapandas.DataFrame or numpy.ndarray

X-axis data (or Y-axis data when second_axis_data is None).

column_names_xlist of str, optional

Column labels.

second_axis_dataarray-like or pandas.DataFrame, optional

Y-axis data.

column_names_ylist of str, optional

Column labels for second_axis_data.

line_modestr, default=”markers”

Plotly mode string, e.g. "markers", "lines", "lines+markers".

x_rangetuple of float, optional

(min, max) for the X axis.

y_rangetuple of float, optional

(min, max) for the Y axis.

colorsstr or list of str, optional

Color palette specification.

separate_graphsbool, default=False

One subplot per data column.

same_range_for_separatebool, default=True

Share axis ranges across subplots.

opacityfloat, optional

Marker opacity.

grid_specstr, default=”column”

Subplot grid layout.

build_trace(x, y, name, color)#

Construct a plotly.graph_objects.Scatter trace.

Parameters:
xarray-like

X-axis values.

yarray-like

Y-axis values.

namestr

Legend label.

colorstr

Marker color.

Returns:
plotly.graph_objects.Scatter
plot_single(*args, **kwargs)#

Build a figure with all series overlaid on one axes.

Returns:
plotly.graph_objects.Figure
plot_subplots(*args, **kwargs)#

Build a subplot figure with one scatter/line panel per column.

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.add_xyz_heatmap_row(fig, slices, row, coloraxis='coloraxis', annot_format=None, hide_ticks=True)#

Add a row of three XY / XZ / YZ cross-section heatmaps to an existing figure.

Each input slice is transposed and vertically flipped before plotting so that the on-screen orientation matches the standard cryo-EM display convention. The function mutates fig in place; pair it with a make_subplots() figure that has at least 3 columns.

Parameters:
figplotly.graph_objects.Figure

Subplot figure with cols >= 3.

slicessequence of array-like

Exactly three 2-D arrays in (XY, XZ, YZ) order.

rowint

1-based row index in the subplot grid.

coloraxisstr, default=”coloraxis”

Name of the shared coloraxis to attach the traces to.

annot_formatstr, optional

Python format() spec for cell annotations (e.g. ".2f"). When None, no annotations are added.

hide_ticksbool, default=True

Hide tick labels on the three subplots.

Raises:
ValueError

If slices does not contain exactly three elements.

cryocat.analysis.visplot.apply_defaults(fig, **layout_overrides)#

Apply global defaults to an existing figure, with optional overrides.

cryocat.analysis.visplot.browse(df, column_name, **kwargs)#

Browse a DataFrame group by group with Prev / Next / dropdown controls.

Displays one group at a time in a Jupyter notebook. Each group’s figure is produced by plot_scatter_3d(); **kwargs are forwarded to it unchanged, so pass the same keyword arguments you would use there (coord_columns, color_column_name, marker_size, opacity, etc.).

Requires ipywidgets. If it is not installed, a clear ImportError is raised with an install hint.

Parameters:
dfpd.DataFrame

Source data.

column_namestr

Column to group by. Unique values become the browser’s navigation steps.

axeslist of str, optional

Three column names to use as x, y, z axes. Alias for coord_columns. When neither axes nor coord_columns is given, the function checks whether columns "x", "y", and "z" exist in df; if they do, they are used automatically; otherwise the first three columns are used.

**kwargs

Forwarded to plot_scatter_3d(). title and output_path are removed if present — the title is set automatically to the group value and saving is not supported in browse mode.

Examples

>>> visplot.browse(motl.df, "object_id", color_column_name="class", marker_size=3)
>>> visplot.browse(df, "label", axes=["cx", "cy", "cz"])
cryocat.analysis.visplot.discrete_colorscale(colors)#

Build a stepped (banded) Plotly colorscale from an ordered list of colors.

Each color fills one equal-width band with hard edges, so an n-color list renders as n flat blocks rather than a smooth gradient. Useful for mapping a small set of integer category codes to distinct colors (see categorical in plot_vtp_mesh()).

cryocat.analysis.visplot.plot_alignment_stability(input_dfs, labels=None, graph_title='Alignment stability', output_path=None)#

Per-parameter alignment statistics over iterations.

Creates a 3x4 grid of line plots, one panel per DataFrame column. Each series in input_dfs is drawn on the same panel.

Parameters:
input_dfssequence of DataSource

Each element is normalized via cryocat.utils.ioutils.df_load(). All sources must share the same columns and number of rows.

labelssequence of str, optional

Series labels for the legend. Defaults to input_dfs[0].columns with the legend hidden.

graph_titlestr, default=”Alignment stability”

Figure title.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_class_occupancy(occupancy_dic, color_scheme=None, show_legend=True, graph_title=None, output_path=None)#

Per-class particle counts over alignment iterations.

Parameters:
occupancy_dicdict

Mapping {class_id: list_of_counts} where each list contains the particle count at each iteration.

color_schemestr or list of str, optional

Plotly palette name or explicit list of colors. None falls back to DEFAULTS.colorway.

show_legendbool, default=True

Display the class legend.

graph_titlestr, optional

Figure title. Defaults to "Class occupancy progress".

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_class_stability(subtomo_changes, color_scheme=None, show_legend=True, graph_title=None, output_path=None)#

Number of particles that changed class at each iteration.

Parameters:
subtomo_changesdict

Mapping {class_id: list_of_change_counts} per iteration.

color_schemestr or list of str, optional

Plotly palette name or explicit list of colors. None falls back to DEFAULTS.colorway.

show_legendbool, default=True

Display the class legend.

graph_titlestr, optional

Figure title. Defaults to "Stability of classes".

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_classification_convergence(occupancy_dic, subtomo_changes_dic, color_scheme=None, graph_title=None, output_path=None)#

Class occupancy and class stability side by side.

Parameters:
occupancy_dicdict

Mapping {class_id: list_of_counts} for the occupancy panel.

subtomo_changes_dicdict

Mapping {class_id: list_of_changes} for the stability panel.

color_schemestr or list of str, optional

Plotly palette name or explicit list of colors. None falls back to DEFAULTS.colorway.

graph_titlestr, optional

Overall figure title.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_fsc(input_data, pixel_size=None, box_size=None, output_path=None)#

Plot a Fourier Shell Correlation (FSC) curve using Plotly.

Parameters:
input_datapath or pandas.DataFrame

Data source. Accepted formats:

.csv

Must contain a column x and one or more of uncorrected_fsc, corrected_fsc, mean_phase_fsc.

.xml

ChimeraX-compatible FSC XML (<coordinate><x>/<y>).

.txt

Single-column file of FSC values. Requires pixel_size and box_size to compute the x-axis.

pandas.DataFrame

Same column convention as .csv.

pixel_sizefloat, optional

Pixel size in Angstroms. Used to label the x-axis 1/Å and required when input_data is a .txt file.

box_sizeint, optional

Box edge length in voxels. Required when input_data is a .txt file.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_grouped_box(data, group_column_name, value_column_name, title=None, xaxis_title=None, yaxis_title=None, colorscale='Monet', boxpoints='outliers', output_path=None)#

Side-by-side box plots of value_column_name grouped by group_column_name.

Each group is rendered with a colour sampled from colorscale, so the palette degrades gracefully whatever the number of groups.

Parameters:
dataDataSource

Long-format data: one row per observation. Normalized via cryocat.utils.ioutils.df_load().

group_column_namestr

Column whose unique values define the box groups (x-axis).

value_column_namestr

Column holding the numeric values plotted in each box.

title, xaxis_title, yaxis_titlestr, optional

Figure and axis labels.

colorscalestr or list, default=”Monet”

Colorscale specification used to colour each box. See resolve_colors_any().

boxpointsstr or bool, default=”outliers”

Plotly boxpoints setting (e.g. "all", "outliers", False).

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_histogram(input_data, column_names_x=None, bins=20, separate_graphs=False, hist_type='count', hist_norm='', same_range_for_separate=True, same_scale=False, colors=None, opacity=None, grid_spec='column')#

Plot 1-D histogram(s) using Plotly.

Parameters:
input_dataDataSource

Data to histogram. Normalized via cryocat.utils.ioutils.df_load().

column_names_xlist of str, optional

Column labels. Defaults to the DataFrame’s own columns.

binsint, default=20

Number of bins.

separate_graphsbool, default=False

One subplot per column.

hist_type{‘count’, ‘sum’, ‘avg’, ‘min’, ‘max’}, default=”count”

Plotly aggregation function.

hist_normstr, default=””

Normalisation string passed to Plotly.

same_range_for_separatebool, default=True

Share x range across subplots.

same_scalebool, default=False

Share y scale across subplots.

colorsstr or list of str, optional

Color palette specification.

opacityfloat, optional

Trace opacity.

grid_specstr, default=”column”

Subplot grid layout.

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_histogram_2d(input_data, column_names_x=None, second_axis_data=None, column_names_y=None, nbinsx=40, nbinsy=40, x_range=None, y_range=None, hist_type='count', hist_norm=None, same_scale=False, colors=None, separate_graphs=False, same_range_for_separate=True, opacity=None, grid_spec='column')#

Plot 2-D histogram(s) using Plotly.

Parameters:
input_dataDataSource

X-axis data. Normalized via cryocat.utils.ioutils.df_load().

column_names_xlist of str, optional

Column labels for X data.

second_axis_dataDataSource, optional

Y-axis data. Normalized via cryocat.utils.ioutils.df_load().

column_names_ylist of str, optional

Column labels for Y data.

nbinsxint, default=40

Bins along X.

nbinsyint, default=40

Bins along Y.

x_rangetuple of float, optional

(min, max) for the X axis.

y_rangetuple of float, optional

(min, max) for the Y axis.

hist_typestr, default=”count”

Plotly aggregation function.

hist_normstr, optional

Normalisation string.

same_scalebool, default=False

Shared colorscale across subplots.

colorsstr or list, optional

Colorscale specification.

separate_graphsbool, default=False

One subplot per column pair.

same_range_for_separatebool, default=True

Share axis ranges across subplots.

opacityfloat, optional

Trace opacity.

grid_specstr, default=”column”

Subplot grid layout.

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_kde(input_data, column_names_x=None, second_axis_data=None, column_names_y=None, nbinsx=200, nbinsy=200, hist_type='count', hist_norm=None, colors=None, opacity=None, grid_spec='column', same_range_for_separate=False, same_scale=False, output_path=None)#

Plot 2-D kernel density estimate contour(s) using Plotly.

Parameters:
input_dataDataSource

X-axis data. Normalized via cryocat.utils.ioutils.df_load().

column_names_xlist of str, optional

Column labels for X data.

second_axis_dataDataSource, optional

Y-axis data. Normalized via cryocat.utils.ioutils.df_load().

column_names_ylist of str, optional

Column labels for Y data.

nbinsxint, default=200

Grid resolution along X.

nbinsyint, default=200

Grid resolution along Y.

hist_typestr, default=”count”

Passed to KDEBuilder (not used in contour rendering).

hist_normstr, optional

Passed to KDEBuilder (not used in contour rendering).

colorsstr or list, optional

Colorscale specification.

opacityfloat, optional

Trace opacity.

grid_specstr, default=”column”

Subplot grid layout.

same_range_for_separatebool, default=False

Share axis ranges across subplots.

same_scalebool, default=False

Normalise all subplots to the same z range.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_line(input_data, column_names_x=None, separate_graphs=False, same_range_for_separate=False, colors=None, opacity=None, grid_spec='column')#

Plot line chart(s) using Plotly.

Parameters:
input_dataDataSource

Y-axis data. X is the sequential row index. Normalized via cryocat.utils.ioutils.df_load().

column_names_xlist of str, optional

Column labels.

separate_graphsbool, default=False

One subplot per column.

same_range_for_separatebool, default=False

Share axis ranges across subplots.

colorsstr or list of str, optional

Color palette specification.

opacityfloat, optional

Line opacity.

grid_specstr, default=”column”

Subplot grid layout.

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_orientational_distribution(coordinates, projection='stereo', graph_title=None, theta_bin=73, radius_bin=33, max_radius=None, colormap='viridis_r', output_path=None)#

Polar histogram of unit vectors, both hemispheres side by side.

Vectors are projected to polar coordinates, binned into a theta_bin × radius_bin grid, and rendered as filled annular sectors via plotly.graph_objects.Barpolar.

Parameters:
coordinatesarray-like

Unit vectors (or vectors that will be projected), shape (N, 3).

projection{‘stereo’, ‘lambert’, ‘equidistant’}, default=”stereo”

Projection algorithm passed to cryocat.utils.geom.create_projection().

graph_titlestr, optional

Figure title.

theta_binint, default=73

Number of angular bin edges. theta_bin - 1 sectors per radial ring.

radius_binint, default=33

Number of radial bin edges. radius_bin - 1 rings per hemisphere.

max_radiusfloat, optional

Maximum projected radius. Defaults to the data maximum.

colormapstr, default=”viridis_r”

Colorscale name resolved via resolve_colorscale().

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_otsu_thresholds(motl, column_name, hbin, graph_title=None, output_path=None)#

Per-group score histograms with their Otsu thresholds overlaid.

Visual companion to cryocat.core.cryomotl.Motl.compute_otsu_threshold(): same per-group histogram and threshold computation, rendered as a grid of Plotly subplots (one per group) with the threshold as a dashed vertical line.

Parameters:
motlMotl

Source motl. The score column is histogrammed.

column_namestr

Column used to group particles (e.g. "tomo_id" or "object_id").

hbinint

Number of histogram bins per group.

graph_titlestr, optional

Figure title.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_pca_summary(cumulative_variance, feature_importances, scatter_kwargs=None, bar_kwargs=None, output_path=None)#

Create a combined subplot for PCA analysis.

The figure has two side-by-side panels:

  • Cumulative explained variance (line plot).

  • Feature importance (horizontal bar plot).

Parameters:
cumulative_variancearray-like

Values of cumulative explained variance.

feature_importancespandas.Series

Series of feature importance (e.g., squared loadings) from PCA.

scatter_kwargsdict, optional

Keyword arguments forwarded to the cumulative-variance plotly.graph_objects.Scatter.

bar_kwargsdict, optional

Keyword arguments forwarded to the feature-importance plotly.graph_objects.Bar.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_ply_mesh(ply_paths, mesh_labels=None, colors=None, opacity=0.5, overlay_points=None, overlay_names=None, overlay_colors=None, overlay_marker_size=3, title=None, output_path=None)#

Display one or more .ply mesh files as interactive 3-D surfaces.

Each file is loaded via open3d.io.read_triangle_mesh and rendered as a semi-transparent plotly.graph_objects.Mesh3d trace. Point clouds passed via overlay_points are added as plotly.graph_objects.Scatter3d traces on top of the mesh(es).

Parameters:
ply_pathsPathOrStr or list of PathOrStr

Path(s) to .ply mesh file(s).

mesh_labelslist of str, optional

Legend labels, one per mesh. Defaults to the filename stems.

colorsstr or list of str, optional

Color palette specification. Resolved via resolve_colors_any().

opacityfloat, default=0.5

Mesh opacity (0–1).

overlay_pointsN×3 array or list of N×3 arrays, optional

One or more point clouds to overlay as Scatter3d markers.

overlay_nameslist of str, optional

Legend labels for each overlay point cloud.

overlay_colorsstr or list of str, optional

Colors for the overlay point clouds. Resolved via resolve_colors_any().

overlay_marker_sizeint, default=3

Marker size for overlay point clouds.

titlestr, optional

Figure title.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_points_with_normals(points, normals=None, labels=None, colors=None, sample_fraction=1.0, show_normals=True, normal_scale=5.0, marker_size=3, title=None, output_path=None)#

Display one or more oriented point clouds as interactive 3-D scatter plots.

Each point cloud is shown as a plotly.graph_objects.Scatter3d trace. When normals are provided and show_normals is True, surface normals are drawn as plotly.graph_objects.Cone traces, giving an approximate view of particle or surface orientation.

Parameters:
pointsarray-like of shape (N, 3) or list of such arrays

Spatial coordinates, one array per point cloud.

normalsarray-like of shape (N, 3) or list of such arrays, optional

Surface normals aligned with points. Required when show_normals=True.

labelslist of str, optional

Legend labels, one per point cloud.

colorsstr or list of str, optional

Color palette specification. Resolved via resolve_colors_any().

sample_fractionfloat, default=1.0

Fraction of points to display (random subsample). Values in (0, 1]. Useful for large dense meshes; the already-sparse oversampled clouds (~1 500 points) can be shown at full resolution.

show_normalsbool, default=True

When True and normals are provided, draw each normal as a cone.

normal_scalefloat, default=5.0

Absolute cone length in the same units as points.

marker_sizeint, default=3

Scatter marker size in pixels.

titlestr, optional

Figure title.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_polar_nn_distances(coordinates, distances, max_radius=None, marker_size=3, colormap='viridis_r', graph_title=None, output_path=None)#

Plot nearest-neighbour distances in polar (stereographic) projection.

Two polar subplots (northern and southern hemisphere) with each point coloured by its nearest-neighbour distance.

Parameters:
coordinatesarray-like

Unit vectors, shape (N, 3).

distancesarray-like

Per-point distances, shape (N,).

max_radiusfloat, optional

Maximum radial extent for both polar subplots. Defaults to the data maximum.

marker_sizeint, default=3

Scatter marker size.

colormapstr, default=”viridis_r”

Colorscale name resolved via resolve_colorscale().

graph_titlestr, optional

Figure title.

output_pathPathOrStr, optional

Saved with _save_plotly() (.html interactive; other extensions need kaleido).

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_rotation_normals(input_rotation, color_map=None, marker_size=4, alpha=1.0, radius=1.0, graph_title=None, output_path=None)#

Plot z-normals of input_rotation as a 3-D scatter on a sphere.

Each rotation is applied to (0, 0, radius) and the resulting points are scattered on a sphere of the given radius. Plotting counterpart of cryocat.utils.geom.rotations_to_z_normals().

Parameters:
input_rotationRotationLike

Orientations to plot. Normalized via cryocat.utils.geom.as_rotation().

color_mapstr, optional

Colorscale name resolved via resolve_colorscale(), used to colour points by their z coordinate. None uses a single solid color from the default colorway.

marker_sizeint, default=4

Scatter marker size.

alphafloat, default=1.0

Marker opacity.

radiusfloat, default=1.0

Sphere radius. Sets the reference vector length and axis ranges.

graph_titlestr, optional

Figure title.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_rotation_normals_binned(input_angles, n_bins=None, cone_sampling=None, radius=1.0, height_scale=0.3, colors='StarryNight', show_sphere=True, graph_title=None, output_path=None)#

Binned orientation distribution: radial bars on a sphere.

Particle orientations (zxz Euler angles) are converted to z-normal directions, assigned to the nearest golden-angle bin, and rendered as outward-pointing radial bars. Bar length and colour both encode the particle count in each bin, producing a “sea-urchin” appearance: long bright spikes where orientations cluster and short stubble for a uniform distribution.

Parameters:
input_anglesarray_like

Shape (N, 3). zxz Euler angles in degrees, exactly as returned by cryocat.core.cryomotl.Motl.get_angles().

n_binsint, optional

Explicit number of direction bins. Mutually exclusive with cone_sampling.

cone_samplingfloat, optional

Angular bin size in degrees; the number of bins is computed via cryocat.utils.geom.number_of_cone_rotations(). Mutually exclusive with n_bins. Defaults to 5.0 when neither parameter is supplied.

radiusfloat, default=1.0

Radius of the reference sphere. All geometry is scaled by this value; binning always uses unit vectors.

height_scalefloat, default=0.3

Maximum bar height as a fraction of radius. The tallest bar reaches radius * (1 + height_scale) from the origin.

colorsstr or colorscale or list of colors, default=”StarryNight”

Colorscale for the bar line colour. Accepts any name known to resolve_colorscale() or an explicit [(pos, color), …] list.

show_spherebool, default=True

When True, adds a translucent reference sphere of radius radius behind the bars.

graph_titlestr, optional

Figure title.

output_pathpath or str, optional

When supplied, the figure is saved to disk via _save_plotly().

Returns:
plotly.graph_objects.Figure

3-D figure with one bar-lines trace (plus an optional sphere surface).

Raises:
UserInputError

When input_angles is not (N, 3) with N >= 1, or when both n_bins and cone_sampling are supplied.

See also

plot_rotation_normals

Raw (unbinned) scatter of the same normals.

cryocat.utils.geom.sample_sphere

Golden-angle bin-direction source.

cryocat.analysis.visplot.plot_scatter_2d(input_data, column_names_x=None, second_axis_data=None, column_names_y=None, separate_graphs=False, same_range_for_separate=False, x_range=None, y_range=None, colors=None, opacity=None, grid_spec='column')#

Plot 2-D scatter plot(s) using Plotly.

Parameters:
input_dataDataSource

X-axis data. Normalized via cryocat.utils.ioutils.df_load().

column_names_xlist of str, optional

Column labels for X data.

second_axis_dataDataSource, optional

Y-axis data. Normalized via cryocat.utils.ioutils.df_load().

column_names_ylist of str, optional

Column labels for Y data.

separate_graphsbool, default=False

One subplot per column pair.

same_range_for_separatebool, default=False

Share axis ranges across subplots.

x_rangetuple of float, optional

(min, max) for the X axis.

y_rangetuple of float, optional

(min, max) for the Y axis.

colorsstr or list of str, optional

Color palette specification.

opacityfloat, optional

Marker opacity.

grid_specstr, default=”column”

Subplot grid layout.

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_scatter_3d(data, coord_columns=None, color_column_name=None, color_label='Group', marker_size=3, opacity=1.0, title=None, hover_columns=None, output_path=None)#

3-D scatter plot with an optional color-coded value column.

Parameters:
dataDataSource

Source data. Normalized via cryocat.utils.ioutils.df_load().

coord_columnslist of str, optional

Three column names for x, y, z. Defaults to the first three columns.

color_column_namestr, optional

Column whose values colour the markers (continuous colorbar).

color_labelstr, default=”Group”

Title shown on the colorbar.

marker_sizeint, default=3

Marker size in pixels.

opacityfloat, default=1.0

Marker opacity.

titlestr, optional

Figure title.

hover_columnslist of str, optional

Column names whose values are shown in the hover tooltip.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_scatter_with_histogram(data_x, data_y, bins_x=None, bins_y=None, colors_x=None, colors_y=None, edges_x=None, edges_y=None, axis_title_x=None, axis_title_y=None, output_path=None)#

Scatter plot with marginal histograms on the top and right.

Parameters:
data_x, data_yarray-like

X / Y data.

bins_x, bins_yint, optional

Number of bins for the X- and Y-marginal histograms. Defaults to 30.

colors_x, colors_ystr or list of str, optional

Color spec for the marginal histogram bars. A list is used directly; a string with matching edges_* is treated as a palette/colorscale name resolved via resolve_colors_any().

edges_x, edges_ylist of float, optional

Bin-edge thresholds for conditional colouring of each marginal.

axis_title_x, axis_title_ystr, optional

Scatter-panel axis labels.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_scatter_xyz_panels(data, coord_columns=None, group_by=None, hover_column_name=None, circle_radius=None, displ_threshold=None, title=None, marker_size=5, output_path=None)#

Plot three 2-D scatter views (XY, XZ, YZ) of 3-D coordinates.

Subsumes the four nearest-neighbour scatter helpers that previously lived in cryocat.analysis.nnana. The behavior of those helpers is recovered via the optional parameters: pass group_by to colour-group particles (plot_nn_rot_coord_df), hover_column_name for interactive hover text (plot_nn_rot_coord_df_plotly), or circle_radius to overlay a reference disk (plot_nn_coord_df).

Parameters:
dataDataSource

Source data with at least three columns of coordinates. Normalized via cryocat.utils.ioutils.df_load().

coord_columnslist of str, optional

Three column names for x, y, z. Defaults to the first three columns of data.

group_bystr, optional

Column whose unique values define color groups with a legend. Mutually useful with hover_column_name; the latter is ignored when group_by is set.

hover_column_namestr, optional

Column used as per-point hover text.

circle_radiusfloat, optional

When given, a filled gold reference disk of this radius is overlaid on each panel.

displ_thresholdfloat, optional

Clamp all axes to [-displ_threshold, displ_threshold].

titlestr, optional

Figure title.

marker_sizeint, default=5

Scatter marker size in pixels.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_scores_and_peaks(peak_files, plot_title=None, output_path=None)#

Plot interactive heatmaps of peak cross-sections for multiple peak-related arrays.

Generates heatmaps for three orthogonal 2-D slices (X, Y, Z) centered at the main peak. The peak center and the colour-scale maximum (vmax) are determined from the first entry in peak_files and reused for all subsequent entries; the colour-scale minimum (vmin) is the data minimum of each entry independently.

Parameters:
peak_fileslist of array_like or list of str

List of 3-D arrays or file paths containing peak-related data. Each entry is processed using cryocat.analysis.tmana.create_starting_parameters_2D() to extract peak-centered slices.

plot_titlestr, optional

Title for the entire figure.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_spherical_density_2d(input_data, column_names_x=None, nbinsx=10, nbinsy=10, x_range=None, y_range=None, hist_type='count', hist_norm='percent', normalize_coord=True, colors='Viridis', same_scale=False, same_range_for_separate=False, grid_spec='column')#

Plot spherical density as 2-D histograms in (phi, theta) space.

Converts 3-D Cartesian coordinates to spherical angles and renders each set of coordinates as a 2-D histogram on the phi/theta plane.

Parameters:
input_dataDataSource

Cartesian coordinates. Must contain a multiple-of-3 number of columns (x, y, z for each set) when given as a DataFrame or CSV. Normalized via cryocat.utils.ioutils.df_load().

column_names_xlist of str, optional

Column names when input_data is a DataFrame.

nbinsxint, default=10

Bins along the phi axis.

nbinsyint, default=10

Bins along the theta axis.

x_rangetuple of float, optional

(min, max) for phi. Defaults to (-pi, pi).

y_rangetuple of float, optional

(min, max) for theta. Defaults to (0, pi).

hist_typestr, default=”count”

Plotly aggregation function.

hist_normstr, default=”percent”

Normalisation string.

normalize_coordbool, default=True

Normalise input vectors to unit length before converting.

colorsstr or list, default=”Viridis”

Colorscale specification.

same_scalebool, default=False

Shared colorscale across subplots.

same_range_for_separatebool, default=False

Share axis ranges across subplots.

grid_specstr, default=”column”

Subplot grid layout.

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.plot_vtp_mesh(vtp_paths, color_by=None, mesh_labels=None, colors=None, colorscale='RdBu_r', colorscale_range=None, categorical=False, category_labels=None, opacity=0.9, overlay_points=None, overlay_names=None, overlay_colors=None, overlay_marker_size=3, title=None, output_path=None)#

Display one or more .vtp meshes, optionally colored by a curvature field.

Each file is loaded via pyvista.read and rendered as a plotly.graph_objects.Mesh3d trace. When color_by is given, a per-vertex scalar field (e.g. "mean_curvature", "gaussian_curvature", "k1", "k2", "curvature_anisotropy", "shape_index", "curvedness", "shape_category") is mapped to the trace’s intensity array using a diverging colorscale. A single colorbar is shown when coloring a single mesh; multi-mesh plots share the same scale.

Point clouds passed via overlay_points are added as plotly.graph_objects.Scatter3d traces on top of the mesh(es), which is useful for overlaying particle positions.

Parameters:
vtp_pathsPathOrStr or list of PathOrStr

Path(s) to .vtp mesh file(s).

color_bystr, optional

Name of a point-data scalar field stored in the file, e.g. "mean_curvature". When None each mesh is drawn with a flat color from colors.

mesh_labelslist of str, optional

Legend labels, one per mesh. Defaults to the filename stems.

colorsstr or list of str, optional

Flat-color palette used when color_by is None.

colorscalestr, default "RdBu_r"

Colorscale used when color_by is set. Accepts any built-in Plotly name ("Viridis", "RdBu_r"), a registered cryoCAT scale ("StarryNightDiverging", "StarryNightBlues", "Monet", …), or a raw [(pos, color), …] list.

colorscale_rangetuple of (float, float), optional

Explicit (cmin, cmax) for the colorscale. When None the range is derived from the data across all loaded meshes. Useful for comparing multiple meshes on a shared scale or for clipping outliers. Ignored when categorical=True.

categoricalbool, default=False

Treat color_by as integer category codes rather than a continuous field. Each code gets a discrete color sampled from colorscale at its ordinal position (negative codes, e.g. flat -1, render gray) and the colorbar becomes a named legend. Intended for fields like "shape_category".

category_labelsdict of {int: str}, optional

Mapping from category code to label shown on the categorical colorbar (e.g. surface.Mesh.SURFACE_TYPE_LABELS). Only used when categorical.

opacityfloat, default=0.9

Mesh opacity (0–1).

overlay_pointsN×3 array or list of N×3 arrays, optional

One or more point clouds to overlay as Scatter3d markers.

overlay_nameslist of str, optional

Legend labels for each overlay point cloud.

overlay_colorsstr or list of str, optional

Colors for the overlay point clouds. Resolved via resolve_colors_any().

overlay_marker_sizeint, default=3

Marker size for overlay point clouds.

titlestr, optional

Figure title.

output_pathPathOrStr, optional

Saved with _save_plotly().

Returns:
plotly.graph_objects.Figure
cryocat.analysis.visplot.px_defaults(**overrides)#

Kwargs to pass into Plotly Express functions.

cryocat.analysis.visplot.register_colorscale(name, hex_colors)#

Register a continuous colorscale from a list of colors (stops spread evenly).

cryocat.analysis.visplot.register_palette(name, colors)#

Register a discrete palette (used for categorical colorway).

cryocat.analysis.visplot.resolve_colors_any(spec=None, *, color_type='palette', n=None)#
cryocat.analysis.visplot.resolve_colorscale(spec)#

Return a Plotly colorscale [(pos,color),…] from name or explicit input.

cryocat.analysis.visplot.resolve_palette(spec)#

Return a list of colors given a name or explicit sequence.

cryocat.analysis.visplot.save_as_svg(fig, path=None, *, camera=None, perspective=None)#

Export fig as an editable SVG string, projecting 3-D traces to 2-D first.

Parameters:
figgo.Figure or dict

The figure to export. A plain dict (as received from a Dash State) is also accepted and converted internally.

pathpath-like, optional

If given, the SVG string is also written to this file.

cameradict, optional

Plotly camera dict with optional sub-dicts eye, center, up and projection (each with the usual Plotly keys). When supplied, it overrides the camera declared in fig.layout.scene.camera. This is how the GUI passes the camera currently shown on screen.

perspectivebool or None, default None

When None (default), the projection type is read from the figure’s scene.camera.projection.type (Plotly’s default is "perspective"). Pass True or False to override.

Returns:
svgstr

The SVG file content.

skippedlist[str]

Trace types that were present in the figure but could not be projected (mesh3d, surface, cone, streamtube). Empty when all traces were handled. The caller is responsible for surfacing this to the user.

Notes

Supported trace types

scatter3d

Fully supported. Points are projected; line and marker style, colour, colourscale+range, marker size, connectgaps, legend name and colour bar are all preserved. Marker symbol has no 2-D equivalent and is dropped. For mode="markers" traces, points are sorted back-to-front by depth so near markers are drawn on top; line traces are left in their original order to preserve geometry.

mesh3d, surface, cone, streamtube

Not supported. These traces are silently omitted; their types are returned in skipped.

Axis normalisation

Plotly rescales data before applying the camera according to scene.aspectmode (default "auto" / "cube"). This function applies the same normalisation so that a figure with x spanning 400 and z spanning 40 projects identically to the screen view.

If the figure contains no 3-D traces, Plotly’s normal SVG export is used and the projection path is not taken.

cryocat.analysis.visplot.set_defaults(**kwargs)#

Update global DEFAULTS. Nested ‘extra_layout’ is merged (shallow).

cryocat.analysis.visplot.use_defaults(**overrides)#

Temporarily override DEFAULTS inside a ‘with’ block.

Yields:
None