erlab.plotting.colors¶
Utilities related to manipulating colors.
Colormaps¶
In addition to the default matplotlib colormaps, cmasher, cmocean, and
colorcet packages can be installed to extend the
available colormaps. If these packages are installed, they will be automatically
imported upon importing erlab.plotting
.
Colormap Normalization¶
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:
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) – The data value that defines
0.5
in the normalization. Defaults to0
.halfrange (float | None) – The range of data values that defines a range of
0.5
in the normalization, so thatvcenter
-halfrange
is0.0
andvcenter
+halfrange
is1.0
in the normalization. Defaults to the largest absolute difference tovcenter
for the values in the dataset.clip (bool) –
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. IfFalse
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.colors.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) – The data value that defines
0.5
in the normalization. Defaults to0
.halfrange (float | None) – The range of data values that defines a range of
0.5
in the normalization, so thatvcenter
-halfrange
is0.0
andvcenter
+halfrange
is1.0
in the normalization. Defaults to the largest absolute difference tovcenter
for the values in the dataset.clip (bool) –
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. IfFalse
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.colors.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\), whereasInversePowerNorm
calculates \(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) – If
vmin
and/orvmax
is 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) – If
vmin
and/orvmax
is 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) –
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. IfFalse
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.colors.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) – The data value that defines
0.5
in the normalization. Defaults to0
.vmin (float | None) – The data value that defines
0.0
in the normalization. Defaults to the min value of the dataset.vmax (float | None) – The data value that defines
1.0
in 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:
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) – The data value that defines
0.5
in the normalization. Defaults to0
.vmin (float | None) – The data value that defines
0.0
in the normalization. Defaults to the min value of the dataset.vmax (float | None) – The data value that defines
1.0
in 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_light
returnsFalse
. Default is'w'
(white).dark (
ColorType
) – The dark color, returned whenimage_is_light
returnsTrue
. Default is'k'
(black).
- erlab.plotting.colors.close_to_white(c)[source]¶
Check if a given color is closer to white than black.
- Parameters:
c (
ColorType
) – Color in any format thatmatplotlib.colors.to_rgb()
can handle.- Returns:
True
if the color is closer to white than black,False
otherwise.- Return type:
- 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 – 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 a
matplotlib.colors.Colormap
or a string representing the name of a registered colormap.cmap2 (Colormap | str) – The second colormap to be combined. Can be either a
matplotlib.colors.Colormap
or a string representing the name of a registered colormap.name (str) – The name of the combined colormap.
register (bool) – Whether to register the combined colormap. Defaults to
False
.N – The number of colors in the resulting colormap. Defaults to 256.
- Returns:
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.
- Parameters:
rgba (ndarray[Any, dtype[_ScalarType_co]]) – The input RGBA image as a numpy array.
background (
RGBColorType
, optional) – The background color to blend with. Defaults to white.
- 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) – The colormap to use for the color axis. If
None
, a predefined linear segmented colormap is used.lnorm (Normalize | None) – The normalization for the lightness axes.
cnorm (Normalize | None) – The normalization for the color axes.
background (
ColorType
, optional) – The background color. IfNone
, it is set to white.N (int) – 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, image_only=False, silent=False)[source]¶
Get the
matplotlib.cm.ScalarMappable
from a givenmatplotlib.axes.Axes
.- Parameters:
- Return type:
- 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) – The
matplotlib.axes.Axes
instance in which the colorbar is drawn.mappable (ScalarMappable | None) – The mappable whose colormap and norm will be used.
width (float) – The width of the colorbar in points.
aspect (float) – aspect ratio of the colorbar.
pad (float) – The pad between the colorbar and axes in points.
minmax (bool) – If
False
, 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']) – Colorbar orientation.
**kwargs – Keyword arguments are passed to
proportional_colorbar
.
- Returns:
cbar – The created colorbar.
- Return type:
- 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, **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) – The
matplotlib.cm.ScalarMappable
described by this colorbar.cax (Axes | None) – Axes into which the colorbar will be drawn.
ax (Axes | Iterable[Axes] | None) – One or more parent axes from which space for a new colorbar axes will be stolen, if
cax
isNone
. This has no effect ifcax
is set. Ifmappable
isNone
andax
is given with more than one Axes, the function will try to infer the mappable from the first one.**kwargs – Extra arguments to
matplotlib.pyplot.colorbar
: refer to thematplotlib
documentation for a list of all possible arguments.
- Returns:
cbar – 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)[source]¶
Unify the color limits for mappables in multiple axes.
- Parameters:
axes (ndarray) – Array of
matplotlib.axes.Axes
to unify the color limits.target (Axes | 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
.image_only (bool) – If
True
, only consider mappables that are images. Default isFalse
.