hyperspy.api.plot.markers#

hyperspy.api.plot.markers.Arrows(offsets, U, V)

A set of Arrow markers based on the matplotlib.quiver.Quiver class.

hyperspy.api.plot.markers.Circles(offsets, sizes)

A set of Circle Markers.

hyperspy.api.plot.markers.Ellipses(offsets, ...)

A set of Ellipse Markers

hyperspy.api.plot.markers.HorizontalLines(...)

A set of HorizontalLines markers

hyperspy.api.plot.markers.Lines(segments[, ...])

A set of Line Segments Markers.

hyperspy.api.plot.markers.Markers(collection)

A set of markers using Matplotlib collections.

hyperspy.api.plot.markers.Points(offsets[, ...])

A set of Points Markers.

hyperspy.api.plot.markers.Polygons(verts[, ...])

A Collection of Rectangles Markers

hyperspy.api.plot.markers.Rectangles(...[, ...])

A Collection of Rectangles Markers

hyperspy.api.plot.markers.Squares(offsets, ...)

A Collection of square markers.

hyperspy.api.plot.markers.Texts(offsets[, ...])

A set of text markers

hyperspy.api.plot.markers.VerticalLines(...)

A set of Vertical Line Markers

Markers that can be added to BaseSignal plots.

Examples

>>> import skimage
>>> im = hs.signals.Signal2D(skimage.data.camera())
>>> m = hs.plot.markers.Rectangles(
...    offsets=[10, 15],
...    widths=(5,),
...    heights=(7,),
...    angles=(0,),
...    color="red",
...    )
>>> im.add_marker(m)
class hyperspy.api.plot.markers.Arrows(offsets, U, V, C=None, scale=1, angles='xy', scale_units='xy', **kwargs)#

Bases: Markers

A set of Arrow markers based on the matplotlib.quiver.Quiver class.

Initialize the set of Arrows Markers.

Parameters:
offsetsarray_like

The positions [x, y] of the center of the marker. If the offsets are not provided, the marker will be placed at the current navigation position.

Uarray_like

The change in x (horizontal) diraction for the arrows.

Varray_like

The change in y (vertical) diraction for the arrows.

Carray_like or None
kwargsdict

Keyword arguments are passed to matplotlib.quiver.Quiver.

update()#

Update the markers on the plot.

class hyperspy.api.plot.markers.Circles(offsets, sizes, offset_transform='data', units='x', facecolors='none', **kwargs)#

Bases: Markers

A set of Circle Markers.

Create a set of Circle Markers.

Parameters:
offsetsarray_like

The positions [x, y] of the center of the marker. If the offsets are not provided, the marker will be placed at the current navigation position.

sizesnumpy.ndarray

The size of the circles in units defined by the argument units.

facecolorsmatplotlib color or list of color

Set the facecolor(s) of the markers. It can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is ‘none’, the patch will not be filled.

units{"points", "inches", "dots", "width"”, "height", "x", "y", "xy"}

The units in which majors and minors are given; "width" and "height" refer to the dimensions of the axes, while "x" and "y" refer to the offsets data units. "xy" differs from all others in that the angle as plotted varies with the aspect ratio, and equals the specified angle only when the aspect ratio is unity. Hence it behaves the same as the matplotlib.patches.Ellipse with axes.transData as its transform.

kwargsdict

Keyword arguments are passed to matplotlib.collections.CircleCollection.

class hyperspy.api.plot.markers.Ellipses(offsets, heights, widths, angles=0, offset_transform='data', units='xy', **kwargs)#

Bases: Markers

A set of Ellipse Markers

Initialize the set of Ellipse Markers.

Parameters:
offsetsarray_like

The positions [x, y] of the center of the marker. If the offsets are not provided, the marker will be placed at the current navigation position.

heights: array-like

The lengths of the second axes.

widths: array-like

The lengths of the first axes (e.g., major axis lengths).

anglesarray_like
The angles of the first axes, degrees CCW from the x-axis.
units{"points", "inches", "dots", "width"”, "height", "x", "y", "xy"}

The units in which majors and minors are given; "width" and "height" refer to the dimensions of the axes, while "x" and "y" refer to the offsets data units. "xy" differs from all others in that the angle as plotted varies with the aspect ratio, and equals the specified angle only when the aspect ratio is unity. Hence it behaves the same as the matplotlib.patches.Ellipse with axes.transData as its transform.

kwargs:

Additional keyword arguments are passed to matplotlib.collections.EllipseCollection.

class hyperspy.api.plot.markers.HorizontalLines(offsets, **kwargs)#

Bases: Markers

A set of HorizontalLines markers

Initialize a set of HorizontalLines markers.

Parameters:
offsetsarray_like

Positions of the markers

kwargsdict

Keyword arguments passed to the underlying marker collection. Any argument that is array-like and has dtype=object is assumed to be an iterating argument and is treated as such.

Examples

>>> import hyperspy.api as hs
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> # Create a Signal2D with 2 navigation dimensions
>>> rng = np.random.default_rng(0)
>>> data = rng.random((25, 25, 100)) * 100
>>> s = hs.signals.Signal1D(data)
>>> offsets = np.array([10, 20, 40])
>>> m = hs.plot.markers.HorizontalLines(
...     offsets=offsets,
...     linewidth=4,
...     colors=['r', 'g', 'b'],
...     )
>>> s.plot()
>>> s.add_marker(m)
get_current_kwargs(only_variable_length=False)#

Return the current keyword arguments for updating the collection.

Parameters:
only_variable_lengthbool

If True, only returns the variable length kwargs. Default is False.

Returns:
kwargsdict

The argument at the current navigation position.

class hyperspy.api.plot.markers.Lines(segments, transform='data', **kwargs)#

Bases: Markers

A set of Line Segments Markers.

Initialize the set of Segments Markers.

Parameters:
segmentsnumpy.ndarray

Must be with shape [n, 2, 2] ragged array with shape (n, 2, 3) at every navigation position. Defines the lines[[[x1,y1],[x2,y2]], …] of the center of the ellipse.

kwargsdict

Additional keyword arguments are passed to matplotlib.collections.LineCollection.

Notes

Unlike markers using offsets argument, the positions of the segments are defined by the segments argument and the tranform specifying the coordinate system of the segments is transform.

class hyperspy.api.plot.markers.Markers(collection, offset_transform='data', transform='display', shift=None, plot_on_signal=True, name='', ScalarMappable_array=None, **kwargs)#

Bases: object

A set of markers using Matplotlib collections.

The markers are defined by a set of arugment required by the collections, typically, offsets, verts or segments will define their positions.

To define a non-static marker any argument that can be set with the matplotlib.collections.Collection.set() method can be passed as an array with dtype=object of the constructor and the same size as the navigation axes of the a signal the markers will be added to.

Parameters:
collectionmatplotlib.collections.Collection or str

A Matplotlib collection to be initialized.

offset_transform, transformstr

offset_transform define the transformation used for the offsets` value and tranform define the transformation for other arguments, typically to scale the size of the Path. It can be one of the following:

  • "data": the offsets are defined in data coordinates and the ax.transData transformation is used.

  • "relative": The offsets are defined in data coordinates in x and coordinates in y relative to the data plotted. Only for 1D figure.

  • "axes": the offsets are defined in axes coordinates and the ax.transAxes transformation is used. (0, 0) is bottom left of the axes, and (1, 1) is top right of the axes.

  • "xaxis": The offsets are defined in data coordinates in x and axes coordinates in y direction; use matplotlib.axes.Axes.get_xaxis_transform() transformation.

  • "yaxis": The offsets are defined in data coordinates in y and axes coordinates in x direction; use matplotlib.axes.Axes.get_xaxis_transform() transformation..

  • "display": the offsets are not transformed, i.e. are defined in the display coordinate system. (0, 0) is the bottom left of the window, and (width, height) is top right of the output in “display units” matplotlib.transforms.IdentityTransform.

shiftNone or float

Only for offset_transform="relative". This applied a systematic shift in the y component of the offsets values. The shift is defined in the matplotlib "axes" coordinate system. This provides a constant shift from the data for labeling Signal1D.

plot_on_signalbool

If True, plot on signal figure, otherwise on navigator.

namestr

The name of the markers.

ScalarMappable_arrayArray-like

Set the array of the matplotlib.cm.ScalarMappable of the matplotlib collection. The ScalarMappable array will overwrite facecolor and edgecolor. Default is None.

**kwargsdict

Keyword arguments passed to the underlying marker collection. Any argument that is array-like and has dtype=object is assumed to be an iterating argument and is treated as such.

Examples

Add markers using a matplotlib.collections.PatchCollection which will display the specified subclass of matplotlib.patches.Patch at the position defined by the argument offsets .

>>> from matplotlib.collections import PatchCollection
>>> from matplotlib.patches import Circle
>>> m = hs.plot.markers.Markers(
...    collection=PatchCollection,
...    patches=[Circle((0, 0), 1)],
...    offsets=np.random.rand(10,2)*10,
...    )
>>> s = hs.signals.Signal2D(np.ones((10, 10, 10, 10)))
>>> s.plot()
>>> s.add_marker(m)

Adding star “iterating” markers using matplotlib.collections.StarPolygonCollection

>>> from matplotlib.collections import StarPolygonCollection
>>> import numpy as np
>>> rng = np.random.default_rng(0)
>>> data = np.ones((25, 25, 100, 100))
>>> s = hs.signals.Signal2D(data)
>>> offsets = np.empty(s.axes_manager.navigation_shape, dtype=object)
>>> for ind in np.ndindex(offsets.shape):
...    offsets[ind] = rng.random((10, 2)) * 100

Every other star has a size of 50/100

>>> m = hs.plot.markers.Markers(
...    collection=StarPolygonCollection,
...    offsets=offsets,
...    numsides=5,
...    color="orange",
...    sizes=(50, 100),
...    )
>>> s.plot()
>>> s.add_marker(m)
add_items(navigation_indices=None, **kwargs)#

Add items to the markers.

Parameters:
navigation_indicestuple or None

Only for variable-lenght markers. If None, all for all navigation coordinates.

**kwargsdict

Mapping of keys:values to add to the markers

Examples

Add a single item:

>>> offsets = np.array([[1, 1], [2, 2]])
>>> texts = np.array(["a", "b"])
>>> m = hs.plot.markers.Texts(offsets=offsets, texts=texts)
>>> print(m)
<Texts, length: 2>
>>> m.add_items(offsets=np.array([[0, 1]]), texts=["c"])
>>> print(m)
<Texts, length: 3>

Add a single item at a defined navigation position of variable length markers:

>>> offsets = np.empty(4, dtype=object)
>>> texts = np.empty(4, dtype=object)
>>> for i in range(len(offsets)):
...    offsets[i] = np.array([[1, 1], [2, 2]])
...    texts[i] = ['a' * (i+1)] * 2
>>> m = hs.plot.markers.Texts(offsets=offsets, texts=texts)
>>> m.add_items(
...    offsets=np.array([[0, 1]]), texts=["new_text"],
...    navigation_indices=(1, )
...    )
close(render_figure=True)#

Remove and disconnect the marker.

Parameters:
render_figurebool, 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.

classmethod from_signal(signal, key=None, signal_axes='metadata', **kwargs)#

Initialize a marker collection from a hyperspy Signal.

Parameters:
signal: :class:`~.api.signals.BaseSignal`

A value passed to the Collection as {key:signal.data}

key: str or None

The key used to create a key value pair to create the subclass of matplotlib.collections.Collection. If None (default) the key is set to "offsets".

signal_axes: str, tuple of :class:`~.axes.UniformDataAxis` or None

If "metadata" look for signal_axes saved in metadata under s.metadata.Peaks.signal_axes and convert from pixel positions to real units before creating the collection. If a tuple of signal axes, those axes will be used otherwise (None) no transformation will happen.

get_current_kwargs(only_variable_length=False)#

Return the current keyword arguments for updating the collection.

Parameters:
only_variable_lengthbool

If True, only returns the variable length kwargs. Default is False.

Returns:
kwargsdict

The argument at the current navigation position.

property offset_transform#

The tranform being used for the offsets values.

plot(render_figure=True)#

Plot a marker which has been added to a signal.

Parameters:
render_figurebool, 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.

plot_colorbar()#

Add a colorbar for the collection.

Returns:
matplotlib.colorbar.Colorbar

The colorbar of the collection.

Examples

>>> rng = np.random.default_rng(0)
>>> s = hs.signals.Signal2D(np.ones((100, 100)))
>>> # Define the size of the circles
>>> sizes = rng.random((10, )) * 10 + 20
>>> # Define the position of the circles
>>> offsets = rng.random((10, 2)) * 100
>>> m = hs.plot.markers.Circles(
...    sizes=sizes,
...    offsets=offsets,
...    linewidth=2,
...    )
>>> s.plot()
>>> s.add_marker(m)
>>> m.set_ScalarMappable_array(sizes.ravel() / 2)
>>> cbar = m.plot_colorbar()
>>> cbar.set_label('Circle radius')
remove_items(indices, keys=None, navigation_indices=None)#

Remove items from the markers.

Parameters:
indicesslice, int or numpy.ndarray

Indicate indices of sub-arrays to remove along the specified axis.

keysstr, list of str or None

Specify the key of the Markers.kwargs to remove. If None, use all compatible keys. Default is None.

navigation_indicestuple

Only for variable-lenght markers. If None, remove for all navigation coordinates.

Examples

Remove a single item:

>>> offsets = np.array([[1, 1], [2, 2]])
>>> m = hs.plot.markers.Points(offsets=offsets)
>>> print(m)
<Points, length: 2>
>>> m.remove_items(indices=(1, ))
>>> print(len(m))
1

Remove a single item at specific navigation position for variable length markers:

>>> offsets = np.empty(4, dtype=object)
>>> texts = np.empty(4, dtype=object)
>>> for i in range(len(offsets)):
...    offsets[i] = np.array([[1, 1], [2, 2]])
...    texts[i] = ['a' * (i+1)] * 2
>>> m = hs.plot.markers.Texts(offsets=offsets, texts=texts)
>>> m.remove_items(1, navigation_indices=(1, ))

Remove several items:

>>> offsets = np.stack([np.arange(0, 100, 10)]*2).T + np.array([5,]*2)
>>> texts = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'f', 'h', 'i'])
>>> m = hs.plot.markers.Texts(offsets=offsets, texts=texts)
>>> print(m)
<Texts, length: 10>
>>> m.remove_items(indices=[1, 2])
>>> print(m)
<Texts, length: 8>
set_ScalarMappable_array(array)#

Set the array of the matplotlib.cm.ScalarMappable of the matplotlib collection. The ScalarMappable array will overwrite facecolor and edgecolor.

Parameters:
arrayarray_like

The value that are mapped to the colors.

See also

plot_colorbar
property transform#

The tranform being used for the values other than offsets, typically sizes, etc.

update()#

Update the markers on the plot.

class hyperspy.api.plot.markers.Points(offsets, sizes=10, offset_transform='data', units='points', **kwargs)#

Bases: Markers

A set of Points Markers.

Initialize the set of points Markers.

Parameters:
offsetsarray_like

The positions [x, y] of the center of the marker. If the offsets are not provided, the marker will be placed at the current navigation position.

sizesint, float or array_like, optional

The size of the markers in display coordinate system.

units{"points", "inches", "dots", "width"”, "height", "x", "y", "xy"}

The units in which majors and minors are given; "width" and "height" refer to the dimensions of the axes, while "x" and "y" refer to the offsets data units. "xy" differs from all others in that the angle as plotted varies with the aspect ratio, and equals the specified angle only when the aspect ratio is unity. Hence it behaves the same as the matplotlib.patches.Ellipse with axes.transData as its transform.

kwargsdict

Keyword arguments are passed to matplotlib.collections.CircleCollection

class hyperspy.api.plot.markers.Polygons(verts, transform='data', **kwargs)#

Bases: Markers

A Collection of Rectangles Markers

Initialize the set of Segments Markers.

Parameters:
vertslist of numpy.ndarray or list of list

The verts define the vertices of the polygons. Note that this can be a ragged list and as such it is not automatically cast to a numpy array as that would result in an array of objects. In the form [[[x1,y1], [x2,y2], … [xn, yn]],[[x1,y1], [x2,y2], …[xm,ym]], …].

**kwargsdict

Additional keyword arguments are passed to matplotlib.collections.PolyCollection

Notes

Unlike markers using offsets argument, the positions of the polygon are defined by the verts argument and the tranform specifying the coordinate system of the verts is transform.

Examples

>>> import hyperspy.api as hs
>>> import numpy as np
>>> # Create a Signal2D with 2 navigation dimensions
>>> data = np.ones((25, 25, 100, 100))
>>> s = hs.signals.Signal2D(data)
>>> poylgon1 = [[1, 1], [20, 20], [1, 20], [25, 5]]
>>> poylgon2 = [[50, 60], [90, 40], [60, 40], [23, 60]]
>>> verts = [poylgon1, poylgon2]
>>> # Create the markers
>>> m = hs.plot.markers.Polygons(
...     verts=verts,
...     linewidth=3,
...     facecolors=('g',),
...     )
>>> # Add the marker to the signal
>>> s.plot()
>>> s.add_marker(m)
class hyperspy.api.plot.markers.Rectangles(offsets, widths, heights, angles=0, offset_transform='data', units='xy', **kwargs)#

Bases: Markers

A Collection of Rectangles Markers

Initialize the set of Segments Markers.

Parameters:
offsetsarray_like

The positions [x, y] of the center of the marker. If the offsets are not provided, the marker will be placed at the current navigation position.

heights: array-like

The lengths of the second axes.

widths: array-like

The lengths of the first axes (e.g., major axis lengths).

anglesarray_like
The angles of the first axes, degrees CCW from the x-axis.
units{"points", "inches", "dots", "width"”, "height", "x", "y", "xy"}

The units in which majors and minors are given; "width" and "height" refer to the dimensions of the axes, while "x" and "y" refer to the offsets data units. "xy" differs from all others in that the angle as plotted varies with the aspect ratio, and equals the specified angle only when the aspect ratio is unity. Hence it behaves the same as the matplotlib.patches.Ellipse with axes.transData as its transform.

kwargs:

Additional keyword arguments are passed to hyperspy.external.matplotlib.collections.RectangleCollection.

class hyperspy.api.plot.markers.Squares(offsets, widths, angles=0, offset_transform='data', units='x', **kwargs)#

Bases: Markers

A Collection of square markers.

Initialize the set of square Markers.

Parameters:
offsetsarray_like

The positions [x, y] of the center of the marker. If the offsets are not provided, the marker will be placed at the current navigation position.

widths: array-like

The lengths of the first axes (e.g., major axis lengths).

anglesarray_like
The angles of the first axes, degrees CCW from the x-axis.
units{"points", "inches", "dots", "width"”, "height", "x", "y", "xy"}

The units in which majors and minors are given; "width" and "height" refer to the dimensions of the axes, while "x" and "y" refer to the offsets data units. "xy" differs from all others in that the angle as plotted varies with the aspect ratio, and equals the specified angle only when the aspect ratio is unity. Hence it behaves the same as the matplotlib.patches.Ellipse with axes.transData as its transform.

kwargs:

Additional keyword arguments are passed to hyperspy.external.matplotlib.collections.SquareCollection.

class hyperspy.api.plot.markers.Texts(offsets, offset_transform='data', transform='display', **kwargs)#

Bases: Markers

A set of text markers

Initialize the set of Circle Markers.

Parameters:
offsetsarray_like

The positions [x, y] of the center of the marker. If the offsets are not provided, the marker will be placed at the current navigation position.

sizesarray_like

The size of the text in points.

facecolors(list of) matplotlib color

Set the facecolor(s) of the markers. It can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If c is ‘none’, the patch will not be filled.

kwargsdict

Keyword arguments are passed to matplotlib.collections.CircleCollection.

class hyperspy.api.plot.markers.VerticalLines(offsets, **kwargs)#

Bases: Markers

A set of Vertical Line Markers

Initialize the set of Vertical Line Markers.

Parameters:
x: [n]

Positions of the markers

kwargs: dict

Keyword arguments passed to the underlying marker collection. Any argument that is array-like and has dtype=object is assumed to be an iterating argument and is treated as such.

Examples

>>> import hyperspy.api as hs
>>> import numpy as np
>>> # Create a Signal2D with 2 navigation dimensions
>>> rng = np.random.default_rng(0)
>>> data = rng.random((25, 25, 100))
>>> s = hs.signals.Signal1D(data)
>>> offsets = np.array([10, 20, 40])
>>> # Create the markers
>>> m = hs.plot.markers.VerticalLines(
...     offsets=offsets,
...     linewidth=3,
...     colors=['r', 'g', 'b'],
...     )
>>> # Add the marker to the signal
>>> s.plot()
>>> s.add_marker(m)
get_current_kwargs(only_variable_length=False)#

Return the current keyword arguments for updating the collection.

Parameters:
only_variable_lengthbool

If True, only returns the variable length kwargs. Default is False.

Returns:
kwargsdict

The argument at the current navigation position.