erlab.plotting.colors¶
Utilities related to manipulating colors.
Colormaps¶
In addition to the default matplotlib colormaps, cmasher, cmocean, colorcet, and cmcrameri can be installed to extend the available colormaps.
Colormap Normalization¶
Demonstration of InversePowerNorm.¶
Demonstration of CenteredPowerNorm and CenteredInversePowerNorm.¶
Functions
|
Determine the text color based on the color of the mappable in an axes. |
Check if a given color is closer to white than black. |
|
|
Calculate the color distance between two matplotlib colors. |
|
Stitch two existing colormaps to create a new colormap. |
|
Flatten the transparency of an RGBA image by blending it with a background color. |
|
Generate a 2D colormap image from lightness and color data. |
|
Get the |
|
Determine if an image is light or dark. |
|
Create a colorbar with fixed width and aspect to ensure uniformity of plots. |
|
Calculate the prominent color of an image. |
|
Replace the current colorbar or creates a new colorbar with proportional spacing. |
|
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.colors.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.colors.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.colors.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.colors.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.colors.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.colors.axes_textcolor(ax, light='k', dark='w')[source]¶
Determine the text color based on the color of the mappable in an axes.
- Parameters:
ax (
matplotlib.axes.Axes) – The axes object for which the text color needs to be determined.light (
ColorType) – The light color, returned whenimage_is_lightreturnsFalse. Default is'k'(white).dark (
ColorType) – The dark color, returned whenimage_is_lightreturnsTrue. Default is'w'(black).
- erlab.plotting.colors.close_to_white(c)[source]¶
Check if a given color is closer to white than black.
- erlab.plotting.colors.color_distance(c1, c2)[source]¶
Calculate the color distance between two matplotlib colors.
- Parameters:
c1 (
ColorType) – Color to calculate the distance between in any format thatmatplotlib.colors.to_rgb()can handle.c2 (
ColorType) – Color to calculate the distance between in any format thatmatplotlib.colors.to_rgb()can handle.
- Returns:
distance (
float) – The color distance between the two colors.- Return type:
Note
The color distance is calculated using the Euclidean distance formula in the RGB color space. The formula takes into account the perceptual differences between colors.
See also
-
- erlab.plotting.colors.combined_cmap(cmap1, cmap2, name, register=False, N=256)[source]¶
Stitch two existing colormaps to create a new colormap.
This was implemented before
cmasher.combine_cmaps()existed. Using that might be better.- Parameters:
cmap1 (
Colormap|str) – The first colormap to be combined. Can be either amatplotlib.colors.Colormapor a string representing the name of a registered colormap.cmap2 (
Colormap|str) – The second colormap to be combined. Can be either amatplotlib.colors.Colormapor a string representing the name of a registered colormap.name (
str) – The name of the combined colormap.register (
bool, default:False) – Whether to register the combined colormap. Defaults toFalse.N (default:
256) – The number of colors in the resulting colormap. Defaults to 256.
- Returns:
matplotlib.colors.Colormap– The combined colormap.- Return type:
- erlab.plotting.colors.flatten_transparency(rgba, background=None)[source]¶
Flatten the transparency of an RGBA image by blending it with a background color.
- erlab.plotting.colors.gen_2d_colormap(ldat, cdat, cmap=None, *, lnorm=None, cnorm=None, background=None, N=256)[source]¶
Generate a 2D colormap image from lightness and color data.
- Parameters:
ldat (
array-like) – The lightness data.cdat (
array-like) – The color data. Must have the same shape asldat.cmap (
Colormap|str|None, default:None) – The colormap to use for the color axis. IfNone, a predefined linear segmented colormap is used.lnorm (
Normalize|None, default:None) – The normalization for the lightness axes.cnorm (
Normalize|None, default:None) – The normalization for the color axes.background (
ColorType, optional) – The background color. IfNone, it is set to white.N (
int, default:256) – The number of levels in the colormap. Default is 256. The resulting colormap will have a shape of(N, N, 4), where the last dimension represents the RGBA values.
- Returns:
cmap_img (
array-like) – RGBA image of the colormap.img (
array-like) – RGBA image with the 2D colormap applied.
- erlab.plotting.colors.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.colors.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.colors.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.colors.prominent_color(im)[source]¶
Calculate the prominent color of an image.
This function calculates the prominent color of an image by finding the most frequent color in the image’s histogram in color space. If the image array is
None, returns white.
- erlab.plotting.colors.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.colors.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.