erlab.plotting.erplot¶
Deprecated convenience module for plotting. Use erlab.plotting instead.
Functions
|
Clean the labels of the given axes. |
|
Copy math equations to the clipboard as SVG. |
|
Apply pretty labels to Matplotlib axes based on their current label text. |
|
Plot a constant energy line to denote the Fermi level. |
|
|
|
Flatten the transparency of an RGBA image by blending it with a background color. |
|
Get the |
|
Apply a gradient fill to a line plot. |
|
Determine if an image is light or dark. |
|
Set the ticks on the x and y axes to only display integer values. |
|
Labels subplots with automatically generated labels. |
|
Labels subplots with automatically generated labels. |
|
Mark points above the horizontal axis. |
|
Mark points above the horizontal axis. |
|
Create a colorbar with fixed width and aspect to ensure uniformity of plots. |
|
Easy placement of inset axes. |
|
Plot a 2D |
|
Plot a 2D array with associated color array. |
|
Plot a 2D hexagonal BZ overlay on the specified axes. |
|
Automated comparison plot of slices. |
|
Generate labels from a dictionary of values. |
|
Replace the current colorbar or creates a new colorbar with proportional spacing. |
|
Rescales ticks and adds an SI prefix to the axis label. |
|
Set titles for multiple axes. |
|
Set x-axis labels for multiple axes. |
|
Set y-axis labels for multiple axes. |
|
Add a size bar to an axes. |
|
Unify the color limits for mappables in multiple axes. |
Classes
|
Inverse power-law normalization of symmetrical data around a center. |
|
Power-law normalization of symmetrical data around a center. |
|
Inverse power-law normalization. |
|
Inverse power-law normalization of data with a set center. |
|
Power-law normalization of data with a set center. |
- class erlab.plotting.erplot.CenteredInversePowerNorm(gamma, vcenter=0, halfrange=None, clip=False)[source]¶
Bases:
CenteredPowerNormInverse power-law normalization of symmetrical data around a center.
Unlike
TwoSlopeInversePowerNorm,CenteredInversePowerNormapplies 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 defines0.5in the normalization. Defaults to0.halfrange (
float|None, default:None) – The range of data values that defines a range of0.5in the normalization, so thatvcenter-halfrangeis0.0andvcenter+halfrangeis1.0in the normalization. Defaults to the largest absolute difference tovcenterfor the values in the dataset.clip (
bool, default:False) –If
Truevalues falling outside the range[vmin, vmax], are mapped to 0 or 1, whichever is closer, and masked values are set to 1. IfFalsemasked 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:
CenteredNormPower-law normalization of symmetrical data around a center.
Unlike
TwoSlopePowerNorm,CenteredPowerNormapplies 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 defines0.5in the normalization. Defaults to0.halfrange (
float|None, default:None) – The range of data values that defines a range of0.5in the normalization, so thatvcenter-halfrangeis0.0andvcenter+halfrangeis1.0in the normalization. Defaults to the largest absolute difference tovcenterfor the values in the dataset.clip (
bool, default:False) –If
Truevalues falling outside the range[vmin, vmax], are mapped to 0 or 1, whichever is closer, and masked values are set to 1. IfFalsemasked 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.InversePowerNorm(gamma, vmin=None, vmax=None, clip=False)[source]¶
Bases:
NormalizeInverse 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.PowerNormcalculates \(x^\gamma\), whereasInversePowerNormcalculates \(1-x^{1/\gamma}\). This provides higher contrast for values closer tovmin.- Parameters:
gamma (
float) – Power law normalization parameter. If equal to 1, the colormap is linear.vmin (
float|None, default:None) – Ifvminand/orvmaxis not given, they are initialized from the minimum and maximum value, respectively, of the first input processed; i.e.,__call__(A)callsautoscale_None(A)vmax (
float|None, default:None) – Ifvminand/orvmaxis not given, they are initialized from the minimum and maximum value, respectively, of the first input processed; i.e.,__call__(A)callsautoscale_None(A)clip (
bool, default:False) –If
Truevalues falling outside the range[vmin, vmax], are mapped to 0 or 1, whichever is closer, and masked values are set to 1. IfFalsemasked 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.TwoSlopeInversePowerNorm(gamma, vcenter=0.0, vmin=None, vmax=None)[source]¶
Bases:
TwoSlopePowerNormInverse 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 defines0.5in the normalization. Defaults to0.vmin (
float|None, default:None) – The data value that defines0.0in the normalization. Defaults to the min value of the dataset.vmax (
float|None, default:None) – The data value that defines1.0in 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:
TwoSlopeNormPower-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 defines0.5in the normalization. Defaults to0.vmin (
float|None, default:None) – The data value that defines0.0in the normalization. Defaults to the min value of the dataset.vmax (
float|None, default:None) – The data value that defines1.0in the normalization. Defaults to the max value of the dataset.
- 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_outerrecursively instead of setting the labels to an empty string.- Parameters:
remove_inner_ticks (
bool, default:False) – IfTrue, 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:
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_NAMESandPRETTY_UNITS.- Parameters:
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) – Thematplotlib.axes.Axesto 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:
- Return type:
- 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.
- erlab.plotting.erplot.get_mappable(ax, index=-1, *, image_only=False, silent=False)[source]¶
Get the
matplotlib.cm.ScalarMappablefrom a givenmatplotlib.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 defaultFalse.silent (
bool, default:False) – IfFalse, raises aRuntimeErrorwhen no mappable is found. IfTrue, silently returnsNone.
- Returns:
- 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:
x (
Collection[float]) – Data of the plot to fill under.y (
Collection[float]) – Data of the plot to fill under.y0 (
float|None, default:None) – The minimum y value of the gradient. IfNone, defaults to the minimum ofy.color (
str|tuple[float,float,float] |tuple[float,float,float,float], default:"C0") – A valid matplotlib color to make the gradient from.cmap (
str|Colormap|None, default:None) – If given, ignorescolorand fills with the given colormap.transpose (
bool, default:False) – Transpose the gradient.reverse (
bool, default:False) – Reverse the gradient.ax (
Axes|None, default:None) – Thematplotlib.axes.Axesto plot in.**kwargs – Keyword arguments passed onto
matplotlib.axes.Axes.imshow().
- Returns:
- Return type:
- 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.
- 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.Axesto label. If an array is given, the order will be determined by the flattening method given byorder.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 byorder. 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 flattenax. ‘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.Axesto label. If an array is given, the order will be determined by the flattening method given byorder.values (
Iterable[int|str] |None, default:None) – Integer or string labels corresponding to each Axes inaxesfor manual labels.startfrom (
int, default:1) – Start from this number when creating automatic labels. Has no effect whenvaluesis notNone.order (
Literal['C','F','A','K'], default:"C") – Order in which to flattenax. ‘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 withloc, 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 thematplotlibdocumentation 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 aspoints.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 aspoints.pad (
tuple[float,float], default:(0, 1.75)) – Offset of the text in points.literal (
bool, default:False) – IfTrue, take the input string literally.roman (
bool, default:True) – IfFalse, itallic fonts are used.bar (
bool, default:False) – IfTrue, prints a bar over the label.ax (
Axes|Iterable[Axes] |None, default:None) –matplotlib.axes.Axesto annotate. IfNone, 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 aspoints.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) – IfTrue, take the input string literally.roman (
bool, default:True) – IfFalse, itallic fonts are used.bar (
bool, default:False) – IfTrue, prints a bar over the label.ax (
Axes|Iterable[Axes] |None, default:None) –matplotlib.axes.Axesto annotate.**kwargs – Extra arguments to
matplotlib.text.Text: refer to thematplotlibdocumentation 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) – Thematplotlib.axes.Axesinstance 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) – IfFalse, the ticks and the ticklabels will be determined from the keyword arguments (the default). IfTrue, 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.Axesto place the inset axes.width (
float|str) – Size of the inset axes to create. Iffloat, specifies the size in inches, e.g.1.3. Ifstr, specifies the size in relative units, e.g.'40%'ofparent_axes.height (
float|str) – Size of the inset axes to create. Iffloat, specifies the size in inches, e.g.1.3. Ifstr, specifies the size in relative units, e.g.'40%'ofparent_axes.pad (
float|tuple[float,float], default:0.1) – Padding betweenparent_axesand 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:
- Return type:
- 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.DataArrayusingmatplotlib.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-dimensionalxarray.DataArraywith evenly spaced coordinates.ax (
Axes|None, default:None) – The targetmatplotlib.axes.Axes.colorbar (
bool, default:False) – Whether to plot a colorbar.colorbar_kw (
dict|None, default:None) – Keyword arguments passed ontoerlab.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 singlefloat, the limits are set as(-lim, lim). IfNone, 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 singlefloat, the limits are set as(-lim, lim). IfNone, automatically determines the limits from the data.rad2deg (
bool|Iterable[str], default:False) – IfTrue, converts some known angle coordinates from radians to degrees. If an iterable ofstris 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 ontofunc.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 amatplotlib.image.NonUniformImageinstead of amatplotlib.image.AxesImage.rtolandatolare the tolerances for the coordinates to be considered evenly spaced. The default values are consistent withnumpy.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 amatplotlib.image.NonUniformImageinstead of amatplotlib.image.AxesImage.rtolandatolare the tolerances for the coordinates to be considered evenly spaced. The default values are consistent withnumpy.isclose.rasterized (
bool, default:True) – Force rasterized output.**improps – Keyword arguments passed onto
matplotlib.pyplot.imshow().
- Returns:
- Return type:
Notes
Some keyword arguments have different default behavior compared to matplotlib.
interpolationis set to'none'for evenly spaced data and'nearest'for nonuniform data.aspectis set to'auto'.originis 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 isTrue.cax (
Axes|None, default:None) – The axes on which to create the colorbar ifcolorbarisTrue. If None, a new axes will be created for the colorbar.colorbar_kw (
dict|None, default:None) – Additional keyword arguments to pass tomatplotlib.pyplot.colorbar.imshow_kw (
dict|None, default:None) – Additional keyword arguments to pass tomatplotlib.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.rtolandatolare the tolerances for the coordinates to be considered evenly spaced. The default values are consistent withnumpy.isclose.atol (
float, default:1.0e-8) – By default, the input array is checked for evenly spaced coordinates.rtolandatolare the tolerances for the coordinates to be considered evenly spaced. The default values are consistent withnumpy.isclose.**indexers_kwargs (
dict) – Additional keyword arguments to pass toqselto select the data to plot. Note that the resulting data after the selection must be 2D.
- Returns:
im (
matplotlib.image.AxesImage) – The plotted image.cb (
matplotlib.colorbar.ColorbarorNone) – The colorbar associated with the plot. Ifcolorbaris False, None is returned.
- Return type:
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) – IfTrue,ais 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. IfNone, 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:
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 singlefloat, the limits are set as(-lim, lim). IfNone, 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 singlefloat, the limits are set as(-lim, lim). IfNone, automatically determines the limits from the data.crop (
bool, default:True) – IfTrue, crops the data to the limits given byxlimandylimprior to plotting.same_limits (
bool|Literal['row','col','all'], default:False) – IfTrue, 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 toTrue.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) – IfTrue, shows every xlabel and ylabel. IfFalse, labels on shared axes are minimized. WhenFalseand theaxesargument is given, theordermust 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) – IfTrue, hides colorbar ticks.annotate (
bool, default:True) – IfFalse, turn off automatic annotation.cmap (
str|Colormap|Iterable[str|Colormap|Iterable[Colormap|str]] |None, default:None) – If supplied a singlestrormatplotlib.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 singlematplotlib.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 forcmap, Defaults to'C'.norm_order (
Literal['C','F'] |None, default:None) – The order to flatten when given a nested sequence fornorm, Defaults tocmap_order.gradient (
bool, default:False) – IfTrue, 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 togradient_fill().subplot_kw (
dict|None, default:None) – Extra arguments tomatplotlib.pyplot.subplots(): refer to thematplotlibdocumentation for a list of all possible arguments.annotate_kw (
dict|None, default:None) – Extra arguments toerlab.plotting.annotations.label_subplot_properties(). Only applied whenannotateisTrue.colorbar_kw (
dict|None, default:None) – Extra arguments toerlab.plotting.colors.proportional_colorbar().axes (
Iterable[Axes] |None, default:None) – A nested sequence ofmatplotlib.axes.Axes. If supplied, the returnedmatplotlib.figure.Figureis 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:
fig (
matplotlib.figure.Figure)axes (
array-likeofmatplotlib.axes.Axes)
- Return type:
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 byorder. 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 flattenax. ‘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
matplotlibdoes not support colors proportional to data in different norms. This function circumvents this behavior.- Parameters:
mappable (
_ScalarMappable|None, default:None) – Thematplotlib.cm.ScalarMappabledescribed 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, ifcaxisNone. This has no effect ifcaxis set. IfmappableisNoneandaxis given with more than one Axes, the function will try to infer the mappable from the first one.index (
int, default:-1) – Ifmappableis not provided, the index of the mappable to get fromax. Passed toget_mappable(). Default is -1, i.e., the most recently added mappable.image_only (
bool, default:False) – Ifmappableis not provided, whether to only consider images as valid mappables when inferring fromax. Passed toget_mappable(). Default isFalse.**kwargs – Extra arguments to
matplotlib.pyplot.colorbar: refer to thematplotlibdocumentation for a list of all possible arguments.
- Returns:
cbar (
matplotlib.colorbar.Colorbar) – The created colorbar.- Return type:
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.ScalarFormatterwill 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 thepowerargument. 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 tosi. 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 flattenax. ‘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 thematplotlibdocumentation 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 flattenax. ‘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 thematplotlibdocumentation 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 flattenax. ‘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 thematplotlib
- 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) – Thematplotlib.axes.Axesinstance to place the size bar in.value (
float) – Length of the size bar in terms ofunit.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 thevalueis200e-6and the unit is"m", settingsi=-6will result in a label of"200 μm", andsi=-3will result in"0.2 mm"(assumingdecimalsis 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 ofmatplotlib.axes.Axesto 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 theaxes. Instead of an axes, a mappable can also be provided.image_only (
bool, default:False) – IfTrue, only consider mappables that are images. Default isFalse.autoscale (
bool, default:False) – IfTrue, 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.