hyperspy.drawing.utils module

hyperspy.drawing.utils.animate_legend(fig=None, ax=None)

Animate the legend of a figure.

A spectrum can be toggled on and off by clicking on the line in the legend.

Parameters
  • fig ({None, matplotlib.figure}, optional) – If None pick the current figure using “plt.gcf”.

  • ax ({None, matplotlib.axes}, optional) – If None pick the current axes using “plt.gca”.

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
  • vmin (scalar) – The range of data to display.

  • vmax (scalar) – 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, vmin=None, vmax=None)

Estimate bounds of the data to display.

Parameters
  • data (numpy array) –

  • vmin (scalar, str, None) – If str, formatted as ‘xth’, use this value to calculate the percentage of pixels that are left out of the lower and upper bounds. For example, for a vmin of ‘1th’, 1% of the lowest will be ignored to estimate the minimum value. Similarly, for a vmax value of ‘1th’, 1% of the highest value will be ignored in the estimation of the maximum value. See numpy.percentile() for more explanation. If None, use the percentiles value set in the preferences. If float of integer, keep this value as bounds.

  • vmax (scalar, str, None) – If str, formatted as ‘xth’, use this value to calculate the percentage of pixels that are left out of the lower and upper bounds. For example, for a vmin of ‘1th’, 1% of the lowest will be ignored to estimate the minimum value. Similarly, for a vmax value of ‘1th’, 1% of the highest value will be ignored in the estimation of the maximum value. See numpy.percentile() for more explanation. If None, use the percentiles value set in the preferences. If float of integer, keep this value as bounds.

Returns

vmin, vmax – The low and high bounds.

Return type

scalar

Raises

ValueError – if the value of vmin vmax is out of the valid range for percentile calculation (in case of string values).

hyperspy.drawing.utils.create_figure(window_title=None, _on_figure_window_close=None, disable_xyscale_keys=False, **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 ({None, string}, optional) –

  • _on_figure_window_close ({None, function}, optional) –

  • disable_xyscale_keys (bool, optional) – Disable the k, l and L shortcuts which toggle the x or y axis between linear and log scale. Default False.

Returns

fig

Return type

plt.figure

hyperspy.drawing.utils.make_cmap(colors, name='my_colormap', position=None, bit=False, register=True)

Create a matplotlib colormap with customized colors, optionally registering it with matplotlib for simplified use.

Adapted from Chris Slocum’s code at: https://github.com/CSlocumWX/custom_colormap/blob/master/custom_colormaps.py and used under the terms of that code’s BSD-3 license

Parameters
  • colors (iterable) – list of either tuples containing rgb values, or html strings Colors should be arranged so that the first color is the lowest value for the colorbar and the last is the highest.

  • name (str) – name of colormap to use when registering with matplotlib

  • position ({None, iterable}, optional) – list containing the values (from [0,1]) that dictate the position of each color within the colormap. If None (default), the colors will be equally-spaced within the colorbar.

  • bit (bool, optional) – True if RGB colors are given in 8-bit [0 to 255] or False if given in arithmetic basis [0 to 1] (default).

  • register (bool, optional) – Wwitch to control whether or not to register the custom colormap with matplotlib in order to enable use by just the name string.

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'}, optional) –

  • dont_plot (bool, optional) – Default False.

Returns

array

Return type

RGB matrix

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

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

This function creates a histogram for each signal and plots the list with the plot_spectra() function.

Parameters
  • signal_list (iterable) – Ordered list of spectra to plot. If style is "cascade" or "mosaic", the spectra can have different size and axes.

  • bins ({int, list, str}, optional) –

    If bins is a string, then it must be one of:

    • 'knuth' : use Knuth’s rule to determine bins,

    • 'scott' : use Scott’s rule to determine bins,

    • 'fd' : use the Freedman-diaconis rule to determine bins,

    • 'blocks' : use bayesian blocks for dynamic bin widths.

  • range_bins ({None, tuple}, optional) – The minimum and maximum range for the histogram. If not specified, it will be (x.min(), x.max()).

  • color ({None, valid matplotlib color, list of colors}, optional) – Sets the color of the lines of the plots. For 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.

  • linestyle ({None, valid matplotlib line style, list of line styles},) – optional The main line styles are '-', '--', '-.', ':'. For a list, if its length is less than the number of spectra to plot, linestyle will be cycled. If None, use continuous lines (same as '-').

  • legend ({None, list of str, '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 toggled on and off by clicking on the line in the legend.

  • fig ({None, matplotlib figure}, optional) – If None, a default figure will be created.

  • **kwargs – other keyword arguments (weight and density) are described in numpy.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', 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, **kwargs)

Plot multiple images as sub-images in one figure.

Parameters
  • images (list of Signal2D or BaseSignal) – images should be a list of Signals to plot. For BaseSignal with navigation dimensions 2 and signal dimension 0, the signal will be tranposed to form a Signal2D. Multi-dimensional images will have each plane plotted as a separate image. If any of the signal shapes is not suitable, a ValueError will be raised.

  • cmap ({matplotlib colormap, list, 'mpl_colors'}, optional) – The colormap used for the images, by default uses the setting color map signal from the plot preferences. A list of colormaps can also be provided, and the images will cycle through them. Optionally, the value 'mpl_colors' will cause the cmap to loop through the default matplotlib colors (to match with the default output of the plot_spectra() method). Note: if using more than one colormap, using the 'single' option for colorbar is disallowed.

  • 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, 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 figures.

  • 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 particularly useful when using diverging color schemes. If “auto” (default), diverging color schemes are automatically centred.

  • 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, 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 matplotlib.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, 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

  • vmin (scalar, str, None) – If str, formatted as ‘xth’, use this value to calculate the percentage of pixels that are left out of the lower and upper bounds. For example, for a vmin of ‘1th’, 1% of the lowest will be ignored to estimate the minimum value. Similarly, for a vmax value of ‘1th’, 1% of the highest value will be ignored in the estimation of the maximum value. It must be in the range [0, 100] See numpy.percentile() for more explanation. If None, use the percentiles value set in the preferences. If float of integer, keep this value as bounds.

  • vmax (scalar, str, None) – If str, formatted as ‘xth’, use this value to calculate the percentage of pixels that are left out of the lower and upper bounds. For example, for a vmin of ‘1th’, 1% of the lowest will be ignored to estimate the minimum value. Similarly, for a vmax value of ‘1th’, 1% of the highest value will be ignored in the estimation of the maximum value. It must be in the range [0, 100] See numpy.percentile() for more explanation. If None, use the percentiles value set in the preferences. If float of integer, keep this value as bounds.

  • **kwargs – Additional keyword arguments passed to matplotlib.imshow()

  • optional – Additional keyword 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, False}, default "True", optional) – 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}, optional,) –

  • "auto" (default) – See signal.plot docstring for full description.

  • navigator_list ({None, list of navigator arguments}, optional, 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, linestyle=None, drawstyle='default', padding=1.0, legend=None, legend_picking=True, legend_loc='upper right', fig=None, ax=None, auto_update=None, **kwargs)

Plot several spectra in the same figure.

Parameters
  • spectra (list of Signal1D or BaseSignal) – Ordered spectra list of signal to plot. If style is “cascade” or “mosaic”, the spectra can have different size and axes. For BaseSignal with navigation dimensions 1 and signal dimension 0, the signal will be tranposed to form a Signal1D.

  • style ({'overlap', 'cascade', 'mosaic', 'heatmap'}) – The style of the plot.

  • color ({None, matplotlib color, list of colors}, optional) – Sets the color of the lines of the plots (no action on ‘heatmap’). For 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.

  • linestyle ({None, matplotlib line style, list of linestyles}, optional) – Sets the line style of the plots (no action on ‘heatmap’). The main line style are '-', '--', '-.', ':'. For a list, if its length is less than the number of spectra to plot, linestyle will be cycled. If None, use continuous lines (same as '-').

  • drawstyle ({'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'},) – default ‘default’ The drawstyle determines how the points are connected, no action with style='heatmap'. See matplotlib.lines.Line2D.set_drawstyle() for more information. The 'default' value is defined by matplotlib.

  • padding (float, optional, default 1.0) – Option for “cascade”. 1 guarantees that there is no 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, list of str, 'auto'}, optional) – 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, optional) – If True (default), a spectrum can be toggled on and off by clicking on the legended line.

  • legend_loc ({str, int}, optional) – This parameter controls where the legend is placed on the figure; see the pyplot.legend docstring for valid values

  • fig ({None, matplotlib figure}, optional) – If None, a default figure will be created. Specifying fig will not work for the ‘heatmap’ style.

  • ax ({none, matplotlib ax (subplot)}, optional) – If None, a default ax will be created. Will not work for ‘mosaic’ or ‘heatmap’ style.

  • auto_update (bool or None) – If True, the plot will update when the data are changed. Only supported with style=’overlap’ and a list of signal with navigation dimension 0. If None (default), update the plot only for style=’overlap’.

  • **kwargs – Keywords arguments passed to matplotlib.pyplot.figure() or matplotlib.pyplot.subplots() if style=’mosaic’. Has no effect on ‘heatmap’ style.

  • optional – Keywords arguments passed to matplotlib.pyplot.figure() or matplotlib.pyplot.subplots() if style=’mosaic’. 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_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 which 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)