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:
objectManager for overlaying multiple images on top of one another.
- class RotTransform(transform=None, xlims=None, ylims=None)[source]#
Bases:
objectRotation transformation settings.
- 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_labelis False andlabel_namesis 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 overlabels_2dand 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 ifcmapis 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
AxesImageobjects 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.transformwithconfig.Transforms.ROTATEto rotate images. If not available, also checks the first element in :attr:config.flipto rotate the image by 180 degrees.Applies
config.transformwithconfig.Transforms.FLIP_HORIZandconfig.Transforms.FLIP_VERTto 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 tocmaps.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:
- 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:
imgs2d (
Sequence[ndarray]) – Sequence of 2D images to display, where the first image may be 2D+channel.channels (
Optional[List[List[int]]]) – A nested list of channels to display for each image, or None to use :attr:config.channelfor the first image and 0 for all subsequent images.cmaps (
Sequence[Union[str,Colormap,DiscreteColormap]]) – Either a single colormap for all images or a list of colormaps corresponding to each image. Colormaps of typecolormaps.DiscreteColormapwill have their normalization object applied as well. If a color is given forconfig.AtlasLabels.BINARYinconfig.atlas_labels, images withcolormaps.DiscreteColormapwill be converted to NaN for foreground to use this color.alphas (
Union[float,Sequence[Union[float,Sequence[float]]],None], default:None) – Either a single alpha for all images or a list of alphas corresponding to each image. Defaults to None to useconfig.alphas, filling with 0.9 for any additional values required andconfig.plot_labelsfor the first value.vmins (
Union[float,Sequence[Union[float,Sequence[float]]],None], default:None) – A list of vmins for each image; defaults to None to use :attr:config.vminsfor the first image and None for all others.vmaxs (
Union[float,Sequence[Union[float,Sequence[float]]],None], default:None) – A list of vmaxs for each image; defaults to None to use :attr:config.vmax_overviewfor the first image and None for all others.check_single (
bool, default:False) – True to check for images with a single unique value displayed with acolormaps.DiscreteColormap, which will not update for unclear reasons. If found, the final value will be incremented by one as a workaround to allow updates. Defaults to False.alpha_blends (
Union[float,Sequence[Union[float,Sequence[float]]],None], default:None) – Opacity blending values for each image inimgs2d; defaults to None.
- Return type:
- Returns:
Nested list containing a list of Matplotlib image objects corresponding to display of each
imgs2dimage.
- rgb: bool#
True to show images as RGB(A); defaults to False.
- class magmap.plot.plot_support.ImageSyncMixin(img5d)[source]#
Bases:
objectMixin class for synchronizing editors with Matplotlib figures.
- axes_exit(event)[source]#
Trigger axes exit for all plot editors.
- Parameters:
event (
LocationEvent) – Axes exit event.
- 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 havecolorandhovercolorattributes.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.
- 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:
- Returns:
- The currently
displayed image, or None if
plot_edsis empty.
- Return type:
- 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:
annotsdictionary.
- 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 tonp.nanto ignore.maximum (
Optional[float], default:nan) – Vmax; can be None for auto setting; defaults tonp.nanto 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:
- Returns:
The updated axes image plot.
- 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 use1 - alpha.mask1 (
Optional[ndarray], default:None) – Foreground mask forimg1; defaults to None, in which case the foreground will be segmented using Otsu’s method.mask2 (
Optional[ndarray], default:None) – Same forimg2; defaults to None.
- Return type:
- 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 eithert,z,y,x[,c]orz,y,xformate; 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_nis a scalar ormax_intens_projectionis 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.
- 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.resolutionshas 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.
- magmap.plot.plot_support.get_plane_axis(plane, get_index=False)[source]#
Gets the name of the plane corresponding to the given axis.
- magmap.plot.plot_support.hide_axes(ax, frame_off=False)[source]#
Hides x- and y-axes and the axes frame.
- 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 inpathis used. If no extension is found,magmap.settings.config.DEFAULT_SAVEFIGis used. If the extension is inconfig.FORMATS_3Dor 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:
- 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.
- 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:
- 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 fromconfig.plot_labelsto 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 fromconfig.plot_labelsto 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:
- Return type:
- 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.resolutionshas 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:
- Return type:
- 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. Ifrevis True, the array will be assumed to have been transposed fromplane.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, fromplaneto “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.