magmap.plot.plot_support module

Shared plotting functions with the MagellanMapper package.

class magmap.plot.plot_support.ImageOverlayer(ax, aspect, origin=None, ignore_invis=False, rgb=False, additive_blend=False)[source]

Bases: object

Manager for overlaying multiple images on top of one another.

class RotTransform(transform=None, xlims=None, ylims=None)[source]

Bases: object

Rotation transformation settings.

transform: Optional[Transform] = None

Matplotlib transformation.

xlims: Optional[Tuple[int, int]] = None

x-axis limits.

ylims: Optional[Tuple[int, int]] = None

y-axis limits

additive_blend: bool

Display images with additive blending; defaults to False.

annotate_labels(labels_2d, ref_lookup, level=None, labels_annots=None, over_label=True, cmap=None, color_bbox=True, label_names=None, kwargs=None)[source]

Annotate labels with acronyms.

Parameters:
  • labels_2d – 2D labels image.

  • ref_lookup – Labels lookup dictionary of label IDs to label metadata. Can be None if over_label is False and label_names is given.

  • level (default: None) – Ontology level; defaults to None.

  • labels_annots (default: None) – Text artists from which new artists will be re-created with the same name and positions. Takes precedence over labels_2d and defaults to None.

  • over_label (default: True) – True (default) to ensure that the annotation is over a label pixel. Otherwise, places the annotation at the label’s centroid, whether or not it is a label pixel, which may be useful for label edges.

  • cmap (default: None) – Discrete colormap to color the label based on its ID. Defaults to None, in which case the color will be black.

  • color_bbox (default: True) – True (default) to color the label bounding box instead of the text. Only used if cmap is given.

  • label_names (default: None) – Dictionary of label IDs to names; defaults to None. If given, only these labels and names will be shown.

  • kwargs (default: None) – Dictionary of additional arguments for the text artist. Defaults to None.

aspect: Union[str, float]

Aspect ratio.

ax: axes.Axes

Plot axes.

ignore_invis: bool

True to avoid creating AxesImage objects for images that would be invisible; defaults to False.

imshow_multichannel(img2d, channel, cmaps, alpha=None, vmin=None, vmax=None, interpolation=None, norms=None, nan_color=None, alpha_blend=None, rgb=False)[source]

Show multichannel 2D image with channels overlaid over one another.

Applies config.transform with config.Transforms.ROTATE to rotate images. If not available, also checks the first element in :attr:config.flip to rotate the image by 180 degrees.

Applies config.transform with config.Transforms.FLIP_HORIZ and config.Transforms.FLIP_VERT to invert images.

Parameters:
  • img2d (ndarray) – 2D image either as 2D (y, x) or 3D (y, x, channel) array.

  • channel (Optional[Sequence[int]]) – Sequence of channels to display; if None, all channels will be shown.

  • cmaps (Sequence[Union[str, Colormap]]) – List of colormaps corresponding to each channel. Colormaps can be the names of specific maps in :mod:config.

  • alpha (Union[float, Sequence[float], None], default: None) – Transparency level for all channels or sequence of levels for each channel. If any value is 0, the corresponding image will not be output. Defaults to None to use 1.

  • vmin (Union[float, Sequence[float], None], default: None) – Scalar or sequence of vmin levels for all channels; defaults to None.

  • vmax (Union[float, Sequence[float], None], default: None) – Scalar or sequence of vmax levels for all channels; defaults to None.

  • interpolation (Optional[str], default: None) – Type of interpolation; defaults to None.

  • norms (Optional[Sequence[Normalize]], default: None) – List of normalizations, which should correspond to cmaps.

  • nan_color (Optional[str], default: None) – String of color to use for NaN values; defaults to None to leave these pixels empty.

  • alpha_blend (Optional[float], default: None) – Opacity blending value; defaults to None.

  • rgb (bool, default: False) – True to display as RGB(A); defaults to False.

Return type:

List[AxesImage]

Returns:

List of Matplotlib image objects.

labels_annots: Dict[int, 'axes.Axes.Text']

Dictionary of label IDs to annotation text artists; defaults to an empty dictionary.

origin: Optional[str]

Image planar orientation, usually either “lower” or None; defaults to None.

overlay_images(imgs2d, channels, cmaps, alphas=None, vmins=None, vmaxs=None, check_single=False, alpha_blends=None)[source]

Show multiple, overlaid images.

Wrapper function calling imshow_multichannel() for multiple images. The first image is treated as a sample image with potential for multiple channels. Subsequent images are typically label images, which may or may not have multple channels.

Parameters:
Return type:

Optional[List[List[AxesImage]]]

Returns:

Nested list containing a list of Matplotlib image objects corresponding to display of each imgs2d image.

remove_labels()[source]

Remove label annotations.

rgb: bool

True to show images as RGB(A); defaults to False.

setup_transform(img2d, rotate=None, center=None)[source]

Set up transformation from config settings.

Parameters:
  • img2d (ndarray) – 2D+/-channel array.

  • rotate (Optional[int], default: None) – Clockwise rotation in degrees.

  • center (Optional[Tuple[int, int]], default: None) – Rotation center in x, y. Default of None gives 0, 0.

Return type:

Optional[RotTransform]

Returns:

self._transform for chained calls.

class magmap.plot.plot_support.ImageSyncMixin(img5d)[source]

Bases: object

Mixin class for synchronizing editors with Matplotlib figures.

property additive_blend: bool

Display images with additive blending; default to False.

axes_exit(event)[source]

Trigger axes exit for all plot editors.

Parameters:

event (LocationEvent) – Axes exit event.

edited: bool

Edited flag.

static enable_btn(btn, enable=True, color=None, max_color=0.99)[source]

Display a button or other widget as enabled or disabled.

Note that the button’s active state will not change since doing so prevents the coloration from changing.

Parameters:
  • btn (matplotlib.widgets.AxesWidget) – Widget to change, which must have color and hovercolor attributes.

  • enable (bool) – True to enable (default), False to disable.

  • color (float) – Intensity value from 0-1 for the main color. The hovercolor will be just above this value, while the disabled main and hovercolors will be just below this value. Defaults to None, which will use config.widget_color.

  • max_color (float) – Max intensity value for hover color; defaults to 0.99 to provide at least some contrast with white backgrounds.

fig: Optional[Figure]

Matplotlib figure.

get_img_display_settings(imgi, chl=None)[source]

Get display settings for the given image.

Only settings from the first editor will be retrieved on the assumption that all the editors are synchronized.

Parameters:
  • imgi (int) – Index of image.

  • chl (int) – Index of channel; defaults to None.

Returns:

The currently

displayed image, or None if plot_eds is empty.

Return type:

magmap.gui.plot_editor.PlotAxImg

img5d: Image5d

Image5d image.

on_close(*args)[source]

Figure close handler.

Disconnects all Plot Editors and listeners.

Parameters:

args – Additional arguments, currently ignored.

plot_eds: Dict[Any, PlotEditor]

Dictionary of plot editors.

save_fig(path, **kwargs)[source]

Save the figure to file, with path based on filename, ROI, and overview plane shown.

Parameters:
  • path (str) – Save path.

  • kwargs – Additional arguments passed to save_fig().

set_labels_level(val)[source]

Set the labels level all Plot Editors.

Parameters:

val (int) – Labels level.

set_show_crosslines(val)[source]

Set the attribute to show crosslines for all Plot Editors.

Parameters:

val (bool) – True to show crosslines, false otherwise.

set_show_labels(val)[source]

Set whether to show labels for all Plot Editors.

Parameters:

val (bool) – True to show labels, false otherwise.

show_labels_annots(show_annots=True, annots=None)[source]

Show labels annotations.

Parameters:
  • show_annots (default: True) – True (default) to show annotations.

  • annots (default: None) – Dictionary of plane to text artist sequence, which serves as a cache to redisplay labels for the same plane. Defaults to None, in which case an empty dict will be used.

Returns:

annots dictionary.

static toggle_btn(btn, on=True, shift=0.2, text=None)[source]

Toggle a button between on/off modes.

Parameters:
  • btn – Button widget to change.

  • on (default: True) – True to display the button as on, False as off.

  • shift (default: 0.2) – Float of amount to shift the button color intensity; defaults to 0.2.

  • text (default: None) – Tuple of (on_text, off_text) for the button label; defaults to None to keep the original text.

update_imgs_display(imgi, chl=None, minimum=nan, maximum=nan, brightness=None, contrast=None, alpha=None, alpha_blend=None, refresh=False, **kwargs)[source]

Update dislayed image settings in all Plot Editors.

Parameters:
  • imgi (int) – Index of image group.

  • chl (Optional[int], default: None) – Index of channel; defaults to None.

  • minimum (Optional[float], default: nan) – Vmin; can be None for auto setting; defaults to np.nan to ignore.

  • maximum (Optional[float], default: nan) – Vmax; can be None for auto setting; defaults to np.nan to ignore.

  • brightness (Optional[float], default: None) – Brightness addend; defaults to None.

  • contrast (Optional[float], default: None) – Contrast multiplier; defaults to None.

  • alpha (Optional[float], default: None) – Opacity value; defalts to None.

  • alpha_blend (Optional[float], default: None) – Opacity blending value; defaults to None.

  • refresh (bool, default: False) – True to refresh all zoomed Plot Editors; defaults to False.

  • kwargs – Additional arguments, which are ignored.

Return type:

PlotAxImg

Returns:

The updated axes image plot.

update_max_intens_proj(shape, display=False)[source]

Update max intensity projection planes.

Parameters:
  • shape (Union[int, Sequence[int]]) – Number of planes for all Plot Editors or sequence of plane counts in z,y,x.

  • display (bool) – True to trigger an update in the Plot Editors; defaults to False.

magmap.plot.plot_support.add_scale_bar(ax, downsample=None, plane=None)[source]

Adds a scale bar to the plot.

Uses the x resolution value and assumes that it is in microns per pixel. The bar’s color is taken from the setting in :attr:config.process_settings.

Parameters:
  • ax – The plot that will show the bar.

  • downsample (default: None) – Downsampling factor by which the resolution will be multiplied; defaults to None.

  • plane (default: None) – Plane of the image, used to transpose the resolutions to find the corresponding x resolution for the given orientation. Defaults to None.

magmap.plot.plot_support.add_vspans(ax, vspans, vspan_lbls=None, padding=1, vspan_alt_y=False)[source]

Add vertical spans to group x-values.

Shifts legend away from span labels.

Parameters:
  • ax (Axes) – Matplotlib axes.

  • vspans (ndarray) – Sequence of vertical span x-vals in data units.

  • vspan_lbls (Optional[Sequence[str]], default: None) – Sequence of span labels; defaults to None.

  • padding (float, default: 1) – Padding around each span; defaults to 1.

  • vspan_alt_y (bool, default: False) – True to alternate the height of labels; defaults to False.

magmap.plot.plot_support.alpha_blend_intersection(img1, img2, alpha=0.5, mask1=None, mask2=None)[source]

Alpha blend the intersecting foreground of two images.

Adjust the opacity to blend the parts of images that overlap while retaining full opacity for their non-overlapping parts to increase contrast and highlight potential misalignments.

Parameters:
  • img1 (ndarray) – First image.

  • img2 (ndarray) – Second image.

  • alpha (float, default: 0.5) – Alpha level from 0-1 for the first image to use for its intersecting area; the second image will use 1 - alpha.

  • mask1 (Optional[ndarray], default: None) – Foreground mask for img1; defaults to None, in which case the foreground will be segmented using Otsu’s method.

  • mask2 (Optional[ndarray], default: None) – Same for img2; defaults to None.

Return type:

Tuple[ndarray, ndarray]

Returns:

The foreground masks with alpha blending for the intersection area.

magmap.plot.plot_support.extract_planes(image5d, plane_n, plane=None, max_intens_proj=False)[source]

Extract a 2D plane or stack of planes.

Parameters:
  • image5d (np.ndarray) – The full image stack in either t,z,y,x[,c] or z,y,x formate; if 4 or more dimensions, the first dimension is assumed to be time and ignored.

  • plane_n (int, slice) – Slice of planes to extract, which can be a single index or multiple indices such as would be used for an animation.

  • plane (str) – Type of plane to extract, which should be one of :attribute:`config.PLANES`.

  • max_intens_proj (bool) – True to show a max intensity projection, which assumes that plane_n is an array of multiple, typically contiguous planes along which the max intensity pixel will be taken. Defaults to False.

Returns:

Tuple of an array of the image, which is 2D if plane_n is a scalar or max_intens_projection is True, or 3D otherwise; the aspect ratio; and the origin value.

magmap.plot.plot_support.fit_frame_to_image(fig, shape=None, aspect=None)[source]

Compress figure to fit image only.

Use config.plot_labels[config.PlotLabels.PADDING] to configure figure padding.

Parameters:
  • fig (Figure) – Figure to compress.

  • shape (Optional[Sequence[int]], default: None) – Shape of image to which the figure will be fit. Default of None uses the first axes bounding box.

  • aspect (Optional[float], default: None) – Aspect ratio of image. Default of None gives 1.

magmap.plot.plot_support.get_aspect_ratio(plane)[source]

Get the aspect ratio and origin for the given plane.

Inversts the ratio if config.transform[config.Transforms.ROTATE] is set to rotate the image by an odd number of 90 degree turns.

Parameters:

plane – Planar orientation, which should be one of :const:config.PLANE.

Returns:

Tuple of the aspect ratio as a float, or None if :attr:detector.resolutions has not been set; and origin as a string, or None for default origin.

magmap.plot.plot_support.get_downsample_max_sizes()[source]

Get the maximum sizes by axis to keep an image within size limits during downsampling as set in the current atlas profile based on whether the image is loaded as a NumPy memmapped array or not.

Return type:

Dict[str, int]

Returns:

Dictionary of plane in xy format to maximum sizes by axis set in the current profile if it is also set to downsample images loaded by NumPy, otherwise None.

magmap.plot.plot_support.get_plane_axis(plane, get_index=False)[source]

Gets the name of the plane corresponding to the given axis.

Parameters:
  • plane (str) – An element of :attr:config.PLANE.

  • get_index (bool) – True to get the axis as an index.

Returns:

The axis name orthogonal to :attr:config.PLANE as string, or the axis index in the order z,y,x if get_index is True.

magmap.plot.plot_support.hide_axes(ax, frame_off=False)[source]

Hides x- and y-axes and the axes frame.

Parameters:
  • ax (Axes) – Plot axes.

  • frame_off (bool, default: False) – True to turn off the frame; defaults to False.

magmap.plot.plot_support.max_plane(img3d, plane)[source]

Get the max plane for the given 3D image.

Parameters:
  • img3d – Image array in (z, y, x) order.

  • plane – Plane as a value from :attr:config.PLANE.

Returns:

Number of elements along plane’s axis.

magmap.plot.plot_support.save_fig(path, ext=None, modifier='', fig=None, backup=True, **kwargs)[source]

Save figure with support for backup and alternative file formats.

Dots per inch is set by config.plot_labels[config.PlotLabels.DPI]. Backs up any existing file before saving. If the found extension is not for a supported format for the figure’s backend, the figure is not saved. Any non-existing parents folders will be created.

Parameters:
  • path (Union[str, Path]) – Base path to use, with or without extension.

  • ext (Optional[str], default: None) – File format extension for saving, with or without period. Defaults to None, in which case any extension in path is used. If no extension is found, magmap.settings.config.DEFAULT_SAVEFIG is used. If the extension is in config.FORMATS_3D or not supported by Matplotlib, the figure will not be saved.

  • modifier (str, default: '') – Modifier string to append before the extension; defaults to an empty string.

  • fig (Optional[Figure], default: None) – Figure; defaults to None to use the current figure.

  • kwargs – Additional arguments to matplotlib.figure.savefig().

  • backup (bool, default: True) – True (default) to back up any existing file before saving.

Return type:

Optional[str]

Returns:

The output path, or None if the file was not saved.

magmap.plot.plot_support.scale_axes(ax, scale_x=None, scale_y=None)[source]

Scale axes.

Parameters:
  • ax (matplotlib.axes.Axes) – Matplotlib axes.

  • scale_x (str) – Matplotlib scale mode, eg “linear”, “log”, “symlog” (to include negative values), and “logit”, for the x-axis. Defaults to None to ignore.

  • scale_y (str) – Matplotlib scale mode for the y-axis. Defaults to None to ignore.

magmap.plot.plot_support.scale_xticks(ax, rotation, x_labels=None)[source]

Draw x-tick labels with smaller font for increasing number of labels.

Parameters:
  • ax (Axes) – Matplotlib axes.

  • rotation (float) – Label rotation angle.

  • x_labels (Optional[Sequence[Any]], default: None) – X-axis labels; defaults to None, in which case the current labels will be used.

magmap.plot.plot_support.scroll_plane(event, z_overview, max_size, jump=None, max_scroll=None)[source]

Scroll through overview images along their orthogonal axis.

Parameters:
  • event (MouseEvent) – Mouse or key event. For mouse events, scroll step sizes will be used for movements. For key events, arrows will be used.

  • z_overview (int) – Index of plane to show.

  • max_size (int) – Maximum number of planes.

  • jump (Optional[Callable[[MouseEvent], Any]], default: None) – Function to jump to a given plane; defaults to None. Activated if present and “j”+click is pressed.

  • max_scroll (Optional[int], default: None) – Max number of planes to scroll by mouse. Ignored during jumps.

Returns:

Index of plane after scrolling.

Return type:

int

magmap.plot.plot_support.set_overview_title(ax, plane, z_overview, zoom='', level=0, max_intens_proj=False)[source]

Set the overview image title.

Parameters:
  • ax – Matplotlib axes on which to display the title.

  • plane – Plane string.

  • z_overview – Value along the axis corresponding to that plane.

  • zoom (default: '') – String showing zoom information; defaults to “”.

  • level (default: 0) – Overview view image level, where 0 is unzoomed, 1 is the next zoom, etc; defaults to 0.

  • max_intens_proj (default: False) – True to add maximum intensity projection information to the first overview subplot; defaults to False.

magmap.plot.plot_support.set_scinot(ax, lims=(-3, 4), lbls=None, units=None)[source]

Set axes tick scientific notation and shift exponents to their labels.

Scientific notation in Matplotlib positions the exponent at the top of the y-axis and right of the x-axis, which may be missed or overlap with the title or other labels. This method sets scientific notation along with axis labels and units and moves any exponent to the unit labels. Units will be formatted with math text.

In some cases, scientific notation is incompatible with the axes’ formatter and will be ignored. It can often be set up before the plot, however, and this function can be called both before and after the plot to set up the notation and later override any labeling set up by the plot.

Parameters:
  • ax (Axes) – Axis object.

  • lims (Sequence[int], default: (-3, 4)) – Scientific notation limits as a sequence of lower and upper bounds outside of which scientific notation will be used for each applicable axis. Defaults to (-2, 4).

  • lbls (Optional[Sequence[str]], default: None) – Sequence of axis labels given in the order (y-axis, x-axis). Defaults to None, which causes the corresponding value from config.plot_labels to be used if available. A None element prevents the label main text from displaying and will show the unit without parentheses if available.

  • units (Optional[Sequence[str]], default: None) – Sequence of units given in the order (y-axis, x-axis). Defaults to None, which causes the corresponding value from config.plot_labels to be used if available. A None element prevents unit display other than any scientific notation exponent.

magmap.plot.plot_support.setup_fig(nrows=1, ncols=1, size=None)[source]

Setup a figure and associated gridspec.GridSpec.

Parameters:
  • nrows (int, default: 1) – Number of rows; defaults to 1.

  • ncols (int, default: 1) – Number of columns; defaults to 1.

  • size (Optional[Sequence[float]], default: None) – Sequence of figure size in (width, height) in inches; defaults to None.

Return type:

Tuple[Figure, GridSpec]

Returns:

The figure and grid spec used for its layout.

magmap.plot.plot_support.setup_images_for_plane(plane, arrs_3d)[source]

Set up image arrays and scaling for the given planar orientation.

Parameters:
  • plane (str) – Target planar orientation as one of config.PLANE.

  • arrs_3d (List[np.ndarray]) – Sequence of 3D arrays to transpose.

Returns:

Sequence of transposed 3D arrays; aspect ratio, or None if :attr:detector.resolutions has not been set; origin, or None for default origin; and transposed labels scaling.

Return type:

List[np.ndarray], float, str, List[float]

magmap.plot.plot_support.setup_vspans(df, col_vspan, vspan_fmt)[source]

Set up vertical spans to group axis groups.

Parameters:
  • df (DataFrame) – Data frame.

  • col_vspan (str) – Column in df, assumed to be ordered by group. Changes in value denote the start of the next vertical span.

  • vspan_fmt (str) – String formatter for span labels.

Return type:

Tuple[ndarray, Sequence[str]]

Returns:

Tuple of a vertical span array of starting indices and a sequence of span labels.

magmap.plot.plot_support.show()[source]

Simple wrapper to show the current Matplotlib figure using matplotlib.pyplot, which manages the event loop.

magmap.plot.plot_support.transpose_images(plane, arrs_3d=None, arrs_1d=None, rev=False)[source]

Transpose images and associated coorinates to the given plane.

Parameters:
  • plane – Target plane, which should be one of :const:config.PLANE. If rev is True, the array will be assumed to have been transposed from plane.

  • arrs_3d (default: None) – Sequence of 3D arrays to transpose; defaults to None.

  • arrs_1d (default: None) – Sequence of 1D arrays to transpose, typically coordinates associated with the 3D arrays; defaults to None.

  • rev (default: False) – True to transpose in reverse, from plane to “xy”.

Returns:

Tuple of a list of transposed 3D arrays, or None if no 3D arrays are given; and a list of transposed 1D arrays, or None if no 1D arrays are given.