erlab.plotting.erplot

Deprecated convenience module for plotting. Use erlab.plotting instead.

Functions

clean_labels(axes[, remove_inner_ticks])

Clean the labels of the given axes.

copy_mathtext(s[, fontsize, fontproperties, ...])

Copy math equations to the clipboard as SVG.

fancy_labels([ax, radians])

Apply pretty labels to Matplotlib axes based on their current label text.

fermiline([ax, value, orientation])

Plot a constant energy line to denote the Fermi level.

figwh([ratio, wide, wscale, style, fixed_height])

flatten_transparency(rgba[, background])

Flatten the transparency of an RGBA image by blending it with a background color.

get_mappable(ax[, index, image_only, silent])

Get the matplotlib.cm.ScalarMappable from a given matplotlib.axes.Axes.

gradient_fill(x, y[, y0, color, cmap, ...])

Apply a gradient fill to a line plot.

image_is_light(im)

Determine if an image is light or dark.

integer_ticks(ax)

Set the ticks on the x and y axes to only display integer values.

label_subplot_properties(axes, values[, ...])

Labels subplots with automatically generated labels.

label_subplots(axes[, values, startfrom, ...])

Labels subplots with automatically generated labels.

mark_points(points, labels, *[, y, pad, ...])

Mark points above the horizontal axis.

mark_points_outside(points, labels[, axis, ...])

Mark points above the horizontal axis.

nice_colorbar([ax, mappable, width, aspect, ...])

Create a colorbar with fixed width and aspect to ensure uniformity of plots.

place_inset(parent_axes, width, height[, ...])

Easy placement of inset axes.

plot_array(arr[, ax, colorbar, colorbar_kw, ...])

Plot a 2D xarray.DataArray using matplotlib.pyplot.imshow().

plot_array_2d(larr, carr[, ax, ...])

Plot a 2D array with associated color array.

plot_hex_bz([a, reciprocal, rotate, offset, ax])

Plot a 2D hexagonal BZ overlay on the specified axes.

plot_slices(maps[, figsize, transpose, ...])

Automated comparison plot of slices.

property_labels([values, decimals, si, ...])

Generate labels from a dictionary of values.

proportional_colorbar([mappable, cax, ax, ...])

Replace the current colorbar or creates a new colorbar with proportional spacing.

scale_units(ax, axis[, si, prefix, power])

Rescales ticks and adds an SI prefix to the axis label.

set_titles(axes, labels[, order])

Set titles for multiple axes.

set_xlabels(axes, labels[, order])

Set x-axis labels for multiple axes.

set_ylabels(axes, labels[, order])

Set y-axis labels for multiple axes.

sizebar(ax, value, unit[, si, resolution, ...])

Add a size bar to an axes.

unify_clim(axes[, target, image_only, ...])

Unify the color limits for mappables in multiple axes.

Classes

CenteredInversePowerNorm(gamma[, vcenter, ...])

Inverse power-law normalization of symmetrical data around a center.

CenteredPowerNorm(gamma[, vcenter, ...])

Power-law normalization of symmetrical data around a center.

InversePowerNorm(gamma[, vmin, vmax, clip])

Inverse power-law normalization.

TwoSlopeInversePowerNorm(gamma[, vcenter, ...])

Inverse power-law normalization of data with a set center.

TwoSlopePowerNorm(gamma[, vcenter, vmin, vmax])

Power-law normalization of data with a set center.

class erlab.plotting.erplot.CenteredInversePowerNorm(gamma, vcenter=0, halfrange=None, clip=False)[source]

Bases: CenteredPowerNorm

Inverse power-law normalization of symmetrical data around a center.

Unlike TwoSlopeInversePowerNorm, CenteredInversePowerNorm applies an equal rate of change around the center.

Useful when mapping symmetrical data around a conceptual center e.g., data that range from -2 to 4, with 0 as the midpoint, and with equal rates of change around that midpoint.

Parameters:
  • gamma (float) – Power law exponent.

  • vcenter (float, default: 0) – The data value that defines 0.5 in the normalization. Defaults to 0.

  • halfrange (float | None, default: None) – The range of data values that defines a range of 0.5 in the normalization, so that vcenter - halfrange is 0.0 and vcenter + halfrange is 1.0 in the normalization. Defaults to the largest absolute difference to vcenter for the values in the dataset.

  • clip (bool, default: False) –

    If True values falling outside the range [vmin, vmax], are mapped to 0 or 1, whichever is closer, and masked values are set to 1. If False masked values remain masked.

    Clipping silently defeats the purpose of setting the over, under, and masked colors in a colormap, so it is likely to lead to surprises; therefore the default is clip=False.

class erlab.plotting.erplot.CenteredPowerNorm(gamma, vcenter=0, halfrange=None, clip=False)[source]

Bases: CenteredNorm

Power-law normalization of symmetrical data around a center.

Unlike TwoSlopePowerNorm, CenteredPowerNorm applies an equal rate of change around the center.

Useful when mapping symmetrical data around a conceptual center e.g., data that range from -2 to 4, with 0 as the midpoint, and with equal rates of change around that midpoint.

Parameters:
  • gamma (float) – Power law exponent.

  • vcenter (float, default: 0) – The data value that defines 0.5 in the normalization. Defaults to 0.

  • halfrange (float | None, default: None) – The range of data values that defines a range of 0.5 in the normalization, so that vcenter - halfrange is 0.0 and vcenter + halfrange is 1.0 in the normalization. Defaults to the largest absolute difference to vcenter for the values in the dataset.

  • clip (bool, default: False) –

    If True values falling outside the range [vmin, vmax], are mapped to 0 or 1, whichever is closer, and masked values are set to 1. If False masked values remain masked.

    Clipping silently defeats the purpose of setting the over, under, and masked colors in a colormap, so it is likely to lead to surprises; therefore the default is clip=False.

__call__(value, clip=None)[source]

Map value to the interval [0, 1].

inverse(value)[source]
class erlab.plotting.erplot.InversePowerNorm(gamma, vmin=None, vmax=None, clip=False)[source]

Bases: Normalize

Inverse power-law normalization.

Linearly map a given value to the 0-1 range and then apply an inverse power-law normalization over that range.

For values \(x\), matplotlib.colors.PowerNorm calculates \(x^\gamma\), whereas InversePowerNorm calculates \(1-x^{1/\gamma}\). This provides higher contrast for values closer to vmin.

Parameters:
  • gamma (float) – Power law normalization parameter. If equal to 1, the colormap is linear.

  • vmin (float | None, default: None) – If vmin and/or vmax is not given, they are initialized from the minimum and maximum value, respectively, of the first input processed; i.e., __call__(A) calls autoscale_None(A)

  • vmax (float | None, default: None) – If vmin and/or vmax is not given, they are initialized from the minimum and maximum value, respectively, of the first input processed; i.e., __call__(A) calls autoscale_None(A)

  • clip (bool, default: False) –

    If True values falling outside the range [vmin, vmax], are mapped to 0 or 1, whichever is closer, and masked values are set to 1. If False masked values remain masked.

    Clipping silently defeats the purpose of setting the over, under, and masked colors in a colormap, so it is likely to lead to surprises; therefore the default is clip=False.

inverse(value)[source]
class erlab.plotting.erplot.TwoSlopeInversePowerNorm(gamma, vcenter=0.0, vmin=None, vmax=None)[source]

Bases: TwoSlopePowerNorm

Inverse power-law normalization of data with a set center.

Useful when mapping data with an unequal rates of change around a conceptual center, e.g., data that range from -2 to 4, with 0 as the midpoint.

Parameters:
  • gamma (float) – Power law exponent.

  • vcenter (float, default: 0.0) – The data value that defines 0.5 in the normalization. Defaults to 0.

  • vmin (float | None, default: None) – The data value that defines 0.0 in the normalization. Defaults to the min value of the dataset.

  • vmax (float | None, default: None) – The data value that defines 1.0 in the normalization. Defaults to the max value of the dataset.

class erlab.plotting.erplot.TwoSlopePowerNorm(gamma, vcenter=0.0, vmin=None, vmax=None)[source]

Bases: TwoSlopeNorm

Power-law normalization of data with a set center.

Useful when mapping data with an unequal rates of change around a conceptual center, e.g., data that range from -2 to 4, with 0 as the midpoint.

Parameters:
  • gamma (float) – Power law exponent.

  • vcenter (float, default: 0.0) – The data value that defines 0.5 in the normalization. Defaults to 0.

  • vmin (float | None, default: None) – The data value that defines 0.0 in the normalization. Defaults to the min value of the dataset.

  • vmax (float | None, default: None) – The data value that defines 1.0 in the normalization. Defaults to the max value of the dataset.

__call__(value, clip=None)[source]

Map value to the interval [0, 1]. The clip argument is unused.

inverse(value)[source]
erlab.plotting.erplot.clean_labels(axes, remove_inner_ticks=False, **kwargs)[source]

Clean the labels of the given axes.

This function removes the labels from the axes except for the outermost axes and prettifies the remaining labels with fancy_labels.

Changed in version 2.5.0: The function now calls Axes.label_outer recursively instead of setting the labels to an empty string.

Parameters:
  • axes (Iterable[Axes]) – The axes to clean the labels for.

  • remove_inner_ticks (bool, default: False) – If True, remove the inner ticks as well (not only tick labels).

  • **kwargs – Additional keyword arguments to be passed to fancy_labels.

erlab.plotting.erplot.copy_mathtext(s, fontsize=None, fontproperties=None, outline=False, rcparams=None, **mathtext_rc)[source]

Copy math equations to the clipboard as SVG.

Parameters:
  • s (str) – The math text to convert to SVG.

  • fontsize (float | Literal['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'] | None, default: None) – The font size to use for the math text. If None, the default font size is used.

  • fontproperties (FontProperties | None, default: None) – The font properties to use for the math text. If None, the default font properties are used.

  • outline (bool, default: False) – If True, the SVG will contain outlined paths instead of text.

  • rcparams (dict | None, default: None) – Additional rc parameters to use for the math text rendering. If None, the default rc parameters are used.

Returns:

str – The SVG string representation of the math text.

Return type:

str

Example

>>> import erlab.plotting as eplt
>>> svg_str = eplt.copy_mathtext(r"$E = mc^2$", fontsize=12)
erlab.plotting.erplot.fancy_labels(ax=None, *, radians=False)[source]

Apply pretty labels to Matplotlib axes based on their current label text.

This function converts plain dimension names already set on the axes into nicely formatted labels (e.g., symbols and units). The labels are determined based on PRETTY_NAMES and PRETTY_UNITS.

Parameters:
  • ax (Axes | Iterable[Axes] | None, default: None) – The target axes or an iterable of axes. If None (default), the current axes is used.

  • radians (bool, optional) – If True, angle units will be displayed in radians instead of degrees.

Examples

>>> import matplotlib.pyplot as plt
>>> import erlab.plotting as eplt
>>> fig, ax = plt.subplots()
>>> ax.set_xlabel("kx")
>>> ax.set_ylabel("eV")
>>> fancy_labels(ax)
>>> ax.get_xlabel()
'$k_x$ (Å${}^{-1}$)'
>>> ax.get_ylabel()
'$E-E_F$ (eV)'
erlab.plotting.erplot.fermiline(ax=None, value=0.0, orientation='h', **kwargs)[source]

Plot a constant energy line to denote the Fermi level.

Parameters:
  • ax (Axes | None, default: None) – The matplotlib.axes.Axes to annotate.

  • value (float, default: 0.0) – The coordinate of the line. Defaults to 0, assuming binding energy.

  • orientation (Literal['h', 'v'], default: "h") – If ‘h’, a horizontal line is plotted. If ‘v’, a vertical line is plotted.

  • **kwargs – Keyword arguments passed onto matplotlib.lines.Line2D.

Returns:

matplotlib.lines.Line2D

Return type:

Line2D | list[Line2D | list[Line2D | MultipleLine2D]]

erlab.plotting.erplot.figwh(ratio=0.6180339887498948, wide=0, wscale=1, style='aps', fixed_height=True)[source]
erlab.plotting.erplot.flatten_transparency(rgba, background=None)[source]

Flatten the transparency of an RGBA image by blending it with a background color.

Parameters:
erlab.plotting.erplot.get_mappable(ax, index=-1, *, image_only=False, silent=False)[source]

Get the matplotlib.cm.ScalarMappable from a given matplotlib.axes.Axes.

Parameters:
  • ax (Axes) – Parent axes.

  • index (int, default: -1) – The index of the mappable to get. By default, the most recently added mappable is returned.

  • image_only (bool, default: False) – Only consider images as a valid mappable, by default False.

  • silent (bool, default: False) – If False, raises a RuntimeError when no mappable is found. If True, silently returns None.

Returns:

matplotlib.cm.ScalarMappable or None

Return type:

_ScalarMappable | None

erlab.plotting.erplot.gradient_fill(x, y, y0=None, color='C0', cmap=None, transpose=False, reverse=False, ax=None, **kwargs)[source]

Apply a gradient fill to a line plot.

Parameters:
Returns:

matplotlib.image.AxesImage

Return type:

AxesImage

erlab.plotting.erplot.image_is_light(im)[source]

Determine if an image is light or dark.

Checks whether the prominent color is closer to white than black.

erlab.plotting.erplot.integer_ticks(ax)[source]

Set the ticks on the x and y axes to only display integer values.

Modifies the x and y ticks of the given axes to only show integer values that are within the current limits of the axes.

Parameters:

ax (Axes | Iterable[Axes]) – Axes or iterable of Axes.

erlab.plotting.erplot.label_subplot_properties(axes, values, decimals=None, si=0, name=None, unit=None, order='C', **kwargs)[source]

Labels subplots with automatically generated labels.

Parameters:
  • axes (Axes | Iterable[Axes]) – matplotlib.axes.Axes to label. If an array is given, the order will be determined by the flattening method given by order.

  • values (dict) – Key-value pair of annotations. The values may be a single value or an array-like of values. If a single value, it will be converted to a list of length 1. If an array of 2 or more dimensions is given, it will be flattened with the order given by order. All values must be of the same length when flattened.

  • decimals (int | None, default: None) – Number of decimal places to round to. If decimals is None, no rounding is performed. If decimals is negative, it specifies the number of positions to the left of the decimal point.

  • si (int, default: 0) – Powers of 10 for automatic SI prefix setting.

  • name (str | None, default: None) – When set, overrides automatic dimension name setting.

  • unit (str | None, default: None) – When set, overrides automatic unit setting.

  • order (Literal['C', 'F', 'A', 'K'], default: "C") – Order in which to flatten ax. ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran-style) order. The default is ‘C’.

  • **kwargs – Extra arguments to erlab.plotting.annotations.label_subplots.

erlab.plotting.erplot.label_subplots(axes, values=None, startfrom=1, order='C', loc='upper left', offset=(0.0, 0.0), prefix='', suffix='', numeric=False, capital=False, fontweight='normal', fontsize=None, **kwargs)[source]

Labels subplots with automatically generated labels.

Parameters:
  • axes (Axes | Iterable[Axes]) – matplotlib.axes.Axes to label. If an array is given, the order will be determined by the flattening method given by order.

  • values (Iterable[int | str] | None, default: None) – Integer or string labels corresponding to each Axes in axes for manual labels.

  • startfrom (int, default: 1) – Start from this number when creating automatic labels. Has no effect when values is not None.

  • order (Literal['C', 'F', 'A', 'K'], default: "C") – Order in which to flatten ax. ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran-style) order. ‘A’ means to flatten in column-major order if a is Fortran contiguous in memory, row-major order otherwise. ‘K’ means to flatten a in the order the elements occur in memory. The default is ‘C’.

  • loc (Literal['upper left', 'upper center', 'upper right', 'center left', 'center', 'center right', 'lower left', 'lower center', 'lower right'], default: "upper left") – The box location. The default is 'upper left'.

  • offset (tuple[float, float], default: (0.0, 0.0)) – Values that are used to position the legend in conjunction with loc, given in display units.

  • prefix (str, default: "") – String to prepend to the alphabet label.

  • suffix (str, default: "") – String to append to the alphabet label.

  • numeric (bool, default: False) – Use integer labels instead of alphabets.

  • capital (bool, default: False) – Capitalize automatically generated alphabetical labels.

  • fontweight (Literal['ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'], default: "normal") – Set the font weight. The default is 'normal'.

  • fontsize (float | Literal['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'] | None, default: None) – Set the font size. The default is 'medium' for axes, and 'large' for figures.

  • **kwargs – Extra arguments to matplotlib.text.Text: refer to the matplotlib documentation for a list of all possible arguments.

erlab.plotting.erplot.mark_points(points, labels, *, y=0.0, pad=(0, 1.75), literal=False, roman=True, bar=False, ax=None, **kwargs)[source]

Mark points above the horizontal axis.

Useful when annotating high symmetry points along a cut.

Parameters:
  • points (Sequence[float]) – Floats indicating the position of each label.

  • labels (Sequence[str]) – Sequence of label strings indicating a high symmetry point. Must be the same length as points.

  • y (float | Sequence[float], default: 0.0) – Position of the label in data coordinates. If a single float is given, it will be used for all points. If a sequence is given, it must be the same length as points.

  • pad (tuple[float, float], default: (0, 1.75)) – Offset of the text in points.

  • literal (bool, default: False) – If True, take the input string literally.

  • roman (bool, default: True) – If False, itallic fonts are used.

  • bar (bool, default: False) – If True, prints a bar over the label.

  • ax (Axes | Iterable[Axes] | None, default: None) – matplotlib.axes.Axes to annotate. If None, the current axes is used.

  • **kwargs – Extra arguments to matplotlib.axes.Axes.text. By default, the horizontal alignment is set to 'center' and the vertical alignment is set to 'baseline'. The text is not clipped to the axes limits.

erlab.plotting.erplot.mark_points_outside(points, labels, axis='x', *, literal=False, roman=True, bar=False, ax=None, **kwargs)[source]

Mark points above the horizontal axis.

Useful when annotating high symmetry points along a cut.

Parameters:
  • points (Sequence[float]) – Floats indicating the position of each label.

  • labels (Sequence[str]) – Sequence of label strings indicating a high symmetry point. Must be the same length as points.

  • axis (Literal['x', 'y'], default: "x") – If 'x', marks points along the horizontal axis. If 'y', marks points along the vertical axis.

  • literal (bool, default: False) – If True, take the input string literally.

  • roman (bool, default: True) – If False, itallic fonts are used.

  • bar (bool, default: False) – If True, prints a bar over the label.

  • ax (Axes | Iterable[Axes] | None, default: None) – matplotlib.axes.Axes to annotate.

  • **kwargs – Extra arguments to matplotlib.text.Text: refer to the matplotlib documentation for a list of all possible arguments.

erlab.plotting.erplot.nice_colorbar(ax=None, *, mappable=None, width=8.0, aspect=5.0, pad=3.0, minmax=False, orientation='vertical', floating=False, ticklabels=None, **kwargs)[source]

Create a colorbar with fixed width and aspect to ensure uniformity of plots.

Parameters:
  • ax (Axes | Iterable[Axes] | None, default: None) – The matplotlib.axes.Axes instance in which the colorbar is drawn.

  • mappable (_ScalarMappable | None, default: None) – The mappable whose colormap and norm will be used.

  • width (float, default: 8.0) – The width of the colorbar in points.

  • aspect (float, default: 5.0) – aspect ratio of the colorbar.

  • pad (float, default: 3.0) – The pad between the colorbar and axes in points.

  • minmax (bool, default: False) – If False, the ticks and the ticklabels will be determined from the keyword arguments (the default). If True, the minimum and maximum of the colorbar will be labeled.

  • orientation (Literal['vertical', 'horizontal'], default: "vertical") – Colorbar orientation.

  • **kwargs – Keyword arguments are passed to proportional_colorbar.

Returns:

cbar (matplotlib.colorbar.Colorbar) – The created colorbar.

erlab.plotting.erplot.place_inset(parent_axes, width, height, pad=0.1, loc='upper right', **kwargs)[source]

Easy placement of inset axes.

Parameters:
  • parent_axes (Axes) – matplotlib.axes.Axes to place the inset axes.

  • width (float | str) – Size of the inset axes to create. If float, specifies the size in inches, e.g. 1.3. If str, specifies the size in relative units, e.g. '40%' of parent_axes.

  • height (float | str) – Size of the inset axes to create. If float, specifies the size in inches, e.g. 1.3. If str, specifies the size in relative units, e.g. '40%' of parent_axes.

  • pad (float | tuple[float, float], default: 0.1) – Padding between parent_axes and inset in inches.

  • loc (Literal['upper left', 'upper center', 'upper right', 'center left', 'center', 'center right', 'lower left', 'lower center', 'lower right'], default: "upper right") – Location to place the inset axes.

  • **kwargs – Keyword arguments are passed onto matplotlib.axes.Axes.inset_axes.

Returns:

matplotlib.axes.Axes

Return type:

Axes

erlab.plotting.erplot.plot_array(arr, ax=None, *, colorbar=False, colorbar_kw=None, gamma=1.0, norm=None, xlim=None, ylim=None, crop=False, rad2deg=False, func=None, func_args=None, rtol=1.0e-5, atol=1.0e-8, rasterized=True, **improps)[source]

Plot a 2D xarray.DataArray using matplotlib.pyplot.imshow().

If the input array is detected to have non-evenly spaced coordinates, it is plotted as a matplotlib.image.NonUniformImage.

Parameters:
  • arr (DataArray) – A two-dimensional xarray.DataArray with evenly spaced coordinates.

  • ax (Axes | None, default: None) – The target matplotlib.axes.Axes.

  • colorbar (bool, default: False) – Whether to plot a colorbar.

  • colorbar_kw (dict | None, default: None) – Keyword arguments passed onto erlab.plotting.colors.nice_colorbar().

  • xlim (float | tuple[float, float] | None, default: None) – If given a sequence of length 2, those values are set as the lower and upper limits of each axis. If given a single float, the limits are set as (-lim, lim). If None, automatically determines the limits from the data.

  • ylim (float | tuple[float, float] | None, default: None) – If given a sequence of length 2, those values are set as the lower and upper limits of each axis. If given a single float, the limits are set as (-lim, lim). If None, automatically determines the limits from the data.

  • rad2deg (bool | Iterable[str], default: False) – If True, converts some known angle coordinates from radians to degrees. If an iterable of str is given, only the coordinates that correspond to the given strings are converted.

  • func (Callable | None, default: None) – A callable that processes the data prior to display. Its output must be an array that has the same shape as the input.

  • func_args (dict | None, default: None) – Keyword arguments passed onto func.

  • rtol (float, default: 1.0e-5) – By default, the input array is checked for evenly spaced coordinates. If it is not evenly spaced, it is plotted as a matplotlib.image.NonUniformImage instead of a matplotlib.image.AxesImage. rtol and atol are the tolerances for the coordinates to be considered evenly spaced. The default values are consistent with numpy.isclose.

  • atol (float, default: 1.0e-8) – By default, the input array is checked for evenly spaced coordinates. If it is not evenly spaced, it is plotted as a matplotlib.image.NonUniformImage instead of a matplotlib.image.AxesImage. rtol and atol are the tolerances for the coordinates to be considered evenly spaced. The default values are consistent with numpy.isclose.

  • rasterized (bool, default: True) – Force rasterized output.

  • **improps – Keyword arguments passed onto matplotlib.pyplot.imshow().

Returns:

matplotlib.image.AxesImage

Return type:

AxesImage

Notes

Some keyword arguments have different default behavior compared to matplotlib.

  • interpolation is set to 'none' for evenly spaced data and 'nearest' for nonuniform data.

  • aspect is set to 'auto'.

  • origin is set to 'lower'.

  • The image is rasterized by default.

erlab.plotting.erplot.plot_array_2d(larr, carr, ax=None, *, normalize_with_larr=False, xlim=None, ylim=None, cmap=None, lnorm=None, cnorm=None, background=None, colorbar=True, cax=None, colorbar_kw=None, imshow_kw=None, N=256, rtol=1.0e-5, atol=1.0e-8, **indexers_kwargs)[source]

Plot a 2D array with associated color array.

The lightness array represents the intensity values, while the color array represents some other property. The arrays must have the same shape.

Parameters:
  • larr (DataArray) – The 2D array representing the lightness values.

  • carr (DataArray) – The 2D array representing the color values.

  • ax (Axes | None, default: None) – The axes on which to plot the array. If None, the current axes will be used.

  • normalize_with_larr (bool, default: False) – Whether to normalize the color array with the lightness array. Default is False.

  • xlim (float | tuple[float, float] | None, default: None) – The x-axis limits for the plot. If a float, it represents the symmetric limits around 0. If a tuple, it represents the lower and upper limits. If None, the limits are determined from the data.

  • ylim (float | tuple[float, float] | None, default: None) – The y-axis limits for the plot. If a float, it represents the symmetric limits around 0. If a tuple, it represents the lower and upper limits. If None, the limits are determined from the data.

  • cmap (Colormap | str | None, default: None) – The colormap to use for the color array. If None, a linear segmented colormap consisting of blue, black, and red is used.

  • lnorm (Normalize | None, default: None) – The normalization object for the lightness array.

  • cnorm (Normalize | None, default: None) – The normalization object for the color array.

  • background (tuple[float, float, float] | str | tuple[float, float, float, float] | tuple[tuple[float, float, float] | str, float] | tuple[tuple[float, float, float, float], float] | None, default: None) – The background color to use for the plot. If None, white is used.

  • colorbar (bool, default: True) – Whether to create a colorbar. Default is True.

  • cax (Axes | None, default: None) – The axes on which to create the colorbar if colorbar is True. If None, a new axes will be created for the colorbar.

  • colorbar_kw (dict | None, default: None) – Additional keyword arguments to pass to matplotlib.pyplot.colorbar.

  • imshow_kw (dict | None, default: None) – Additional keyword arguments to pass to matplotlib.pyplot.imshow.

  • N (int, default: 256) – The number of levels in the colormap. Default is 256.

  • rtol (float, default: 1.0e-5) – By default, the input array is checked for evenly spaced coordinates. rtol and atol are the tolerances for the coordinates to be considered evenly spaced. The default values are consistent with numpy.isclose.

  • atol (float, default: 1.0e-8) – By default, the input array is checked for evenly spaced coordinates. rtol and atol are the tolerances for the coordinates to be considered evenly spaced. The default values are consistent with numpy.isclose.

  • **indexers_kwargs (dict) – Additional keyword arguments to pass to qsel to select the data to plot. Note that the resulting data after the selection must be 2D.

Returns:

Return type:

tuple[AxesImage, Colorbar | None]

Example

>>> import erlab.plotting as eplt
>>> import matplotlib.pyplot as plt
>>> import xarray as xr
>>> larr = xr.DataArray([[1, 2, 3], [4, 5, 6]])
>>> carr = xr.DataArray([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]])
>>> eplt.plot_array_2d(larr, carr)
erlab.plotting.erplot.plot_hex_bz(a=3.54, *, reciprocal=False, rotate=0.0, offset=(0.0, 0.0), ax=None, **kwargs)[source]

Plot a 2D hexagonal BZ overlay on the specified axes.

Parameters:
  • a (float, default: 3.54) – Lattice constant of the hexagonal lattice.

  • reciprocal (bool, default: False) – If True, a is interpreted as the periodicity of the reciprocal lattice.

  • rotate (float, default: 0.0) – Rotation angle in degrees to apply to the BZ.

  • offset (tuple[float, float], default: (0.0, 0.0)) – Offset for the Brillouin zone center in the form of a tuple (x, y).

  • ax (Axes | None, default: None) – The axes to plot the BZ on. If None, the current axes are used.

  • **kwargs – Additional keyword arguments passed to matplotlib.patches.RegularPolygon.

erlab.plotting.erplot.plot_slices(maps, figsize=None, *, transpose=False, xlim=None, ylim=None, crop=True, same_limits=False, axis='auto', show_all_labels=False, colorbar='none', hide_colorbar_ticks=True, annotate=True, cmap=None, norm=None, order='C', cmap_order='C', norm_order=None, gradient=False, gradient_kw=None, subplot_kw=None, annotate_kw=None, colorbar_kw=None, axes=None, **values)[source]

Automated comparison plot of slices.

Parameters:
  • maps (DataArray | Sequence[DataArray]) – Arrays to plot.

  • figsize (tuple[float, float] | None, default: None) – Figure size.

  • transpose (bool, default: False) – Transpose each map before plotting.

  • xlim (float | tuple[float | None, float | None] | None, default: None) – If given a sequence of length 2, those values are set as the lower and upper limits of each axis. If given a single float, the limits are set as (-lim, lim). If None, automatically determines the limits from the data.

  • ylim (float | tuple[float | None, float | None] | None, default: None) – If given a sequence of length 2, those values are set as the lower and upper limits of each axis. If given a single float, the limits are set as (-lim, lim). If None, automatically determines the limits from the data.

  • crop (bool, default: True) – If True, crops the data to the limits given by xlim and ylim prior to plotting.

  • same_limits (bool | Literal['row', 'col', 'all'], default: False) – If True, all images will have the same vmin and vmax. Passing 'row' or 'col' will set same limits for rows or columns, respectively. Passing 'all' is equivalent to True.

  • axis (Literal['on', 'off', 'equal', 'scaled', 'tight', 'auto', 'image', 'square'], default: "auto") –

    Passed onto matplotlib.axes.Axes.axis(). Possible values are:

    Value

    Description

    ’on’

    Turn on axis lines and labels.

    ’off’

    Turn off axis lines and labels.

    ’equal’

    Set equal scaling (i.e., make circles circular) by changing axis limits. This is the same as ax.set_aspect('equal', adjustable='datalim'). Explicit data limits may not be respected in this case.

    ’scaled’

    Set equal scaling (i.e., make circles circular) by changing dimensions of the plot box. This is the same as ax.set_aspect('equal', adjustable='box', anchor='C'). Additionally, further autoscaling will be disabled.

    ’tight’

    Set limits just large enough to show all data, then disable further autoscaling.

    ’auto’

    Automatic scaling (fill plot box with data).

    ’image’

    ’scaled’ with axis limits equal to data limits.

    ’square’

    Square plot; similar to ‘scaled’, but initially forcing xmax-xmin == ymax-ymin.

  • show_all_labels (bool, default: False) – If True, shows every xlabel and ylabel. If False, labels on shared axes are minimized. When False and the axes argument is given, the order must be specified to correctly hide shared labels.

  • colorbar (Literal['none', 'right', 'rightspan', 'all'], default: "none") –

    Controls colorbar behavior. Possible values are:

    Value

    Description

    ’none’

    Do not show colorbars.

    ’right’

    Creates a colorbar on the right for each row.

    ’rightspan’

    Create a single colorbar that spans all axes.

    ’all’

    Plot a colorbar for every axes.

  • hide_colorbar_ticks (bool, default: True) – If True, hides colorbar ticks.

  • annotate (bool, default: True) – If False, turn off automatic annotation.

  • cmap (str | Colormap | Iterable[str | Colormap | Iterable[Colormap | str]] | None, default: None) – If supplied a single str or matplotlib.colors.Colormap, the colormap is applied to all axes. Otherwise, a nested sequence with the same shape as the resulting axes can be provided to use different colormaps for different axes. If the slices are 1D, this argument can be used to supply valid colors as line colors for different slices.

  • norm (Normalize | Iterable[Normalize | Iterable[Normalize]] | None, default: None) – If supplied a single matplotlib.colors.Normalize, the norm is applied to all axes. Otherwise, a nested sequence with the same shape as the resulting axes can be provided to use different norms for different axes.

  • order (Literal['C', 'F'], default: "C") – Order to display the data. Effectively, this determines if each map is displayed along the same row or the same column. ‘C’ means to flatten in row-major (C-style) order, and ‘F’ means to flatten in column-major (Fortran-style) order.

  • cmap_order (Literal['C', 'F'], default: "C") – The order to flatten when given a nested sequence for cmap, Defaults to 'C'.

  • norm_order (Literal['C', 'F'] | None, default: None) – The order to flatten when given a nested sequence for norm, Defaults to cmap_order.

  • gradient (bool, default: False) – If True, for 1D slices, fills the area under the curve with a gradient. Has no effect for 2D slices.

  • gradient_kw (dict | None, default: None) – Extra arguments to gradient_fill().

  • subplot_kw (dict | None, default: None) – Extra arguments to matplotlib.pyplot.subplots(): refer to the matplotlib documentation for a list of all possible arguments.

  • annotate_kw (dict | None, default: None) – Extra arguments to erlab.plotting.annotations.label_subplot_properties(). Only applied when annotate is True.

  • colorbar_kw (dict | None, default: None) – Extra arguments to erlab.plotting.colors.proportional_colorbar().

  • axes (Iterable[Axes] | None, default: None) – A nested sequence of matplotlib.axes.Axes. If supplied, the returned matplotlib.figure.Figure is inferred from the first axes.

  • **values – Key-value pair of cut location and bin widths. See examples. Remaining arguments are passed onto plot_array().

Returns:

Return type:

tuple[Figure, Iterable[Axes]]

Examples

# Two maps: map1, map2
# Create a figure with a 3 by 2 grid.

fig, axes = plot_slices([map1, map2], eV=[0, -0.1, -0.2], eV_width=0.05)
erlab.plotting.erplot.property_labels(values=None, decimals=None, si=0, name=None, unit=None, order='C', **values_kwargs)[source]

Generate labels from a dictionary of values.

Given a dictionary of values, this function generates a list of label strings with the key as the dimension name and the value as the dimension value. Multiple key-value pairs will be separated by a newline character in each label. The name and unit will be automatically determined from the key.

Parameters:
  • values (dict | None, default: None) – Key-value pair of annotations. The values may be a single value or an array-like of values. If a single value, it will be converted to a list of length 1. If an array of 2 or more dimensions is given, it will be flattened with the order given by order. All values must be of the same length when flattened.

  • decimals (int | None, default: None) – Number of decimal places to round to. If decimals is None, no rounding is performed. If decimals is negative, it specifies the number of positions to the left of the decimal point.

  • si (int, default: 0) – Powers of 10 for automatic SI prefix setting.

  • name (str | None, default: None) – When set, overrides automatic dimension name setting.

  • unit (str | None, default: None) – When set, overrides automatic unit setting.

  • order (Literal['C', 'F', 'A', 'K'], default: "C") – Order in which to flatten ax. ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran-style) order. The default is ‘C’.

erlab.plotting.erplot.proportional_colorbar(mappable=None, cax=None, ax=None, *, index=-1, image_only=False, **kwargs)[source]

Replace the current colorbar or creates a new colorbar with proportional spacing.

The default behavior of colorbars in matplotlib does not support colors proportional to data in different norms. This function circumvents this behavior.

Parameters:
  • mappable (_ScalarMappable | None, default: None) – The matplotlib.cm.ScalarMappable described by this colorbar.

  • cax (Axes | None, default: None) – Axes into which the colorbar will be drawn.

  • ax (Axes | Iterable[Axes] | None, default: None) – One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set. If mappable is None and ax is given with more than one Axes, the function will try to infer the mappable from the first one.

  • index (int, default: -1) – If mappable is not provided, the index of the mappable to get from ax. Passed to get_mappable(). Default is -1, i.e., the most recently added mappable.

  • image_only (bool, default: False) – If mappable is not provided, whether to only consider images as valid mappables when inferring from ax. Passed to get_mappable(). Default is False.

  • **kwargs – Extra arguments to matplotlib.pyplot.colorbar: refer to the matplotlib documentation for a list of all possible arguments.

Returns:

cbar (matplotlib.colorbar.Colorbar) – The created colorbar.

Return type:

Colorbar

Examples

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

# Create example data and plot
X, Y = np.mgrid[0 : 3 : complex(0, 100), 0 : 2 : complex(0, 100)]
pcm = plt.pcolormesh(
    X,
    Y,
    (1 + np.sin(Y * 10.0)) * X**2,
    norm=matplotlib.colors.PowerNorm(gamma=0.5),
    cmap="Blues_r",
    shading="auto",
)

# Plot evenly spaced colorbar
proportional_colorbar()
erlab.plotting.erplot.scale_units(ax, axis, si=0, *, prefix=True, power=False)[source]

Rescales ticks and adds an SI prefix to the axis label.

Useful when you want to rescale the ticks without actually rescaling the data. For example, when plotting a cut from a low pass energy scan, you might want to convert the energy units from eV to meV.

Using this function on an axis where the major locator is not the default formatter matplotlib.ticker.ScalarFormatter will result in undefined behavior.

Parameters:
  • ax (Axes | Iterable[Axes]) – Axes or iterable of Axes to rescale.

  • axis (Literal['x', 'y', 'z']) – The axis you wish to rescale.

  • si (int, default: 0) – Exponent of 10 corresponding to a SI prefix.

  • prefix (bool, default: True) – If True, tries to detect the unit from the axis label and scales it accordingly. The scaling behaviour is controlled by the power argument. If no units are found in the axis label, it is silently ignored.

  • power (bool, default: False) – If False, prefixes the detected unit on the axis label with a SI prefix corresponding to si. If True, the unit is prefixed with a scientific notation instead.

erlab.plotting.erplot.set_titles(axes, labels, order='C', **kwargs)[source]

Set titles for multiple axes.

Parameters:
  • axes – Axes to set titles for.

  • labels (Iterable[str] | str) – Title strings to set. If a single string is given, it will be used for all axes.

  • order (default: "C") – Order in which to flatten ax. ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran-style) order. The default is ‘C’.

  • **kwargs – Extra arguments to matplotlib.axes.Axes.set_title: refer to the matplotlib documentation for a list of all possible arguments.

erlab.plotting.erplot.set_xlabels(axes, labels, order='C', **kwargs)[source]

Set x-axis labels for multiple axes.

Parameters:
  • axes – Axes to set x-axis labels for.

  • labels (Iterable[str] | str) – Label strings to set. If a single string is given, it will be used for all axes.

  • order (default: "C") – Order in which to flatten ax. ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran-style) order. The default is ‘C’.

  • **kwargs – Extra arguments to matplotlib.axes.Axes.set_xlabel: refer to the matplotlib documentation for a list of all possible arguments.

erlab.plotting.erplot.set_ylabels(axes, labels, order='C', **kwargs)[source]

Set y-axis labels for multiple axes.

Parameters:
  • axes – Axes to set y-axis labels for.

  • labels (Iterable[str] | str) – Label strings to set. If a single string is given, it will be used for all axes.

  • order (default: "C") – Order in which to flatten ax. ‘C’ means to flatten in row-major (C-style) order. ‘F’ means to flatten in column-major (Fortran-style) order. The default is ‘C’.

  • **kwargs – Extra arguments to matplotlib.axes.Axes.set_ylabel: refer to the matplotlib

erlab.plotting.erplot.sizebar(ax, value, unit, si=0, resolution=1.0, decimals=0, label=None, loc='lower right', pad=0.1, borderpad=0.5, sep=3.0, frameon=False, **kwargs)[source]

Add a size bar to an axes.

Parameters:
  • ax (Axes) – The matplotlib.axes.Axes instance to place the size bar in.

  • value (float) – Length of the size bar in terms of unit.

  • unit (str) – An SI unit string without any prefixes. For example, ‘m’ for meters.

  • si (int, default: 0) – Exponents that have a corresponding SI prefix. This determines the unit of the label that is shown next to the size bar. For example, if the value is 200e-6 and the unit is "m", setting si=-6 will result in a label of "200 μm", and si=-3 will result in "0.2 mm" (assuming decimals is set appropriately).

  • resolution (float, default: 1.0) – Scale of the current axes coordinates. For example, if the plot axes values are given in μm, the resolution should be 1e-6.

  • decimals (int, default: 0) – Number of decimals displayed on the size bar label.

  • label (str | None, default: None) – When provided, overrides the automatically generated label string.

  • loc (Literal['upper left', 'upper center', 'upper right', 'center left', 'center', 'center right', 'lower left', 'lower center', 'lower right'], default: "lower right") – Location of the size bar.

  • pad (float, default: 0.1) – Padding around the label and size bar, in fraction of the font size.

  • borderpad (float, default: 0.5) – Border padding, in fraction of the font size.

  • sep (float, default: 3.0) – Separation between the label and the size bar, in points.

  • frameon (bool, default: False) – If True, draw a box around the horizontal bar and label.

  • **kwargs – Keyword arguments forwarded to mpl_toolkits.axes_grid1.anchored_artists.AnchoredSizeBar.

Example

>>> # Plot a size bar with a length of 200 μm on an axes given in mm
>>> eplt.sizebar(ax, value=200e-6, unit="m", si=-6, resolution=1e-3)
erlab.plotting.erplot.unify_clim(axes, target=None, image_only=False, autoscale=False, vmin=None, vmax=None)[source]

Unify the color limits for mappables in multiple axes.

Parameters:
  • axes (Sequence[Axes]) – Array of matplotlib.axes.Axes to unify the color limits.

  • target (Axes | _ScalarMappable | None, default: None) – The target axis to unify the color limits. If provided, the target color limits will be taken from this axes. Otherwise, the color limits will be set to include all mappables in the axes. Instead of an axes, a mappable can also be provided.

  • image_only (bool, default: False) – If True, only consider mappables that are images. Default is False.

  • autoscale (bool, default: False) – If True, the color limits will be determined from the minimum and maximum values of the plotted data. Otherwise, the color limits will be determined by the vmin and vmax of the norm applied to the target mappable.

  • vmin (float | None, default: None) – If provided, the color limits will be set to these values.

  • vmax (float | None, default: None) – If provided, the color limits will be set to these values.