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

(Source code)

../_images/norms_example_1.pdf

Demonstration of InversePowerNorm.

(Source code)

../_images/norms_example_2.pdf

Demonstration of CenteredPowerNorm and CenteredInversePowerNorm.

Functions

axes_textcolor(ax[, light, dark])

Determine the text color based on the color of the mappable in an axes.

close_to_white(c)

Check if a given color is closer to white than black.

color_distance(c1, c2)

Calculate the color distance between two matplotlib colors.

combined_cmap(cmap1, cmap2, name[, register, N])

Stitch two existing colormaps to create a new colormap.

flatten_transparency(rgba[, background])

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

gen_2d_colormap(ldat, cdat[, cmap, lnorm, ...])

Generate a 2D colormap image from lightness and color data.

get_mappable(ax[, image_only, silent])

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

image_is_light(im)

Determine if an image is light or dark.

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

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

prominent_color(im)

Calculate the prominent color of an image.

proportional_colorbar([mappable, cax, ax])

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

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.

InsetAxesLocator(ax, width, height, pad, loc)

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.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 to 0.

  • halfrange (float | 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) –

    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.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 to 0.

  • halfrange (float | 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) –

    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.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\), 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) – 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) – 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) –

    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.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 to 0.

  • 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 to 0.

  • 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.

__call__(value, clip=None)[source]

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

inverse(value)[source]
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:
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 that matplotlib.colors.to_rgb() can handle.

Returns:

True if the color is closer to white than black, False otherwise.

Return type:

bool

erlab.plotting.colors.color_distance(c1, c2)[source]

Calculate the color distance between two matplotlib colors.

Parameters:
Returns:

distance – The color distance between the two colors.

Return type:

float

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:

matplotlib.colors.Colormap

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 as ldat.

  • 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. If None, 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 given matplotlib.axes.Axes.

Parameters:
  • ax (Axes) – Parent axes.

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

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

Return type:

matplotlib.cm.ScalarMappable or 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) – 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). If True, 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:

matplotlib.colorbar.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, **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 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.

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

Returns:

cbar – The created colorbar.

Return type:

matplotlib.colorbar.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.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 is False.