Plotting Module#
Visualization utilities for BCDI data.
Volume Slicing#
- cdiutils.plot.slice.plot_volume_slices(data, support=None, voxel_size=None, data_centre=None, views=None, convention=None, title=None, equal_limits=True, slice_shift=None, integrate=False, opacity=None, plot_type='imshow', contour_levels=100, show=True, **plot_params)[source]#
Generic function for plotting 2D slices (cross section or sum, with option ‘integrate’) of 3D volumes. The slices are plotted according to the specified views and conventions. If not specified, natural views are plotted in matrix convention (x-axis: 2nd dim, y-axis: 1st dim), i.e: * first slice: taken at the centre of axis0 * second slice: taken at the centre of axis1 * third slice: taken at the centre of axis2
- Parameters:
data (np.ndarray) – the data to plot.
support (np.ndarray, optional) – a support for the data. Defaults to None.
voxel_size (tuple | list, optional) – the voxel size to modify the aspect ratio accordingly. Defaults to None.
data_centre (tuple | list, optional) – the centre to take the data at. Defaults to None.
views (tuple[str], optional) – the views for each plot according to the provided convention. If None default views of the specified convention are plotted. Defaults to None.
convention (str, optional) – the convention employed to plot the multiple slices, if views not specified, will set the default views for the specified convention, i.e.: (“x-”, “y+”, “z-”) for XU convention and (“z+”, “y-”, “x+”) for the CXI convention. If None, natural views are plotted. Defaults to None.
title (str, optional) – the title of the plot. Defaults to None.
equal_limits (bool, optional) – whether to have the same limit extend for all axes. Defaults to True.
slice_shift (tuple | list, optional) – the shift in the slice selection, by default will use the centre for each dim. Defaults to None.
integrate (bool, optional) – whether to sum the data instead of taking the slice. Defaults to False.
opacity (np.ndarray, optional) – the opacity 3D array of the data. Defaults to None. If constant opacity is required, use the ‘alpha’ parameter.
plot_type (str, optional) – Type of plot to use. Options are ‘imshow’ or ‘contourf’. Defaults to ‘imshow’.
contour_levels (int, optional) – Number of contour levels when using ‘contourf’ plot type. Defaults to 100.
show (bool, optional) – whether to show the plot. Defaults to True. False might be useful if the function is only used for generating the axes that are then redrawn afterwards.
**plot_params – additional plot params that will be parsed into the matplotlib imshow() function.
- Returns:
the generated figure and axes.
- Return type:
tuple[plt.Figure, plt.Axes]
- cdiutils.plot.slice.plot_multiple_volume_slices(*data_arrays, data_labels=None, supports=None, voxel_sizes=None, data_centres=None, slice_shifts=None, data_stacking='horizontal', pvs_args=None, cbar_args=None, xlim=None, ylim=None, remove_ticks=False, figsize=None, title=None, show=True, **plot_params)[source]#
Plot 2D slices of multiple 3D volumes with customizable layout. This function uses plot_volume_slices as a building block to create a composite figure comparing multiple datasets.
- Parameters:
*data_arrays (np.ndarray) – Multiple 3D arrays to plot.
data_labels (list[str], optional) – Labels for each dataset.
supports (list[np.ndarray], optional) – Support masks for each dataset.
voxel_sizes (list, optional) – List of voxel sizes for each dataset.
data_centres (list, optional) – List of data centers for each dataset.
slice_shifts (list, optional) – List of slice shifts for each dataset.
data_stacking (str, optional) – How to arrange plots (“vertical” or “horizontal”). Defaults to “vertical”.
pvs_args (dict, optional) – Dictionary of parameters for plot_volume_slices.
cbar_args (dict, optional) – Dictionary of colorbar parameters.
xlim (tuple, optional) – Custom x-axis limits (min, max) to apply to all plots.
ylim (tuple, optional) – Custom y-axis limits (min, max) to apply to all plots.
remove_ticks (bool, optional) – Whether to remove ticks between subplots. Defaults to False.
figsize (tuple, optional) – Figure size. If None, calculated based on data.
title (str, optional) – Overall figure title.
show (bool, optional) – Whether to display the figure. Defaults to True.
**plot_params – Additional plotting parameters passed to plot_volume_slices.
- Returns:
The generated figure.
- Return type:
plt.Figure
- cdiutils.plot.slice.plot_slices(*data, slice_labels=None, figsize=None, data_stacking='vertical', nan_supports=None, vmin=None, vmax=None, alphas=None, origin='lower', cmap='turbo', show_cbar=True, cbar_title=None, cbar_location='top', cbar_extend='both', norm=None, cbar_ticks=None, slice_name=None, suptitle=None, show=True)[source]#
Plot 2D slices of the provided data.
3D Visualisation#
Volume plotting functions for BCDI data.
This module provides matplotlib-based functions for plotting 3D volumetric data. For interactive 3D visualization, see cdiutils.interactive.volume.
Note
VolumeViewer has been moved to cdiutils.interactive.volume. Importing from this module is deprecated but supported for backward compatibility.
- cdiutils.plot.volume.plot_3d_voxels(data, support, view='y+', convention='cxi', **plot_params)[source]#
Plot a 3D volumetric representation of data. Voxel are plotted as voxels! No triangulation/interpolation. The voxels to plot are based on the provided support, while the colouring is generated from the data variable.
- Parameters:
data (np.ndarray) – the quantity to plot.
support (np.ndarray) – the support of the data to plot.
view (str, optional) – the initial view of the 3D plot. Can be
"y+". ("x+-/y+-/z+-". Defaults to)
convention (str, optional) – The convention the provided data
follow
"cxi". (eitheir XU or CXI. Defaults to)
- Raises:
ValueError – if convention in invalid.
- Returns:
the matpltolib figure the data were drawn in.
- Return type:
plt.Figure
- cdiutils.plot.volume.hemisphere_projection(data, support, axis, looking_from_downstream=True)[source]#
Compute the hemisphere projection of a volume along one axis.
- Parameters:
data (np.ndarray) – the volume data to project.
support (np.ndarray) – the support of the reconstructed data.
axis (int) – the axis along which to project.
looking_from_downstream (bool, optional) – The direction along axis, positive-going (True) or negative-going (False). Defaults to True.
- Returns:
the 2D array corresponding to the projection.
- Return type:
np.ndarray
- cdiutils.plot.volume.plot_3d_surface_projections(data, support, voxel_size, view_parameters=None, convention=None, figsize=None, title=None, cbar_title=None, save=None, **plot_params)[source]#
Plot 3D projected views from a 3D object.
- Parameters:
data (np.ndarray) – the data to plot.
support (np.ndarray) – the support of the reconstructed object.
voxel_size (tuple | list | np.ndarray) – the voxel size of the data to plot.
view_parameters (dict, optional) – some parameters required for setting the plot views. Defaults to CXI_VIEW_PARAMETERS.
convention (str, optional) – the convention of the data, either “cxi” or “xu”. Defaults to None, which will use the CXI convention.
figsize (tuple, optional) – the size of the figure. Defaults to None.
title (str, optional) – the title of the figure. Defaults to None.
cbar_title (str, optional) – the title of the colour bar. Defaults to None.
- Returns:
the figure.
- Return type:
matplotlib.figure.Figure
- cdiutils.plot.volume.plot_3d_object(data, support=None, cmap='turbo', title='', vmin=None, vmax=None, show=True, marker='H', alpha=1)[source]#
Plot a 3D object.
- Parameters:
data – the 3D array (np.array) to plot.
support – 3D array (np.array) with the same shape as data.
Support is the shape of the 3D data to plot, coordinates whose values <= 0 won’t be plotted. Coordinates whose values > 0 are considred to be part of the object to plot. :param cmap: the matplotlib colormap (str) used for the colorbar (default: “jet”). :param title: title (str) of the figure. Default is empty string. :param vmin: the minimum value (float) for the color scale (default: None). :param vmax: the maximum value (float) for the color scale (default: None). :param show: whether or not to show the figure (bool). If False, the figure is not displayed but returned. :return: None if show is True, otherwise the figure.
- cdiutils.plot.volume.plot_3d_vector_field(data, support, arrow=True, scale=5, cmap='jet', title='', vmin=None, vmax=None, verbose=False)[source]#
Plot a 3D vector field represented by arrows.
- Parameters:
data – the (4-)3D data (np.array). If the object to plot has
a shape m * n * l, then the data must be 3 * m * n * l. Each voxel must contain 3 chanels that describe the vector to plot. :param support: 3D array (np.array) with the same shape as data but without the chanels (therefore m * n * l). Support is the shape of the 3D data to plot, coordinates whose values <= 0 won’t be plotted. Coordinates whose values > 0 are considred to be part of the object to plot. :param arrow: whether or not to used arrows for field representation (bool). If False, marker “o” is plotted instead and color represents norm of the arrow. :param cmap:ScalarMappable the matplotlib colormap (str) used for the colorbar (default: “turbo”). :param title: title (str) of the figure. Default is empty string. :param vmin: the minimum value (float) for the color scale (default: None). :param vmax: the maximum value (float) for the color scale (default: None). :param verbose: whether or not to print out the min and max values of the absolute vector field (bool).
Formatting & Styling#
- cdiutils.plot.formatting.add_labels(axes, views=None, space='direct', convention='cxi', unit=None)[source]#
- cdiutils.plot.formatting.get_x_y_limits_extents(shape, voxel_size, data_centre=None, equal_limits=False)[source]#
- cdiutils.plot.formatting.set_x_y_limits_extents(ax, extents, limits, plane, xaxis_points_left=False)[source]#
- cdiutils.plot.formatting.x_y_lim_from_support(support, pixel_size=(1, 1), central_pixel=None, pad=(-10, 10))[source]#
Return the x and y limits of the a plot using support constraints. The plot will be limited to the support dimension + the pad.
- Parameters:
support (np.ndarray) – the support to get the limits from.
pixel_size (tuple, optional) – the pixel size. Defaults to (1, 1).
central_pixel (tuple, optional) – the position of the central pixel. This matters only if extent/aspect/pixel size are specific. In this case, the user might want to specify where to centre the plotting at.
pad (tuple, optional) – the space between the limits found from the support limits and the ax frame. Defaults to (-5, 5).
- Returns:
the x_limits and y_limits.
- Return type:
list
- cdiutils.plot.formatting.get_extent(shape, voxel_size, plane, zero_centred=True, indexing='ij')[source]#
Find the extents for matshow/imshow plotting, for a given plane. Note that in matlotlib convention, the extent must be provided in the order x, y, but the imshow function plot axis0 along y and axis1 along x. Therefore, plane and indexing must be chosen appropriately.
- Parameters:
shape (tuple) – the shape of the data to plot. voxel_size (tuple | list | np.ndarray): the voxel size of the data to plot.
voxel_size (tuple | list | np.ndarray) – the voxel size of the data to plot.
plane (list) – what plane to get the extents from. Should be a list of 2 axis integers.
zero_centred (bool, optional) – whether the plot must be zero_centred at zero. Defaults to True.
indexing (str) – the indexing convention. If ‘xy’, plane[0] and plane[1] must correspond to x and y respectively. If ‘ij’, plane[0] and plane[1] must correspond to y and x, respectively (numpy/matrix convent).
- Returns:
- first two values correspond to x-axis extent, last two
to the y-axis extent in the matshow/imshow plot.
- Return type:
tuple
- cdiutils.plot.formatting.get_plot_configs(key)[source]#
Get the plotting configurations according to the provided key. If the key matches the generic PLOT_CONFIGS, the configurations are returned, otherwise error is raised.
- Parameters:
key (str) – the key word used for accessing the configurations.
- Raises:
ValueError – if the key does not match any generic keys.
- Returns:
the plotting configurations.
- Return type:
dict
- cdiutils.plot.formatting.update_plot_params(style=None, usetex=False, use_siunitx=True, **kwargs)[source]#
Update the matplotlib plot parameters to plublication style
- cdiutils.plot.formatting.get_figure_size(width='default', scale=1, subplots=(1, 1))[source]#
Get the figure dimensions to avoid scaling in LaTex.
This function was taken from https://jwalton.info/Embed-Publication-Matplotlib-Latex/
- Parameters:
width (int | str) – Document width in points, or string of predefined
document type (float or string) :param fraction: fraction of the width which you wish the figure to occupy (float) :param subplots: the number of rows and columns of subplots
- Returns:
dimensions of the figure in inches (tuple)
- Return type:
tuple
- cdiutils.plot.formatting.get_mappable(ax)[source]#
Get a mappable object from an axis regardless of plot type.
- cdiutils.plot.formatting.add_colorbar(ax, mappable=None, loc='right', size='5%', pad=0.05, label_size=6, scientific_notation=False, **kwargs)[source]#
Add a colorbar to the given axes. Stolen from Edoardo Zatterin sxdm package (https://gitlab.esrf.fr/id01-science/id01-sxdm-utils/).
- Parameters:
ax (plt.Axes) – the axes to which the colorbar will be added.
mappable (matplotlib.cm.ScalarMappable, optional) – the mappable object that the colorbar will be based on. If None, will take ax.images[0]. Defaults to None.
loc (str, optional) – the location where the colorbar will be placed. Defaults to “right”.
size (str, optional) – the size of the colorbar. Defaults to “5%”.
pad (float, optional) – the padding between the colorbar and the axes. Defaults to 0.05.
label_size (int, optional) – the size of the colorbar labels. Defaults to 6.
scientific_notation (bool, optional) – whether to use scientific notation for colorbar labels. Defaults to False.
- Returns:
the colorbar object.
- Return type:
matplotlib.colorbar.Colorbar
- cdiutils.plot.formatting.make_colorwheel(ax, cmap='jch_max')[source]#
Create a colorwheel in the given axis showing phase and magnitude encoding.
This is the generic function that creates a colorwheel in any matplotlib axis. Use this when you want to create a standalone colorwheel (e.g., shared legend for multiple subplots).
- Parameters:
ax (matplotlib.axes.Axes) – the axis to create the colorwheel in.
cmap (str, optional) – the colormap name. For 2D colormaps (‘jch_max’, ‘jch_const’), magnitude is encoded. For 1D colormaps (e.g., ‘hsv’, ‘twilight’), only phase is shown. Defaults to ‘jch_max’.
- Returns:
the axis containing the colorwheel.
- Return type:
matplotlib.axes.Axes
- cdiutils.plot.formatting.add_colorwheel(ax, cmap='jch_max', title=None, size=0.25, pad=0.05)[source]#
Add a 2D colorwheel legend as an inset to an axis showing phase and magnitude encoding.
This function creates an inset axis next to the given axis and draws the colorwheel in it. Use this for adding a colorwheel legend to individual plots.
- Parameters:
ax (matplotlib.axes.Axes) – the axis to add the colorwheel to.
cmap (str, optional) – the colormap name. For 2D colormaps (‘jch_max’, ‘jch_const’), magnitude is encoded. For 1D colormaps (e.g., ‘hsv’, ‘twilight’), only phase is shown. Defaults to ‘jch_max’.
size (float, optional) – size of the colorwheel relative to the parent axis (0-1). Defaults to 0.25.
pad (float, optional) – padding between the axis and colorwheel. Defaults to 0.05.
- Returns:
the inset axes containing the colorwheel.
- Return type:
matplotlib.axes.Axes
Colormaps#
Color maps and color conversion utilities for BCDI visualisation.
This module provides custom colormaps and utilities for converting complex-valued arrays to RGB(A) representations, particularly useful for visualising phase information in BCDI reconstructions.
- cdiutils.plot.colormap.complex_to_rgb(complex_array, cmap='abyss')[source]#
Map complex array to RGB using perceptually uniform JCh colormap.
This function encodes complex data into RGB colors using the JCh (CAM02-UCS) perceptually uniform color space. Phase is mapped to hue, and magnitude is encoded as lightness in the RGB values.
- Parameters:
complex_array (ndarray) – Complex-valued array of any shape.
cmap (str) – 2D colormap to use. Options: - ‘abyss’: Perceptually uniform colormap (dark to light) - ‘peak’: High-contrast colormap (emphasizes peaks) - ‘barrel’: Cylindrical colormap (smooth transitions) - ‘jch_max’: Maximum chroma colormap (vivid, saturated colors) - ‘jch_const’: Constant chroma colormap (uniform brightness across hues) Default is ‘jch_const’.
output_type – Output data type. Options: - ‘float’: Values in [0, 1] range (default) - ‘uint8’: Values in [0, 255] range (for saving images)
- Returns:
Array of shape (…, 3) containing RGB values. RGB channels encode both phase (as hue) and magnitude (as lightness) via the JCh colorspace.
- Return type:
ndarray
Examples
>>> # Basic usage with default max chroma colormap >>> rgb = complex_to_rgb(complex_array) >>> plt.imshow(rgb)
>>> # Use constant chroma for uniform appearance >>> rgb = complex_to_rgb(complex_array, cmap='jch_const')
>>> # Save as uint8 image >>> rgb = complex_to_rgb(complex_array, output_type='uint8') >>> plt.imsave('complex_data.png', rgb)
Notes
Unlike HSV-based approaches, this uses the CAM02-UCS (JCh) color space, ensuring equal perceptual differences for equal phase differences.
Magnitude is fully encoded in RGB lightness - no alpha channel needed.
References