hyperspy.drawing package

Submodules

hyperspy.drawing.figure module

class hyperspy.drawing.figure.BlittedFigure

Bases: object

add_marker(marker)
close()
create_figure(**kwargs)

Create matplotlib figure

Parameters:**kwargs – All keyword arguments are passed to plt.figure.
title

hyperspy.drawing.image module

class hyperspy.drawing.image.ImagePlot

Bases: hyperspy.drawing.figure.BlittedFigure

Class to plot an image with the necessary machinery to update the image when the coordinates of an AxesManager change.

data_fuction

function or method – A function that returns a 2D array when called without any arguments.

pixel_units

{None, string} – The pixel units for the scale bar. Normally

scalebar, colorbar, plot_indices

bool

title

str – The title is printed at the top of the image.

vmin, vmax

float – Limit the range of the color map scale to the given values.

min_aspect

float – Set the minimum aspect ratio of the image and the figure. To keep the image in the aspect limit the pixels are made rectangular.

saturated_pixels

scalar – The percentage of pixels that are left out of the bounds. For example, the low and high bounds of a value of 1 are the 0.5% and 99.5% percentiles. It must be in the [0, 100] range.

centre_colormap

{“auto”, True, False} – If True the centre of the color scheme is set to zero. This is specially useful when using diverging color schemes. If “auto” (default), diverging color schemes are automatically centred.

axes_ticks
configure()
connect()
create_axis()
create_figure(max_size=None, min_size=2, **kwargs)

Create matplotlib figure

The figure size is automatically computed by default, taking into account the x and y dimensions of the image. Alternatively the figure size can be defined by passing the figsize keyword argument.

Parameters:
  • min_size (max_size,) – The maximum and minimum size of the axes in inches. These have no effect when passing the figsize keyword to manually set the figure size.
  • **kwargs – All keyword arguments are passed to plt.figure.
gui_adjust_contrast(display=True, toolkit=None)
Display widgets to adjust image contrast if available. Parameters ———- display: bool

If True, display the user interface widgets. If False, return the widgets container in a dictionary, usually for customisation or testing.

toolkit: str, iterable of strings or None

If None (default), all available widgets are displayed or returned. If string, only the widgets of the selected toolkit are displayed if available. If an interable of toolkit strings, the widgets of all listed toolkits are displayed or returned.

on_key_press(event)
optimize_colorbar(number_of_ticks=5, tolerance=5, step_prec_max=1)
optimize_contrast(data)
plot(**kwargs)
scalebar
set_contrast(vmin, vmax)
update(**kwargs)
vmax
vmin

hyperspy.drawing.marker module

class hyperspy.drawing.marker.MarkerBase

Bases: object

Marker that can be added to the signal figure

marker_properties

dictionary – Accepts a dictionary of valid (i.e. recognized by mpl.plot) containing valid line properties. In addition it understands the keyword type that can take the following values: {‘line’, ‘text’}

add_data(**kwargs)

Add data to the structured array. Each field of data should have the same dimensions than the navigation axes. The other fields are not changed.

close(render_figure=True)

Remove and disconnect the marker.

Parameters:render_figure (bool, optional, default True) – If True, the figure is rendered after removing the marker. If False, the figure is not rendered after removing the marker. This is useful when many markers are removed from a figure, since rendering the figure after removing each marker will slow things down.
get_data_position(ind)
isiterable(obj)
marker_properties
plot(render_figure=True)

Plot a marker which has been added to a signal.

Parameters:render_figure (bool, optional, default True) – If True, will render the figure after adding the marker. If False, the marker will be added to the plot, but will the figure will not be rendered. This is useful when plotting many markers, since rendering the figure after adding each marker will slow things down.
set_data(x1=None, y1=None, x2=None, y2=None, text=None, size=None)

Set data to the structured array. Each field of data should have the same dimensions than the navigation axes. The other fields are overwritten.

set_marker_properties(**kwargs)

Set the line_properties attribute using keyword arguments.

hyperspy.drawing.marker.dict2marker(marker_dict, marker_name)
hyperspy.drawing.marker.markers_metadata_dict_to_markers(metadata_markers_dict, axes_manager)

hyperspy.drawing.mpl_he module

class hyperspy.drawing.mpl_he.MPL_HyperExplorer

Bases: object

assign_pointer()
close()
close_navigator_plot()
is_active
plot(**kwargs)
plot_navigator(colorbar=True, scalebar=True, scalebar_color='white', axes_ticks=None, saturated_pixels=0, vmin=None, vmax=None, no_nans=False, centre_colormap='auto', title=None, **kwds)
plot_signal()

hyperspy.drawing.mpl_hie module

class hyperspy.drawing.mpl_hie.MPL_HyperImage_Explorer

Bases: hyperspy.drawing.mpl_he.MPL_HyperExplorer

plot_signal(colorbar=True, scalebar=True, scalebar_color='white', axes_ticks=None, saturated_pixels=0, vmin=None, vmax=None, no_nans=False, centre_colormap='auto', **kwargs)

Plot image.

Parameters:
  • colorbar (bool, optional) – If true, a colorbar is plotted for non-RGB images.
  • scalebar (bool, optional) – If True and the units and scale of the x and y axes are the same a scale bar is plotted.
  • scalebar_color (str, optional) – A valid MPL color string; will be used as the scalebar color.
  • axes_ticks ({None, bool}, optional) – If True, plot the axes ticks. If None axes_ticks are only plotted when the scale bar is not plotted. If False the axes ticks are never plotted.
  • saturated_pixels (scalar) – The percentage of pixels that are left out of the bounds. For example, the low and high bounds of a value of 1 are the 0.5% and 99.5% percentiles. It must be in the [0, 100] range.
  • vmax (vmin,) – vmin and vmax are used to normalize luminance data.
  • no_nans (bool, optional) – If True, set nans to zero for plotting.
  • optional (**kwargs,) – Additional key word arguments passed to matplotlib.imshow()

hyperspy.drawing.mpl_hse module

class hyperspy.drawing.mpl_hse.MPL_HyperSignal1D_Explorer

Bases: hyperspy.drawing.mpl_he.MPL_HyperExplorer

Plots the current spectrum to the screen and a map with a cursor to explore the SI.

add_right_pointer()
auto_update_plot
key2switch_right_pointer(event)
plot_signal()
remove_right_pointer()
right_pointer_on

I’m the ‘x’ property.

hyperspy.drawing.signal module

hyperspy.drawing.signal1d module

class hyperspy.drawing.signal1d.Signal1DFigure(title='')

Bases: hyperspy.drawing.figure.BlittedFigure

add_line(line, ax='left')
create_axis()
create_right_axis()
plot()
update()
class hyperspy.drawing.signal1d.Signal1DLine

Bases: object

Line that can be added to Signal1DFigure.

type

{‘scatter’, ‘step’, ‘line’} – Select the line drawing style.

line_properties

dictionary – Accepts a dictionary of valid (i.e. recognized by mpl.plot) containing valid line properties. In addition it understands the keyword type that can take the following values: {‘scatter’, ‘step’, ‘line’}

auto_update

bool – If False, executing _auto_update_line does not update the line plot.

set_line_properties()

Enables setting the line_properties attribute using keyword arguments.

Raises:ValueError – If an invalid keyword value is passed to line_properties.
close()
color
get_complex
line_properties
plot(data=1)
set_line_properties(**kwargs)
type
update(force_replot=False, render_figure=True)

Update the current spectrum figure

hyperspy.drawing.tiles module

class hyperspy.drawing.tiles.HistogramTilePlot

Bases: hyperspy.drawing.figure.BlittedFigure

close()
create_axis(ncols=1, nrows=1, number=1, title='')
plot(db, **kwargs)
update(db, **kwargs)

hyperspy.drawing.utils module

class hyperspy.drawing.utils.ColorCycle

Bases: object

hyperspy.drawing.utils.animate_legend(figure='last')

Animate the legend of a figure.

A spectrum can be toggle on and off by clicking on the legended line.

Parameters:figure ('last' | matplotlib.figure) – If ‘last’ pick the last figure

Note

Code inspired from legend_picking.py in the matplotlib gallery

hyperspy.drawing.utils.centre_colormap_values(vmin, vmax)

Calculate vmin and vmax to set the colormap midpoint to zero.

Parameters:vmax (vmin,) – The range of data to display.
Returns:cvmin, cvmax – The values to obtain a centre colormap.
Return type:scalar
hyperspy.drawing.utils.contrast_stretching(data, saturated_pixels)

Calculate bounds that leaves out a given percentage of the data.

Parameters:
  • data (numpy array) –
  • saturated_pixels (scalar, None) – The percentage of pixels that are left out of the bounds. For example, the low and high bounds of a value of 1 are the 0.5% and 99.5% percentiles. It must be in the [0, 100] range. If None, set the value to 0.
Returns:

vmin, vmax – The low and high bounds

Return type:

scalar

Raises:

ValueError if the value of saturated_pixels is out of the valid range.

hyperspy.drawing.utils.create_figure(window_title=None, _on_figure_window_close=None, **kwargs)

Create a matplotlib figure.

This function adds the possibility to execute another function when the figure is closed and to easily set the window title. Any keyword argument is passed to the plt.figure function

Parameters:
  • window_title (string) –
  • _on_figure_window_close (function) –
Returns:

fig

Return type:

plt.figure

hyperspy.drawing.utils.on_figure_window_close(figure, function)

Connects a close figure signal to a given function.

Parameters:
  • figure (mpl figure instance) –
  • function (function) –
hyperspy.drawing.utils.plot_RGB_map(im_list, normalization='single', dont_plot=False)

Plot 2 or 3 maps in RGB.

Parameters:
  • im_list (list of Signal2D instances) –
  • normalization ({'single', 'global'}) –
  • dont_plot (bool) –
Returns:

array

Return type:

RGB matrix

hyperspy.drawing.utils.plot_histograms(signal_list, bins='freedman', range_bins=None, color=None, line_style=None, legend='auto', fig=None, **kwargs)

Plot the histogram of every signal in the list in the same figure.

This function creates a histogram for each signal and plot the list with the utils.plot.plot_spectra function.

Parameters:
  • signal_list (iterable) – Ordered spectra list to plot. If style is “cascade” or “mosaic” the spectra can have different size and axes.
  • bins (int or list or str, optional) – If bins is a string, then it must be one of: ‘knuth’ : use Knuth’s rule to determine bins ‘scotts’ : use Scott’s rule to determine bins ‘freedman’ : use the Freedman-diaconis rule to determine bins ‘blocks’ : use bayesian blocks for dynamic bin widths
  • range_bins (tuple or None, optional.) – the minimum and maximum range for the histogram. If not specified, it will be (x.min(), x.max())
  • color (valid matplotlib color or a list of them or None, optional.) – Sets the color of the lines of the plots. If a list, if its length is less than the number of spectra to plot, the colors will be cycled. If If None, use default matplotlib color cycle.
  • line_style (valid matplotlib line style or a list of them or None,) –
  • optional. – The main line style are ‘-‘,’–’,’steps’,’-.’,’:’. If a list, if its length is less than the number of spectra to plot, line_style will be cycled. If If None, use continuous lines, eg: (‘-‘,’–’,’steps’,’-.’,’:’)
  • legend (None or list of str or 'auto', optional.) – Display a legend. If ‘auto’, the title of each spectra (metadata.General.title) is used.
  • legend_picking (bool, optional.) – If true, a spectrum can be toggle on and off by clicking on the legended line.
  • fig (matplotlib figure or None, optional.) – If None, a default figure will be created.
  • **kwargs – other keyword arguments (weight and density) are described in np.histogram().

Example

Histograms of two random chi-square distributions >>> img = hs.signals.Signal2D(np.random.chisquare(1,[10,10,100])) >>> img2 = hs.signals.Signal2D(np.random.chisquare(2,[10,10,100])) >>> hs.plot.plot_histograms([img,img2],legend=[‘hist1’,’hist2’])

Returns:ax – An array is returned when style is “mosaic”.
Return type:matplotlib axes or list of matplotlib axes
hyperspy.drawing.utils.plot_images(images, cmap=None, no_nans=False, per_row=3, label='auto', labelwrap=30, suptitle=None, suptitle_fontsize=18, colorbar='multi', centre_colormap='auto', saturated_pixels=0, scalebar=None, scalebar_color='white', axes_decor='all', padding=None, tight_layout=False, aspect='auto', min_asp=0.1, namefrac_thresh=0.4, fig=None, vmin=None, vmax=None, *args, **kwargs)

Plot multiple images as sub-images in one figure.

Parameters:
  • images (list) – images should be a list of Signals (Images) to plot If any signal is not an image, a ValueError will be raised multi-dimensional images will have each plane plotted as a separate image
  • cmap (matplotlib colormap, optional) – The colormap used for the images, by default read from pyplot
  • no_nans (bool, optional) – If True, set nans to zero for plotting.
  • per_row (int, optional) – The number of plots in each row
  • label (None, str, or list of str, optional) – Control the title labeling of the plotted images. If None, no titles will be shown. If ‘auto’ (default), function will try to determine suitable titles using Signal2D titles, falling back to the ‘titles’ option if no good short titles are detected. Works best if all images to be plotted have the same beginning to their titles. If ‘titles’, the title from each image’s metadata.General.title will be used. If any other single str, images will be labeled in sequence using that str as a prefix. If a list of str, the list elements will be used to determine the labels (repeated, if necessary).
  • labelwrap (int, optional) – integer specifying the number of characters that will be used on one line If the function returns an unexpected blank figure, lower this value to reduce overlap of the labels between each figure
  • suptitle (str, optional) – Title to use at the top of the figure. If called with label=’auto’, this parameter will override the automatically determined title.
  • suptitle_fontsize (int, optional) – Font size to use for super title at top of figure
  • colorbar ({'multi', None, 'single'}) – Controls the type of colorbars that are plotted. If None, no colorbar is plotted. If ‘multi’ (default), individual colorbars are plotted for each (non-RGB) image If ‘single’, all (non-RGB) images are plotted on the same scale, and one colorbar is shown for all
  • centre_colormap ({"auto", True, False}) – If True the centre of the color scheme is set to zero. This is specially useful when using diverging color schemes. If “auto” (default), diverging color schemes are automatically centred.
  • saturated_pixels (None, scalar or list of scalar, optional, default: 0) – If list of scalar, the length should match the number of images to show. If provide in the list, set the value to 0. The percentage of pixels that are left out of the bounds. For example, the low and high bounds of a value of 1 are the 0.5% and 99.5% percentiles. It must be in the [0, 100] range.
  • scalebar ({None, 'all', list of ints}, optional) – If None (or False), no scalebars will be added to the images. If ‘all’, scalebars will be added to all images. If list of ints, scalebars will be added to each image specified.
  • scalebar_color (str, optional) – A valid MPL color string; will be used as the scalebar color
  • axes_decor ({'all', 'ticks', 'off', None}, optional) – Controls how the axes are displayed on each image; default is ‘all’ If ‘all’, both ticks and axis labels will be shown If ‘ticks’, no axis labels will be shown, but ticks/labels will If ‘off’, all decorations and frame will be disabled If None, no axis decorations will be shown, but ticks/frame will
  • padding (None or dict, optional) –

    This parameter controls the spacing between images. If None, default options will be used Otherwise, supply a dictionary with the spacing options as keywords and desired values as values Values should be supplied as used in pyplot.subplots_adjust(), and can be:

    ’left’, ‘bottom’, ‘right’, ‘top’, ‘wspace’ (width), and ‘hspace’ (height)
  • tight_layout (bool, optional) – If true, hyperspy will attempt to improve image placement in figure using matplotlib’s tight_layout If false, repositioning images inside the figure will be left as an exercise for the user.
  • aspect (str or numeric, optional) – If ‘auto’, aspect ratio is auto determined, subject to min_asp. If ‘square’, image will be forced onto square display. If ‘equal’, aspect ratio of 1 will be enforced. If float (or int/long), given value will be used.
  • min_asp (float, optional) – Minimum aspect ratio to be used when plotting images
  • namefrac_thresh (float, optional) – Threshold to use for auto-labeling. This parameter controls how much of the titles must be the same for the auto-shortening of labels to activate. Can vary from 0 to 1. Smaller values encourage shortening of titles by auto-labeling, while larger values will require more overlap in titles before activing the auto-label code.
  • fig (mpl figure, optional) – If set, the images will be plotted to an existing MPL figure
  • vmax (vmin,) – If list of scalar, the length should match the number of images to show. A list of scalar is not compatible with a single colorbar. See vmin, vmax of matplotlib.imshow() for more details.
  • **kwargs, optional (*args,) –

    Additional arguments passed to matplotlib.imshow()

Returns:

axes_list – a list of subplot axes that hold the images

Return type:

list

See also

plot_spectra()
Plotting of multiple spectra
plot_signals()
Plotting of multiple signals
plot_histograms()
Compare signal histograms

Notes

interpolation is a useful parameter to provide as a keyword argument to control how the space between pixels is interpolated. A value of 'nearest' will cause no interpolation between pixels.

tight_layout is known to be quite brittle, so an option is provided to disable it. Turn this option off if output is not as expected, or try adjusting label, labelwrap, or per_row

hyperspy.drawing.utils.plot_signals(signal_list, sync=True, navigator='auto', navigator_list=None, **kwargs)

Plot several signals at the same time.

Parameters:
  • signal_list (list of BaseSignal instances) – If sync is set to True, the signals must have the same navigation shape, but not necessarily the same signal shape.
  • sync (True or False, default "True") – If True: the signals will share navigation, all the signals must have the same navigation shape for this to work, but not necessarily the same signal shape.
  • navigator ({"auto", None, "spectrum", "slider", BaseSignal}, default "auto") – See signal.plot docstring for full description
  • navigator_list ({List of navigator arguments, None}, default None) – Set different navigator options for the signals. Must use valid navigator arguments: “auto”, None, “spectrum”, “slider”, or a hyperspy Signal. The list must have the same size as signal_list. If None, the argument specified in navigator will be used.
  • **kwargs – Any extra keyword arguments are passed to each signal plot method.

Example

>>> s_cl = hs.load("coreloss.dm3")
>>> s_ll = hs.load("lowloss.dm3")
>>> hs.plot.plot_signals([s_cl, s_ll])

Specifying the navigator:

>>> s_cl = hs.load("coreloss.dm3")
>>> s_ll = hs.load("lowloss.dm3")
>>> hs.plot.plot_signals([s_cl, s_ll], navigator="slider")

Specifying the navigator for each signal:

>>> s_cl = hs.load("coreloss.dm3")
>>> s_ll = hs.load("lowloss.dm3")
>>> s_edx = hs.load("edx.dm3")
>>> s_adf = hs.load("adf.dm3")
>>> hs.plot.plot_signals(
        [s_cl, s_ll, s_edx], navigator_list=["slider",None,s_adf])
hyperspy.drawing.utils.plot_spectra(spectra, style='overlap', color=None, line_style=None, padding=1.0, legend=None, legend_picking=True, legend_loc='upper right', fig=None, ax=None, **kwargs)

Plot several spectra in the same figure.

Extra keyword arguments are passed to matplotlib.figure.

Parameters:
  • spectra (iterable object) – Ordered spectra list to plot. If style is “cascade” or “mosaic” the spectra can have different size and axes.
  • style ({'overlap', 'cascade', 'mosaic', 'heatmap'}) – The style of the plot.
  • color (matplotlib color or a list of them or None) – Sets the color of the lines of the plots (no action on ‘heatmap’). If a list, if its length is less than the number of spectra to plot, the colors will be cycled. If None, use default matplotlib color cycle.
  • line_style (matplotlib line style or a list of them or None) – Sets the line style of the plots (no action on ‘heatmap’). The main line style are ‘-‘,’–’,’steps’,’-.’,’:’. If a list, if its length is less than the number of spectra to plot, line_style will be cycled. If If None, use continuous lines, eg: (‘-‘,’–’,’steps’,’-.’,’:’)
  • padding (float, optional, default 0.1) – Option for “cascade”. 1 guarantees that there is not overlapping. However, in many cases a value between 0 and 1 can produce a tighter plot without overlapping. Negative values have the same effect but reverse the order of the spectra without reversing the order of the colors.
  • legend (None or list of str or 'auto') – If list of string, legend for “cascade” or title for “mosaic” is displayed. If ‘auto’, the title of each spectra (metadata.General.title) is used.
  • legend_picking (bool) – If true, a spectrum can be toggle on and off by clicking on the legended line.
  • legend_loc (str or int) – This parameter controls where the legend is placed on the figure; see the pyplot.legend docstring for valid values
  • fig (matplotlib figure or None) – If None, a default figure will be created. Specifying fig will not work for the ‘heatmap’ style.
  • ax (matplotlib ax (subplot) or None) – If None, a default ax will be created. Will not work for ‘mosaic’ or ‘heatmap’ style.
  • **kwargs – remaining keyword arguments are passed to matplotlib.figure() or matplotlib.subplots(). Has no effect on ‘heatmap’ style.

Example

>>> s = hs.load("some_spectra")
>>> hs.plot.plot_spectra(s, style='cascade', color='red', padding=0.5)

To save the plot as a png-file

>>> hs.plot.plot_spectra(s).figure.savefig("test.png")
Returns:ax – An array is returned when style is “mosaic”.
Return type:matplotlib axes or list of matplotlib axes
hyperspy.drawing.utils.set_axes_decor(ax, axes_decor)
hyperspy.drawing.utils.set_xaxis_lims(mpl_ax, hs_axis)

Set the matplotlib axis limits to match that of a HyperSpy axis

Parameters:
  • mpl_ax (matplotlib.axis.Axis) – The matplotlib axis to change
  • hs_axis (DataAxis) – The data axis that contains the values that control the scaling
hyperspy.drawing.utils.subplot_parameters(fig)

Returns a list of the subplot parameters of a mpl figure.

Parameters:fig (mpl figure) –
Returns:tuple
Return type:(left, bottom, right, top, wspace, hspace)

hyperspy.drawing.widget module

class hyperspy.drawing.widget.DraggableWidgetBase(axes_manager, **kwargs)

Bases: hyperspy.drawing.widget.WidgetBase

Adds the position and indices properties, and adds a framework for letting the user drag the patch around. Also adds the moved event.

The default behavior is that position snaps to the values corresponding to the values of the axes grid (i.e. no subpixel values). This behavior can be controlled by the property snap_position.

Any inheritors must override these methods:
_onmousemove(self, event) _update_patch_position(self) _set_patch(self)
button_release(event)

whenever a mouse button is released

connect(ax)

Connect to the matplotlib Axes’ events.

indices
onpick(event)
position
snap_position
class hyperspy.drawing.widget.ResizableDraggableWidgetBase(axes_manager, **kwargs)

Bases: hyperspy.drawing.widget.DraggableWidgetBase

Adds the size property and get_size_in_axes method, and adds a framework for letting the user resize the patch, including resizing by key strokes (‘+’, ‘-‘). Also adds the ‘resized’ event.

Utility functions for resizing are implemented by increase_size and decrease_size, which will in-/decrement the size by 1. Other utility functions include get_centre and get_centre_indices which returns the center position, and the internal _apply_changes which helps make sure that only one ‘changed’ event is fired for a combined move and resize.

Any inheritors must override these methods:
_update_patch_position(self) _update_patch_size(self) _update_patch_geometry(self) _set_patch(self)
button_release(event)

whenever a mouse button is released

connect(ax)

Connect to the matplotlib Axes’ events.

decrease_size()

Decrement all sizes by 1. Applied via ‘size’ property.

get_centre()

Get’s the center indices. The default implementation is simply the position + half the size in axes space, which should work for any symmetric widget, but more advanced widgets will need to decide whether to return the center of gravity or the geometrical center of the bounds.

get_centre_index()

Get’s the center position (in index space). The default implementation is simply the indices + half the size, which should work for any symmetric widget, but more advanced widgets will need to decide whether to return the center of gravity or the geometrical center of the bounds.

get_size_in_indices()

Gets the size property converted to the index space (via ‘axes’ attribute).

increase_size()

Increment all sizes by 1. Applied via ‘size’ property.

on_key_press(event)
onpick(event)
set_size_in_indices(value)

Sets the size property converted to the index space (via ‘axes’ attribute).

size
snap_all
snap_size
class hyperspy.drawing.widget.ResizersMixin(resizers=True, **kwargs)

Bases: object

Widget mix-in for adding resizing manipulation handles.

The default handles are green boxes displayed on the outside corners of the boundaries. By default, the handles are only displayed when the widget is selected (picked in matplotlib terminology).

resizers : {bool}
Property that determines whether the resizer handles should be used
resize_color : {matplotlib color}
The color of the resize handles.
resize_pixel_size : {tuple | None}
Size of the resize handles in screen pixels. If None, it is set equal to the size of one ‘data-pixel’ (image pixel size).
resizer_picked : {False | int}
Inidcates which, if any, resizer was selected the last time the widget was picked. False if another patch was picked, or the index of the resizer handle that was picked.
onpick(event)

Picking of main patch is same as for widget base, but this also handles picking of the resize handles. If a resize handles is picked, picked is set to True, and resizer_picked is set to an integer indicating which handle was picked (0-3 for top left, top right, bottom left, bottom right). It is set to False if another widget was picked.

If the main patch is picked, the offset from the picked pixel to the position is stored in pick_offset. This can be used in e.g. _onmousemove to ease dragging code (prevent widget center/corner snapping to mouse).

resizers
set_on(value)

Turns on/off resizers whet widget is turned on/off.

class hyperspy.drawing.widget.Widget1DBase(axes_manager, **kwargs)

Bases: hyperspy.drawing.widget.DraggableWidgetBase

A base class for 1D widgets.

It sets the right dimensions for size and position, adds the ‘border_thickness’ attribute and initalizes the ‘axes’ attribute to the first two navigation axes if possible, if not, the two first signal_axes are used. Other than that it mainly supplies common utility functions for inheritors, and implements required functions for ResizableDraggableWidgetBase.

The implementation for ResizableDraggableWidgetBase methods all assume that a Rectangle patch will be used, centered on position. If not, the inheriting class will have to override those as applicable.

class hyperspy.drawing.widget.Widget2DBase(axes_manager, **kwargs)

Bases: hyperspy.drawing.widget.ResizableDraggableWidgetBase

A base class for 2D widgets. It sets the right dimensions for size and position, adds the ‘border_thickness’ attribute and initalizes the ‘axes’ attribute to the first two navigation axes if possible, if not, the two first signal_axes are used. Other than that it mainly supplies common utility functions for inheritors, and implements required functions for ResizableDraggableWidgetBase.

The implementation for ResizableDraggableWidgetBase methods all assume that a Rectangle patch will be used, centered on position. If not, the inheriting class will have to override those as applicable.

class hyperspy.drawing.widget.WidgetBase(axes_manager=None, **kwargs)

Bases: object

Base class for interactive widgets/patches. A widget creates and maintains one or more matplotlib patches, and manages the interaction code so that the user can maniuplate it on the fly.

This base class implements functionality witch is common to all such widgets, mainly the code that manages the patch, axes management, and sets up common events (‘changed’ and ‘closed’).

Any inherting subclasses must implement the following methods:
_set_patch(self) _on_navigate(obj, name, old, new) # Only for widgets that can navigate

It should also make sure to fill the ‘axes’ attribute as early as possible (but after the base class init), so that it is available when needed.

axes
close(window=None)

Set the on state to off (removes patch and disconnects), and trigger events.closed.

connect(ax)

Connect to the matplotlib Axes’ events.

connect_navigate()

Connect to the axes_manager such that changes in the widget or in the axes_manager are reflected in the other.

disconnect()

Disconnect from all events (both matplotlib and navigation).

disconnect_navigate()

Disconnect a previous naivgation connection.

draw_patch(*args)

Update the patch drawing.

is_on()

Determines if the widget is set to draw if valid (turned on).

select()

Cause this widget to be the selected widget in its MPL axes. This assumes that the widget has its patch added to the MPL axes.

set_mpl_ax(ax)

Set the matplotlib Axes that the widget will draw to. If the widget on state is True, it will also add the patch to the Axes, and connect to its default events.

set_on(value)

Change the on state of the widget. If turning off, all patches will be removed from the matplotlib axes and the widget will disconnect from all events. If turning on, the patch(es) will be added to the matplotlib axes, and the widget will connect to its default events.

hyperspy.drawing.widgets module

Interactive widgets that can be added to Signal plots.

Example

Module contents