hyperspy.api.plot
#
Markers that can be added to |
|
|
Plot the histogram of every signal in the list in one figure. |
|
Plot multiple images either as sub-images or overlayed in one figure. |
|
Plot one or multiple ROI maps of a |
|
Plot several signals at the same time. |
|
Plot several spectra in the same figure. |
Plotting funtions.
Functions:
- plot_images
Plot multiple images in the same figure.
- plot_spectra
Plot multiple spectra in the same figure.
- plot_signals
Plot multiple signals at the same time.
- plot_histograms
Compute and plot the histograms of multiple signals in the same figure.
- plot_roi_map
Plot a the spatial variation of a signal sliced by a ROI in the signal space.
The hyperspy.api.plot
module contains the following submodules:
hyperspy.api.plot.markers
Markers that can be added to
BaseSignal
figure.
- hyperspy.api.plot.plot_histograms(signal_list, bins='fd', range_bins=None, color=None, linestyle=None, legend='auto', fig=None, ax=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_listiterable
Ordered list of spectra to plot. If
style
is"cascade"
or"mosaic"
, the spectra can have different size and axes.- bins
int
or sequence offloat
orstr
, default “fd” If
bins
is an int, it defines the number of equal-width bins in the given range. Ifbins
is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths.If
bins
is a string from the list below, will use the method chosen to calculate the optimal bin width and consequently the number of bins (see Notes for more detail on the estimators) from the data that falls within the requested range. While the bin width will be optimal for the actual data in the range, the number of bins will be computed to fill the entire range, including the empty portions. For visualisation, using the'auto'
option is suggested. Weighted data is not supported for automated bin size selection.Possible strings are:
'auto'
: Maximum of the ‘sturges’ and ‘fd’ estimators. Provides good all around performance.'fd'
: Freedman Diaconis Estimator, robust (resilient to outliers) estimator that takes into account data variability and data size.'doane'
: An improved version of Sturges’ estimator that works better with non-normal datasets.'scott'
: Less robust estimator that that takes into account data variability and data size.'stone'
: Estimator based on leave-one-out cross-validation estimate of the integrated squared error. Can be regarded as a generalization of Scott’s rule.'rice'
: Estimator does not take variability into account, only data size. Commonly overestimates number of bins required.'sturges'
: R’s default method, only accounts for data size. Only optimal for gaussian data and underestimates number of bins for large non-gaussian datasets.'sqrt'
: Square root (of data size) estimator, used by Excel and other programs for its speed and simplicity.'knuth'
: Knuth’s rule is a fixed-width, Bayesian approach to determining the optimal bin width of a histogram.'blocks'
: Determination of optimal adaptive-width histogram bins using the Bayesian Blocks algorithm.
- range_bins(
float
,float
), optional The lower and upper limit of the range of bins. If not provided, range is simply
(a.min(), a.max())
. Values outside the range are ignored. The first element of the range must be less than or equal to the second. range affects the automatic bin computation as well. While bin width is computed to be optimal based on the actual data within range, the bin count will fill the entire range including portions containing no data.- color
None
, (list
of) matplotlib color, 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
, (list
of) matplotlib line style, 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
ofstr
,'auto'
, default'auto'
Display a legend. If ‘auto’, the title of each spectra (metadata.General.title) is used.
- legend_pickingbool, default
True
If True, a spectrum can be toggled on and off by clicking on the line in the legend.
- fig
None
,matplotlib.figure.Figure
, defaultNone
If None (default), a default figure will be created.
- **kwargs
other keyword arguments (weight and density) are described in
numpy.histogram()
.
- Returns:
matplotlib.axes.Axes
orlist
ofmatplotlib.axes.Axes
An array is returned when
style='mosaic'
.
Examples
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']) <Axes: xlabel='value (<undefined>)', ylabel='Intensity'>
- hyperspy.api.plot.plot_images(images, cmap=None, no_nans=False, per_row=3, label='auto', labelwrap=30, suptitle=None, suptitle_fontsize=18, colorbar='default', 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, ax=None, vmin=None, vmax=None, overlay=False, colors='auto', alphas=1.0, legend_picking=True, legend_loc='upper right', pixel_size_factor=None, **kwargs)#
Plot multiple images either as sub-images or overlayed in one figure.
- Parameters:
- images
list
ofSignal2D
orBaseSignal
images should be a list of Signals to plot. For
BaseSignal
with navigation dimensions 2 and signal dimension 0, the signal will be transposed 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
None
, (list
of)matplotlib.colors.Colormap
orstr
, defaultNone
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 defaultmatplotlib
colors (to match with the default output of theplot_spectra()
method). Note: if using more than one colormap, using the'single'
option forcolorbar
is disallowed.- no_nansbool, optional
If True, set nans to zero for plotting.
- per_row
int
, optional The number of plots in each row.
- label
None
,str
,list
ofstr
, 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‘default’, ‘multi’, ‘single’,
None
, optional Controls the type of colorbars that are plotted, incompatible with
overlay=True
. If ‘default’, same as ‘multi’ whenoverlay=False
, otherwise same asNone
. If ‘multi’, 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. If None, no colorbar is plotted.- centre_colormap‘auto’,
True
,False
, optional 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
ofint
, 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_layoutbool, 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
,float
,int
, 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
matplotlib.figure.Figure
, defaultNone
If set, the images will be plotted to an existing matplotlib figure. If the parameter
ax
is provided, this parameter will be ignored and the figure will be obtained from theax
parameter.- ax
matplotlib.axes.Axes
orlist
ofmatplotlib.axes.Axes
, defaultNone
The matplotlib axes to use to display the images. When using overlay=True, ax must be a matplotlib axis. If None, new matplotlib axes will be created as required.
- vmin, 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 or integer, keep this value as bounds. Note: vmin is ignored when overlaying images.- overlaybool, optional
If True, overlays the images with different colors rather than plotting each image as a subplot.
- colors‘auto’,
list
ofstr
, optional If list, it must contains colors acceptable to matplotlib [1]. If
'auto'
, colors will be taken from matplotlib.colors.BASE_COLORS.- alphas
float
orlist
offloat
, optional Float value or a list of floats corresponding to the alpha value of each color.
- legend_picking: bool, optional
If True (default), an image can be toggled on and off by clicking on the legended line. For
overlay=True
only.- legend_loc
str
,int
, optional This parameter controls where the legend is placed on the figure see the
matplotlib.pyplot.legend()
docstring for valid values- pixel_size_factor
None
,int
orfloat
, optional If
None
(default), the size of the figure is taken from the matplotlibrcParams
. Otherwise sets the size of the figure when plotting an overlay image. The higher the number the larger the figure and therefore a greater number of pixels are used. This value will be ignored if a Figure is provided.- **kwargs, optional
Additional keyword arguments passed to
matplotlib.pyplot.imshow()
.
- images
- Returns:
- axes_list
list
A list of subplot axes that hold the images.
- axes_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.
References
[1]Matplotlib colors API: https://matplotlib.org/stable/api/colors_api.html.
- hyperspy.api.plot.plot_roi_map(signal, rois=1, color=None, cmap=None, single_figure=False, single_figure_kwargs=None, **kwargs)#
Plot one or multiple ROI maps of a
signal
.Uses regions of interest (ROIs) to select ranges along the signal axis.
For each ROI, a plot is generated of the summed data values within this signal ROI at each point in the
signal
’s navigation space.The ROIs can be moved interactively and the corresponding map plots will update automatically.
- Parameters:
- signal
BaseSignal
The signal to inspect.
- rois
int
, subclass ofhyperspy.roi.BaseROI
orlist
ofhyperspy.roi.BaseROI
ROIs to slice the signal in signal space. If
int
, define the number of ROIs to use.- color
list
ofstr
orNone
Color of the ROIs. Any string supported by matplotlib to define a color can be used. The length of the list must be equal to the number ROIs. If None (default), the default matplotlib colors are used.
- cmap
str
oflist
ofstr
orNone
Only for signals with navigation dimension of 2. Define the colormap of the map(s). If string, any string supported by matplotlib to define a colormap can be used and a colored frame matching the ROI color will be added to the map. If list of str, it must be the same length as the ROIs. If None (default), the colors from the
color
argument are used and no colored frame is added.- single_figurebool
Whether to plot on a single figure or several figures. If True,
plot_images()
orplot_spectra()
will be used, depending on the navigation dimension of the signal.- single_figure_kwargs
dict
,None
Only when
single_figure=True
. Keywords arguments are passed toplot_images()
orplot_spectra()
depending on the navigation dimension of the signal. If None, defaultkwargs
are used with the following changesscalebar=[0]
,axes_decor="off"
andsuptitle=""
.- **kwargs
dict
The keyword argument are passed to
plot()
.
- signal
- Returns:
- rois
list
ofhyperspy.roi.BaseROI
The ROI objects that slice
signal
.- roi_sums
BaseSignal
The sums of the signals defined by the ROIs.
- rois
Notes
Performance consideration:
RectangularROI
is ~2x faster thanCircleROI
.If the data sliced by the ROI contains
numpy.nan
,numpy.nansum()
will be used instead ofnumpy.sum()
at the cost of a speed penalty (more than 2 times slower).Plotting ROI maps on a single figure is slower than on separate figures.
Examples
3D hyperspectral data
For 3D hyperspectral data, the ROIs used will be instances of
SpanROI
. Therefore, these ROIs can be used to select particular spectral ranges, e.g. a particular peak.The map generated for a given ROI is therefore the sum of this spectral region at each point in the hyperspectral map. Therefore, regions of the sample where this peak is bright will be bright in this map.
4D STEM
For 4D STEM data, by default, the ROIs used will be instances of
RectangularROI
. Other hyperspy ROIs, such asCircleROI
can be used. These ROIs can be used to select particular regions in reciprocal space, e.g. a particular diffraction spot.The map generated for a given ROI is the intensity of this region at each point in the scan. Therefore, regions of the scan where a particular spot is intense will appear bright.
- hyperspy.api.plot.plot_signals(signal_list, sync=True, navigator='auto', navigator_list=None, **kwargs)#
Plot several signals at the same time.
- Parameters:
- signal_list
list
ofBaseSignal
If sync is set to True, the signals must have the same navigation shape, but not necessarily the same signal shape.
- syncbool, optional
If True (default), 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
None
,BaseSignal
orstr
- {``’auto’`` | ``’spectrum’`` | ``’slider’`` }, default ``”auto”``
See signal.plot docstring for full description.
- navigator_list
None
,list
ofBaseSignal
orlist
ofstr
, defaultNone
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
dict
Any extra keyword arguments are passed to each signal
plot
method.
- signal_list
Examples
>>> s1 = hs.signals.Signal1D(np.arange(100).reshape((10, 10))) >>> s2 = hs.signals.Signal1D(np.arange(100).reshape((10, 10)) * -1) >>> hs.plot.plot_signals([s1, s2])
Specifying the navigator:
>>> hs.plot.plot_signals([s1, s2], navigator="slider")
Specifying the navigator for each signal:
>>> s3 = hs.signals.Signal1D(np.ones((10, 10))) >>> s_nav = hs.signals.Signal1D(np.ones((10))) >>> hs.plot.plot_signals( ... [s1, s2, s3], navigator_list=["slider", None, s_nav] ... )
- hyperspy.api.plot.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, normalise=False, **kwargs)#
Plot several spectra in the same figure.
- Parameters:
- spectra
list
ofSignal1D
orBaseSignal
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 transposed to form aSignal1D
.- style{
'overlap'
|'cascade'
|'mosaic'
|'heatmap'
}, default ‘overlap’ The style of the plot: ‘overlap’ (default), ‘cascade’, ‘mosaic’, or ‘heatmap’.
- color
None
or (list
of) matplotlib color, defaultNone
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 (default), use default matplotlib color cycle.
- linestyle
None
or (list
of) matplotlib line style, defaultNone
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'
. Seematplotlib.lines.Line2D.set_drawstyle()
for more information. The'default'
value is defined by matplotlib.- padding
float
, 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
ofstr
,'auto'
, defaultNone
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. Default None.
- legend_pickingbool, default
True
If True (default), a spectrum can be toggled on and off by clicking on the legended line.
- legend_loc
str
orint
, optional This parameter controls where the legend is placed on the figure; see the pyplot.legend docstring for valid values. Default
'upper right'
.- fig
None
,matplotlib.figure.Figure
, defaultNone
If None (default), a default figure will be created. Not supported for the
'heatmap'
style.- ax
None
,matplotlib.axes.Axes
, defaultNone
If None (default), matplotlib axes will be created when necessary. Not supported for the
'heatmap'
style.- auto_updatebool or
None
, defaultNone
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’.
- normalisebool, default
False
If True, the data are normalised to the [0, 1] interval in the plot.
- **kwargs
dict
Depending on the style used, the keyword arguments are passed to different functions
"overlap"
,"cascade"
or"mosiac"
: arguments passed tomatplotlib.pyplot.figure()
"heatmap"
: arguments passed toplot()
.
- spectra
- Returns:
matplotlib.axes.Axes
orlist
ofmatplotlib.axes.Axes
An array is returned when style is ‘mosaic’.
Examples
>>> s = hs.signals.Signal1D(np.arange(100).reshape((10, 10))) >>> hs.plot.plot_spectra(s, style='cascade', color='red', padding=0.5) <Axes: xlabel='<undefined> (<undefined>)'>
To save the plot as a png-file
>>> ax = hs.plot.plot_spectra(s) >>> ax.figure.savefig("test.png")