pycolorbar.univariate package#

Submodules#

pycolorbar.univariate.cmap module#

pycolorbar.univariate.cmap.adapt_cmap(cmap, *, interval=None, n=None, alpha=None, bias=1)[source][source]#

Adapt a colormap by subsetting its colors and applying transparency, if specified.

Parameters:
  • cmap (matplotlib.colors.Colormap) – The original colormap to adapt (e.g., LinearSegmentedColormap or ListedColormap).

  • interval (tuple of float, optional) – A tuple (start, end) with values between 0 and 1, indicating the fraction of the colormap to use. Defaults to using the full colormap (0, 1).

  • n (int, optional) – The number of colors to return. If None, the colormap is not resampled.

  • alpha (float, optional) – A transparency value to apply to the colors, where 0 is fully transparent and 1 is fully opaque. If alpha is None (the default), the original transparency of the colors is preserved.

  • bias (float, optional) – A factor that skews the distribution of colors in the colormap. A bias of 1 (default) results in no bias. Values less than 1 space the colors more widely at the high end of the color map. Values greater than 1 space the colors more widely at the lower end of the colormap.

Returns:

A new colormap that reflects the specified interval, n, alpha and bias values.

Return type:

matplotlib.colors.Colormap

Notes

  • The function creates a new colormap by extracting a subset of the colors from the original colormap.

  • The resulting colormap has the same name as the original, unless specified otherwise in the internal logic.

pycolorbar.univariate.cmap.check_interval(interval)[source][source]#

Validate that the interval is within the range [0, 1].

Parameters:

interval (tuple or None) – A tuple of two float values between 0 and 1 representing the range of the colormap. If None, the interval is set to (0, 1).

Returns:

Validated interval.

Return type:

tuple

Raises:

ValueError – If the interval is not within the range [0, 1] or if the first value is greater than or equal to the second.

pycolorbar.univariate.cmap.combine_cmaps(cmaps: list[Colormap | str], *, nodes: list[float] | ndarray | None = None, n=None, output_n: int = 256, name: str = 'combined_cmap') LinearSegmentedColormap[source][source]#

Create a composite matplotlib colormap by combining multiple colormaps.

Parameters:
  • cmaps (list) – List of matplotlib.Colormap or registered colormap names to be combined.

  • nodes (list of float or np.ndarray, optional) – Blending points between colormaps, in the range [0, 1]. Nodes values should be one less than the number of colormaps. Defaults to equal divisions if None.

  • n (list of int or None, optional) – Number of colors for each colormap. Defaults to None, which uses the original number of colors for each colormap.

  • output_n (int, optional) – Number of colors in the output colormap. Default is 256.

  • name (str, optional) – Name for the combined colormap. Default is “combined_cmap”.

Returns:

The composite colormap created from the specified colormaps.

Return type:

LinearSegmentedColormap

Raises:
  • TypeError – If the list contains mixed datatypes or invalid colormap names.

  • ValueError – If the cmaps contain only one single colormap, or if the number of nodes is not one less than the number of colormaps, or if the nodes do not contain incrementing values between 0.0 and 1.0.

Notes

The colormaps are combined from low value to high value end. Code adapted from CMasher (1313e/CMasher).

Examples

Using predefined colormap names:

custom_cmap_1 = combine_cmaps(

[“ocean”, “prism”, “coolwarm”], nodes=[0.2, 0.75]

)

Using Colormap objects:

cmap_0 = plt.get_cmap(“Blues”) cmap_1 = plt.get_cmap(“Oranges”) cmap_2 = plt.get_cmap(“Greens”) custom_cmap_2 = combine_cmaps([cmap_0, cmap_1, cmap_2])

pycolorbar.univariate.cmap.get_cmap_colors(cmap, *, interval=None, n=None, alpha=None, bias=1)[source][source]#

Retrieve a list of RGB colors from a colormap, optionally subsetting by an interval and number of colors (n).

Parameters:
  • cmap (matplotlib.colors.Colormap) – A colormap instance (e.g., LinearSegmentedColormap or ListedColormap).

  • interval (tuple of float, optional) – A tuple (start, end) with values between 0 and 1, representing the fraction of the colormap to retain. Defaults to the full colormap (0, 1).

  • n (int, optional) – Number of colors to return. If None, the number of colors depends on the colormap (default: None).

  • alpha (float, optional) – A transparency value to apply to the colors, where 0 is fully transparent and 1 is fully opaque. If alpha is None (the default), the original transparency of the colors is preserved. If provided, all colors will be updated to have the specified alpha value.

  • bias (float, optional) – A factor that skews the distribution of colors in the colormap. A bias of 1 (default) results in no bias. Values less than 1 space the colors more widely at the high end of the color map. Values greater than 1 space the colors more widely at the lower end of the colormap.

Returns:

A NumPy array of RGB colors extracted from the colormap.

Return type:

np.ndarray

Notes

  • If the colormap is a LinearSegmentedColormap and does not have an N attribute, 256 colors are returned.

  • If interval is provided, only the specified range of the colormap will be returned.

pycolorbar.univariate.cmap.get_cmap_lab(cmap)[source][source]#

Convert a colormap’s RGB values into the CAM02-UCS color space.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

A NumPy array of LAB values corresponding to the colormap’s colors in the CAM02-UCS color space. The LAB values represent Lightness (L) and color components (A, B) in a perceptually uniform space.

Return type:

np.ndarray

Raises:

ImportError – If the colorspacious package is not installed.

Notes

This function converts the RGB values of the input colormap into the CAM02-UCS color space, which is designed to provide perceptually uniform color information, meaning that equal distances in this color space correspond to equal perceptual differences. The conversion is done using the colorspacious package.

The LAB values consist of: - L: Lightness - A and B: Unique color components

Examples

>>> import matplotlib.pyplot as plt
>>> from matplotlib import cm
>>> cmap = cm.viridis
>>> lab = get_cmap_lab(cmap)
>>> print(lab)
pycolorbar.univariate.cmap.get_cmap_lightness(cmap)[source][source]#

Extract the lightness component of a colormap using the CAM02-UCS color space.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

lightness – A 1D array of lightness values corresponding to the colors in the colormap. These values are derived from the CAM02-UCS color space’s lightness (L) component.

Return type:

ndarray

Raises:

ImportError – If the colorspacious package is not installed, an error is raised.

Notes

The function converts the RGB values of the input colormap into the CAM02-UCS color space, which provides perceptually uniform color information. The lightness component (L) is then extracted and returned as a 1D array.

Examples

>>> import matplotlib.pyplot as plt
>>> from matplotlib import cm
>>> cmap = cm.viridis
>>> lightness = get_cmap_lightness(cmap)
>>> print(lightness)
pycolorbar.univariate.cmap.get_cmap_segmentdata(cmap, n=None)[source][source]#

Retrieve the segment data of a colormap, or generate it if not present.

Parameters:
  • cmap (matplotlib.colors.Colormap) – A colormap instance (e.g., LinearSegmentedColormap or ListedColormap).

  • n (int, optional) – The number of discrete points to sample from the colormap. If None, the colormap’s N attribute is used.

Returns:

A dictionary representing the colormap’s segment data for red, green, and blue channels. Each entry in the dictionary corresponds to a list of (x, y0, y1) tuples, where: - x is the position (0 to 1) along the colormap. - y0 is the color value to the left of x. - y1 is the color value to the right of x.

Return type:

dict

Notes

  • The segment data is used to create LinearSegmentedColormap objects.

  • If the colormap has a _segmentdata attribute, it is returned directly.

  • If the colormap is sampled using n points, this function constructs the segment data manually.

pycolorbar.univariate.cmap.get_cvd_cmap(cmap, *, cvd_type, severity=50)[source][source]#

Return a Matplotlib colormap emulating a specified color-vision deficiency (CVD).

This function simulates how the colormap would appear to someone with a particular type of color-vision deficiency using the colorspacious package.

Parameters:
  • cmap (matplotlib.colors.Colormap) – The input colormap to be converted. It can be an instance of either ListedColormap or LinearSegmentedColormap.

  • cvd_type (str) – The type of color-vision deficiency to simulate. Valid options are: ‘deuteranomaly’, ‘protanomaly’, and ‘tritanomaly’.

  • severity (int, optional) – The severity of the color-vision deficiency on a scale from 0 (no deficiency) to 100 (complete deficiency), by default 50. For people suffering of tritanomaly, only severity = 100 actually exists in reality.

Returns:

A new colormap that simulates the appearance of the input colormap for individuals with the specified color-vision deficiency.

Return type:

matplotlib.colors.Colormap

Examples

>>> import matplotlib.pyplot as plt
>>> from matplotlib.colors import get_cmap
>>> cmap = get_cmap("viridis")
>>> cvd_cmap = get_cvd_cmap(cmap, cvd_type="deuteranomaly", severity=50)
>>> plt.imshow([list(range(256))], cmap=cvd_cmap)
>>> plt.show()

Notes

This function relies on the colorspacious package to perform color conversions. Make sure to install it using conda install -c conda-forge colorspacious if not already available.

pycolorbar.univariate.cmap.get_gray_cmap(cmap)[source][source]#

Convert a given colormap to its grayscale equivalent.

Grayscale conversion is based on the lightness component of CAM02-UCS color space.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

cmap_gray – The grayscale version of the input colormap, where the RGB values are set based on the lightness of the corresponding color in the CAM02-UCS color space. If the original colormap includes transparency (alpha), it is preserved.

Return type:

matplotlib.colors.Colormap

Raises:

ImportError – If the colorspacious package is not installed, an error is raised.

Notes

This function uses the CAM02-UCS color space to convert the colors of the input colormap to grayscale based on their perceived lightness. The grayscale colors are created by setting the R, G, and B channels to the normalized lightness values. If the original colormap contains an alpha channel, it is maintained in the resulting grayscale colormap.

Examples

>>> import matplotlib.pyplot as plt
>>> from matplotlib import cm
>>> cmap = cm.viridis
>>> cmap_gray = get_gray_cmap(cmap)
>>> plt.imshow([[0, 1]], cmap=cmap_gray)
>>> plt.show()
pycolorbar.univariate.cmap.get_shifted_cmap(cmap)[source][source]#

Shift the colors of a cyclic colormap, centering the midpoint of the color range.

This function is useful for cyclic colormaps, such as those representing angles or phases, where the start and end colors should seamlessly wrap around. The function shifts the colormap so that the midpoint of the color range becomes the new start.

Parameters:

cmap (matplotlib.colors.Colormap) – The original cyclic colormap to shift.

Returns:

A new colormap with its colors shifted so that the midpoint of the original colormap becomes the new starting point.

Return type:

matplotlib.colors.Colormap

Notes

  • This function is particularly useful for cyclic colormaps where symmetry or phase is important.

  • It works by dividing the colormap at its midpoint and swapping the two halves.

pycolorbar.univariate.cmap.infer_cmap_type(cmap)[source][source]#

Infer the type of a colormap based on its lightness values and color differences.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

A string indicating the type of colormap: - ‘misc’ if the colormap does not fit other categories. - ‘sequential’ if lightness values always increase or decrease. - ‘diverging’ if the colormap has a central extreme with sequential sides. - ‘cyclic’ if the perceptual differences between colors indicate a repeating pattern. - ‘isoluminant’ if all lightness values are the same.

Return type:

str

Notes

This function analyzes the lightness and color differences of the colormap to classify it into one of several categories: sequential, diverging, cyclic, or miscellaneous. It is adapted from the cmasher library’s get_cmap_type function.

pycolorbar.univariate.cmap.is_cyclic_cmap(cmap)[source][source]#

Check if the colormap is of type ‘cyclic’.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

True if the colormap is cyclic, False otherwise.

Return type:

bool

pycolorbar.univariate.cmap.is_diverging_cmap(cmap)[source][source]#

Check if the colormap is of type ‘diverging’.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

True if the colormap is diverging, False otherwise.

Return type:

bool

pycolorbar.univariate.cmap.is_isoluminant_cmap(cmap)[source][source]#

Check if the colormap is of type ‘isoluminant’.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

True if the colormap is isoluminant, False otherwise.

Return type:

bool

pycolorbar.univariate.cmap.is_sequential_cmap(cmap)[source][source]#

Check if the colormap is of type ‘sequential’.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

True if the colormap is sequential, False otherwise.

Return type:

bool

pycolorbar.univariate.cmap_cyclic module#

pycolorbar.univariate.cmap_cyclic.get_discrete_cyclic_cmap(cmap, n)[source][source]#

Create a discrete cyclic color palette.

pycolorbar.univariate.cmap_cyclic.plot_circular_colormap(cmap, r_min=0.2, r_max=1, ax=None, add_title=True, antialiased=False, clockwise=True, zero_location='N', add_contour=True, contour_color='black', contour_linewidth=None, n_cycles=0, amplitude=0.6283185307179586, power=4)[source][source]#

Plot a circular colormap with an optional sinusoidal pattern.

Parameters:
  • cmap (matplotlib.colors.Colormap) – The colormap to be used for the plot.

  • r_min (float, optional) – The minimum radius for the colormap circle. The default value is 0.2.

  • r_max (float, optional) – The maximum radius for the colormap circle. The default value is 1.

  • ax (matplotlib.axes._subplots.PolarAxesSubplot, optional) – The polar axis on which to plot. If None, a new figure and axis are created. The default is None.

  • antialiased (bool, optional) – Whether to apply antialiasing to the pcolormesh plot. Default is False.

  • add_title (bool, optional) – Whether to add the colormap name as a title. Default is True.

  • clockwise (bool, optional) – If True, the angles increase in the clockwise direction. Default is True.

  • zero_location (str, optional) – The location of the zero angle. For example, “N” for North. Default is “N”.

  • add_contour (bool, optional) – Whether to add contour lines at the inner and outer boundaries. The default is True..

  • contour_color (str or color, optional) – The color of the contour lines. Default is “black”.

  • contour_linewidth (float, optional) – The linewidth of the contour lines. If None, the default linewidth is used.

  • n_cycles (int, optional) – The number of sine wave cycles in the radial direction. Set to 0 to omit the spiral pattern. The default is 0.

  • amplitude (float, optional) – Amplitude of the sine wave component in the spiral pattern. The default value is np.pi/5.

  • power (int, optional) – Power of the radial distance in the spiral pattern. The default value is 4.

Returns:

The QuadMesh object representing the plotted circular colormap.

Return type:

matplotlib.collections.QuadMesh

References

Kovesi, P., 2015. “Good Colour Maps: How to Design Them.” arXiv preprint arXiv:1509.03700.

pycolorbar.univariate.cmap_viz module#

pycolorbar.univariate.cmap_viz.delta_e_cie2000(lab1, lab2)[source][source]#

Calculate the Delta E (CIEDE2000) color difference between two LAB colors.

Parameters:
  • lab1 (array-like, shape (3,)) – LAB color 1 in the format [L*, a*, b*].

  • lab2 (array-like, shape (3,)) – LAB color 2 in the format [L*, a*, b*].

Returns:

delta_e – The Delta E (CIEDE2000) color difference between the two LAB colors.

Return type:

float

Notes

This implementation follows the CIEDE2000 standard and is adapted from formulas described in Sharma et al. (2005).

pycolorbar.univariate.cmap_viz.plot_circular_colormaps(cmaps, cols=None, subplot_size=None, dpi=200, n_cycles=0, amplitude=0.6283185307179586, power=4, **plot_kwargs)[source][source]#

Plot a list of colormaps.

pycolorbar.univariate.cmap_viz.plot_colormap(cmap, dpi=200, ax=None, **plot_kwargs)[source][source]#

Plot a single colormap.

pycolorbar.univariate.cmap_viz.plot_colormaps(cmaps, cols=None, subplot_size=None, dpi=200, **plot_kwargs)[source][source]#

Plot a list of colormaps.

pycolorbar.univariate.cmap_viz.plot_deltae(cmap, ax=None, accurate=True, labelsize=6, ticksize=6, s=2, **plot_kwargs)[source][source]#

Plot the Delta E (CIE76) values of a colormap.

The Delta E represents the color difference between consecutive colors in the LAB color space.

Parameters:
  • cmap (matplotlib.colors.Colormap) – The colormap instance (e.g., LinearSegmentedColormap or ListedColormap) whose color differences will be plotted.

  • ax (matplotlib.axes.Axes, optional) – The axes on which to plot the Delta E values. If None, a new figure and axes will be created.

  • accurate (bool) – If True, compute the Delta E (CIEDE2000). IF False, compute the Delta E (CIE76) which corresponds to the Euclidean distance in the CIELAB color space.

  • labelsize (int, optional) – Font size for the labels. Default is 6.

  • ticksize (int, optional) – Font size for the tick labels. Default is 6.

  • s (int, optional) – Marker size for the scatter plot. Default is 2.

  • **plot_kwargs (keyword arguments) – Additional keyword arguments passed to ax.plot (e.g., line style, marker).

Returns:

ax – The axes with the Delta E plot.

Return type:

matplotlib.axes.Axes

Notes

  • Delta E (ΔE) is a measure of color difference in LAB color space.

  • This function uses the CIE76 formula to compute ΔE between consecutive colors in the colormap.

  • Typical ΔE values:
    • 0-1: Imperceptible difference.

    • 1-2: Perceptible only to trained eyes.

    • 2-10: Perceptible to the human eye.

    • 10+: Large difference.

Example

>>> cmap = plt.get_cmap("viridis")
>>> plot_deltae(cmap)
pycolorbar.univariate.cmap_viz.plot_lab_components(cmap, ax=None, add_legend=True, labelsize=6, ticksize=6, s=2, **plot_kwargs)[source][source]#

Plot the LAB components of a colormap.

Lightness (L*) is displayed on the left y-axis and A* and B* components on the right y-axis.

Parameters:
  • cmap (matplotlib.colors.Colormap) – The colormap instance (e.g., LinearSegmentedColormap or ListedColormap) whose RGB components will be plotted.

  • ax (matplotlib.axes.Axes, optional) – The axes on which to plot the LAB components. If None, a new figure and axes will be created.

  • labelsize (int, optional) – Font size for the labels. Default is 6.

  • ticksize (int, optional) – Font size for the tick labels. Default is 6.

  • s (int, optional) – Marker size for the scatter plot. Default is 2.

  • **plot_kwargs (keyword arguments) – Additional keyword arguments passed to ax.scatter (e.g., marker size, edge colors).

Returns:

ax – The axes with the RGB component plots.

Return type:

matplotlib.axes.Axes

pycolorbar.univariate.cmap_viz.plot_lightness(cmap, ax=None, difference=False, labelsize=6, ticksize=6, s=2, **plot_kwargs)[source][source]#

Plot the lightness values of a colormap.

Parameters:
  • cmap (matplotlib.colors.Colormap) – The colormap instance (e.g., LinearSegmentedColormap or ListedColormap) whose lightness will be plotted.

  • ax (matplotlib.axes.Axes, optional) – The axes on which to plot the lightness. If None, a new figure and axes will be created.

  • **plot_kwargs (keyword arguments) – Additional keyword arguments passed to ax.scatter (e.g., marker size, edge colors).

Returns:

ax – The axes with the lightness plot.

Return type:

matplotlib.axes.Axes

pycolorbar.univariate.cmap_viz.plot_rgb_components(cmap, ax=None, labelsize=6, ticksize=6, s=2, **plot_kwargs)[source][source]#

Plot the RGB components of a colormap.

Parameters:
  • cmap (matplotlib.colors.Colormap) – The colormap instance (e.g., LinearSegmentedColormap or ListedColormap) whose RGB components will be plotted.

  • ax (matplotlib.axes.Axes, optional) – The axes on which to plot the RGB components. If None, a new figure and axes will be created.

  • labelsize (int, optional) – Font size for the labels. Default is 6.

  • ticksize (int, optional) – Font size for the tick labels. Default is 6.

  • s (int, optional) – Marker size for the scatter plot. Default is 2.

  • **plot_kwargs (keyword arguments) – Additional keyword arguments passed to ax.scatter (e.g., marker size, edge colors).

Returns:

ax – The axes with the RGB component plots.

Return type:

matplotlib.axes.Axes

pycolorbar.univariate.cmap_viz.plot_viscm_diagnostic(cmap)[source][source]#

Evaluate goodness of colormap using perceptual deltas.

pycolorbar.univariate.colorbar module#

Module with functions to plot univariate colorbars.

pycolorbar.univariate.colorbar.add_colorbar_legend(*, mappable, ax, box_aspect=1, height=0.2, pad=0.005, loc='upper right', inside_figure=True, optimize_layout=True, fancybox=False, fancybox_pad=0, fancybox_fc='white', fancybox_ec='none', fancybox_lw=0.5, fancybox_alpha=0.4, fancybox_shape='square', **cbar_kwargs)[source][source]#

Add a univariate colorbar legend to a plot.

Parameters:
  • mappable – The matplotlib.cm.ScalarMappable (i.e., AxesImage, ContourSet, etc.) described by the colorbar.

  • ax (matplotlib.axes.Axes) – The axes to which the bivariate legend will be added.

  • box_aspect (float, optional) – Aspect ratio of the inset Axes. Default is 1.

  • height (float, optional) – Height of the inset as a fraction [0-1] of the main Axes. Default is 0.2.

  • pad (float, optional) – Padding between the inset and main Axes in figure coordinates. Default is 0.005.

  • loc (str or tuple, optional) – Location of the inset. Default is ‘upper right’.

  • inside_figure (bool, optional) – Whether inset is inside the figure region. Default is True.

  • optimize_layout (bool, optional) – Whether to auto-adjust the inset position for ticklabels. Default is True. NOTE: If True, do not call fig.tight_layout() afterwards.

  • fancybox (bool, optional) – Whether to draw a fancy box behind the inset. Default is False.

  • fancybox_pad (float, optional) – Padding of the fancy box in figure coordinates. Default is 0.

  • fancybox_fc (str, optional) – Face color of the fancy box. Default is ‘white’.

  • fancybox_ec (str, optional) – Edge color of the fancy box. Default is ‘none’.

  • fancybox_lw (float, optional) – Line width of the fancy box. Default is 0.5.

  • fancybox_alpha (float, optional) – Alpha of the fancy box. Default is 0.4.

  • fancybox_shape ({'circle', 'square'}, optional) – Shape of the fancy box. Default is ‘square’.

  • **kwargs (dict) – Additional keyword arguments passed to the matplotlib.figure.colorbar. See the matplotlib.figure.colorbar documentation.

Returns:

The image object representing the colorbar.

Return type:

matplotlib.image.AxesImage

pycolorbar.univariate.colorbar.plot_colorbar(p, *, ax=None, cax=None, **cbar_kwargs)[source][source]#

Add a univariate colorbar to a matplotlib/cartopy plot.

You can either provide:

  • An existing Axes (ax) in which to place the colorbar (the colorbar will be appended to one of its sides).

  • A dedicated Axes object (cax) for direct drawing of the colorbar on the specified cax.

  • Or no Axes at all, in which case a new figure and Axes are created.

If both ax and cax are given, ax is ignored !.

Parameters:
  • mappable – The matplotlib.cm.ScalarMappable (i.e., AxesImage, ContourSet, etc.) described by the colorbar.

  • ax (matplotlib.axes.Axes or cartopy.mpl.geoaxes.GeoAxesSubplot, optional) – The Axes to which the colorbar should be appended. Ignored if cax is provided. If both ax and cax are None, a new figure and Axes are created.

  • cax (matplotlib.axes.Axes, optional) – The Axes in which to directly draw the colorbar. If provided, ax is ignored.

  • **cbar_kwargs (dict) – Additional keyword arguments passed to the matplotlib.figure.colorbar. See the matplotlib.figure.colorbar documentation. Arguments ‘size’ and ‘pad’ controls the size of the colorbar. and the padding between the plot and the colorbar only if cax is not specified !.

pycolorbar.univariate.colorbar.set_colorbar_fully_transparent(p)[source][source]#

Set the colorbar of a plot fully transparent.

This is useful for animation where the colorbar should not always in all frames but the plot area must be fixed.

pycolorbar.univariate.colorbar_circular module#

Module with functions to plot circular univariate colorbars.

pycolorbar.univariate.colorbar_circular.add_circular_colorbar_legend(*, cmap, ax, box_aspect=1, height=0.2, pad=0.005, loc='upper right', inside_figure=True, optimize_layout=True, fancybox=False, fancybox_pad=0, fancybox_fc='white', fancybox_ec='none', fancybox_lw=0.5, fancybox_alpha=0.4, fancybox_shape='square', use_wedges=True, **kwargs)[source][source]#

Add the circular colorbar legend to a plot.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to which the colorbar legend will be added.

  • cmap (matplotlib.colors.Colormap) – A cyclic matplotlib colormap.

  • box_aspect (float, optional) – Aspect ratio of the inset Axes. Default is 1.

  • height (float, optional) – Height of the inset as a fraction [0-1] of the main Axes. Default is 0.2.

  • pad (float, optional) – Padding between the inset and main Axes in figure coordinates. Default is 0.005.

  • loc (str or tuple, optional) – Location of the inset. Default is ‘upper right’.

  • inside_figure (bool, optional) – Whether inset is inside the figure region. Default is True.

  • optimize_layout (bool, optional) – Whether to auto-adjust the inset position for ticklabels. Default is True. NOTE: If True, do not call fig.tight_layout() afterwards.

  • fancybox (bool, optional) – Whether to draw a fancy box behind the inset. Default is False.

  • fancybox_pad (float, optional) – Padding of the fancy box in figure coordinates. Default is 0.

  • fancybox_fc (str, optional) – Face color of the fancy box. Default is ‘white’.

  • fancybox_ec (str, optional) – Edge color of the fancy box. Default is ‘none’.

  • fancybox_lw (float, optional) – Line width of the fancy box. Default is 0.5.

  • fancybox_alpha (float, optional) – Alpha of the fancy box. Default is 0.4.

  • fancybox_shape ({'circle', 'square'}, optional) – Shape of the fancy box. Default is ‘square’.

  • discrete (float, optional) – Whether to plot a discrete or continuous circular colorbar. If True (the default) call the plot_circular_colorbar_discrete function. Otherwise call the plot_circular_colorbar function

  • **kwargs (dict) – Additional keyword arguments passed to the circular colorbar. See the plot_circular_colorbar documentation.

Returns:

The image object representing the circular colorbar.

Return type:

matplotlib.image.AxesImage

pycolorbar.univariate.colorbar_circular.plot_circular_colorbar(cmap, *, ax=None, cax=None, location='right', size='30%', pad=0.3, box_aspect=1, use_wedges=True, r_min=0.2, r_max=0.5, antialiased=False, center=(0.5, 0.5), adapt_limits=True, wedges_edgecolor='none', wedges_linewidths=None, zero_location='N', clockwise=True, add_contour=True, contour_color='black', contour_linewidth=None, add_ticks=True, ticklength=0.02, tickcolor='black', tickwidth=1, ticks=None, ticklabels=None, ticklabels_pad=None, ticklabels_size=10)[source][source]#

Plot a circular colorbar either drawing wedges or a mesh in polar projection.

You can either provide:

  • An existing Axes (ax) in which to place the colorbar (the colorbar will be appended to one of its sides).

  • A dedicated Axes object (cax) for direct drawing of the colorbar on the specified cax.

  • Or no Axes at all, in which case a new figure and Axes are created.

If both ax and cax are given, ax is ignored !.

Parameters:
  • cmap (matplotlib.colors.Colormap) – Colormap to use for the wedges.

  • ax (matplotlib.axes.Axes or cartopy.mpl.geoaxes.GeoAxesSubplot, optional) – The Axes to which the colorbar should be appended. Ignored if cax is provided. If both ax and cax are None, a new figure and Axes are created. If ax is specified and cax is None, arguments ‘pad’, ‘size’ and ‘box_aspect’ controls the appearance of the new axis.

  • cax (matplotlib.axes.Axes, optional) – The Axes in which to directly draw the colorbar. If provided, ax is ignored.

  • location (str, optional) – The side of the plot (‘right’, ‘left’, ‘top’, ‘bottom’) where the colorbar should be placed. The default location is “right”.

  • size (str, optional) – The size of the colorbar relative to the parent Axes when using append_axes. For instance, ‘30%’ means 30% of the parent Axes width (or height, depending on location). The default value is ‘30%’.

  • pad (float, optional) – Padding between the main axis and colorbar. The default value is 0.3.

  • box_aspect (float, optional) – Aspect ratio of the colorbar box. The default value is 1.

  • r_min (float, optional) – Inner and outer radius of the colorbar. If use_wedges=True, these define the annular wedge boundaries. If use_wedges=False,these define the radial range in the polar projection.

  • r_max (float, optional) – Inner and outer radius of the colorbar. If use_wedges=True, these define the annular wedge boundaries. If use_wedges=False,these define the radial range in the polar projection.

  • center (tuple, optional) – The coordinate center (x,y) around which to draw the circular colorbar. The default is (0.5, 0.5). Only used if use_wedges=True.

  • zero_location (str, optional) – Starting location of the colorbar (‘N’, ‘E’, ‘S’, ‘W’). The default zero location is “N”.

  • clockwise (bool, optional) – Direction of rotation. If True, clockwise; if False, counterclockwise. The default value is True.

  • adapt_limits (bool, optional) – If True, automatically adjusts the the limits of the plot to include the circle colorbar if center and r_min or r_max are changed. Only used if use_wedges=True. The default is True.

  • antialiased (bool, optional) – Whether to antialias the wedges. The default is False.

  • add_contour (bool, optional) – Whether to add contour circles. The default is True.

  • contour_color (str, optional) – Color of the contour circles. The default color is “black”.

  • contour_linewidth (float, optional) – Line width of the contour circles.

  • wedges_edgecolor (str, optional) – Edge color of the wedges. The default is “none”. Only used if use_wedges=True.

  • wedges_linewidths (float, optional) – Line widths of the wedges. Only used if use_wedges=True.

  • add_ticks (bool, optional) – Whether to add tick marks. The default is True. Only used if use_wedges=True.

  • ticklength (float, optional) – Length of the tick marks. The default value is 0.02. Only used if use_wedges=True.

  • tickcolor (str, optional) – Color of the tick marks. The default color is “black”. Only used if use_wedges=True.

  • tickwidth (float, optional) – Line width of the tick marks. The default value is 1. Only used if use_wedges=True.

  • ticks (array-like, optional) – Positions of the ticks in radians.

  • ticklabels (array-like, optional) – Labels for the ticks.

  • ticklabels_pad (float, optional) – Radial offset for the tick labels. The default value is 0.05.

  • ticklabels_size (int, optional) – Font size for the tick labels. The default value is 10.

Return type:

matplotlib.collection.PatchCollection or matplotlib.collection.Quadmesh

pycolorbar.univariate.colorbar_circular.plot_circular_colorbar_polar(cmap, *, ax=None, cax=None, location='right', size='30%', pad=0.3, r_min=0.8, r_max=1, antialiased=False, clockwise=True, zero_location='N', add_contour=True, contour_color='black', contour_linewidth=None, ticks=None, ticklabels=None, ticklabels_pad=4, ticklabels_size=10)[source][source]#

Plot a circular colorbar on a polar projection.

This function plots a circular colorbar representing the specified cyclic colormap using pcolormesh in a polar projection Axes. With this approach, it is not possible to add tick lines with this function !

You can either provide:

  • An existing Axes (ax) in which to place the colorbar (the colorbar will be appended to one of its sides).

  • A dedicated Axes object (cax) for direct drawing of the colorbar on the specified cax.

  • Or no Axes at all, in which case a new figure and Axes are created.

If both ax and cax are given, ax is ignored !.

Parameters:
  • cmap (matplotlib.colors.Colormap) – Colormap to use for the wedges.

  • ax (matplotlib.axes.Axes or cartopy.mpl.geoaxes.GeoAxesSubplot, optional) – The Axes to which the colorbar should be appended. Ignored if cax is provided. If both ax and cax are None, a new figure and Axes are created. If ax is specified and cax is None, arguments ‘pad’, ‘size’ and ‘box_aspect’ controls the appearance of the new axis.

  • cax (matplotlib.axes.Axes, optional) – The Axes in which to directly draw the colorbar. If provided, ax is ignored.

  • location (str, optional) – The side of the plot (‘right’, ‘left’, ‘top’, ‘bottom’) where the colorbar should be placed. The default location is “right”.

  • size (str, optional) – The size of the colorbar relative to the parent Axes when using append_axes. For instance, ‘30%’ means 30% of the parent Axes width (or height, depending on location). The default value is ‘30%’.

  • pad (float, optional) – Padding between the main axis and colorbar. The default value is 0.3.

  • r_min (float, optional) – Inner radius of the colorbar. The default value is 0.8.

  • r_max (float, optional) – Outer radius of the colorbar. The default value is 1.

  • zero_location (str, optional) – Starting location of the colorbar (‘N’, ‘E’, ‘S’, ‘W’). The default zero location is “N”.

  • clockwise (bool, optional) – Direction of rotation. If True, clockwise; if False, counterclockwise. The default value is True.

  • antialiased (bool, optional) – Whether to antialias the mesh. The default is False.

  • add_contour (bool, optional) – Whether to add contour circles. The default is True.

  • contour_color (str, optional) – Color of the contour circles. The default color “black”.

  • contour_linewidth (float, optional) – Line width of the contour circles.

  • ticks (array-like, optional) – Positions of the ticks in radians.

  • ticklabels (array-like, optional) – Labels for the ticks.

  • ticklabels_pad (float, optional) – Radial offset for the tick labels. The default value is 0.05.

  • ticklabels_size (int, optional) – Font size for the tick labels. The default value is 10.

Return type:

matplotlib.collections.QuadMesh

pycolorbar.univariate.colorbar_circular.plot_circular_colorbar_wedges(cmap, *, ax=None, cax=None, location='right', size='30%', pad=0.3, box_aspect=1, r_min=0.2, r_max=0.5, center=(0.5, 0.5), adapt_limits=True, zero_location='N', clockwise=True, antialiased=False, add_contour=True, contour_color='black', contour_linewidth=None, wedges_edgecolor='none', wedges_linewidths=None, add_ticks=True, ticks=None, ticklength=0.02, tickcolor='black', tickwidth=1, ticklabels=None, ticklabels_pad=0.05, ticklabels_size=10)[source][source]#

Plot a circular colorbar using wedges.

This function plots a circular colorbar representing the specified cyclic colormap. You can either provide:

  • An existing Axes (ax) in which to place the colorbar (the colorbar will be appended to one of its sides).

  • A dedicated Axes object (cax) for direct drawing of the colorbar on the specified cax.

  • Or no Axes at all, in which case a new figure and Axes are created.

If both ax and cax are given, ax is ignored !.

Parameters:
  • cmap (matplotlib.colors.Colormap) – Colormap to use for the wedges.

  • ax (matplotlib.axes.Axes or cartopy.mpl.geoaxes.GeoAxesSubplot, optional) – The Axes to which the colorbar should be appended. Ignored if cax is provided. If both ax and cax are None, a new figure and Axes are created. If ax is specified and cax is None, arguments ‘pad’, ‘size’ and ‘box_aspect’ controls the appearance of the new axis.

  • cax (matplotlib.axes.Axes, optional) – The Axes in which to directly draw the colorbar. If provided, ax is ignored.

  • location (str, optional) – The side of the plot (‘right’, ‘left’, ‘top’, ‘bottom’) where the colorbar should be placed. The default location is “right”.

  • size (str, optional) – The size of the colorbar relative to the parent Axes when using append_axes. For instance, ‘30%’ means 30% of the parent Axes width (or height, depending on location). The default value is ‘30%’.

  • pad (float, optional) – Padding between the main axis and colorbar. The default value is 0.3.

  • box_aspect (float, optional) – Aspect ratio of the colorbar box. The default value is 1.

  • r_min (float, optional) – Inner radius of the colorbar. The default value is 0.2.

  • r_max (float, optional) – Outer radius of the colorbar. The default value is 0.5.

  • center (tuple, optional) – The coordinate center (x,y) around which to draw the circular colorbar. The default is (0.5, 0.5)

  • zero_location (str, optional) – Starting location of the colorbar (‘N’, ‘E’, ‘S’, ‘W’). The default zero location is “N”.

  • clockwise (bool, optional) – Direction of rotation. If True, clockwise; if False, counterclockwise. The default value is True.

  • adapt_limits (bool, optional) – If True, automatically adjusts the the limits of the plot to include the circle colorbar if center and r_min or r_max are changed. The default is True.

  • antialiased (bool, optional) – Whether to antialias the wedges. The default is False.

  • add_contour (bool, optional) – Whether to add contour circles. The default is True.

  • contour_color (str, optional) – Color of the contour circles. The default color “black”.

  • contour_linewidth (float, optional) – Line width of the contour circles.

  • wedges_edgecolor (str, optional) – Edge color of the wedges. The default is “none”.

  • wedges_linewidths (float, optional) – Line widths of the wedges.

  • add_ticks (bool, optional) – Whether to add tick marks. The default is True.

  • ticklength (float, optional) – Length of the tick mark. The default value is 0.02.

  • tickcolor (str, optional) – Color of the tick mark. The default color is “black”.

  • tickwidth (float, optional) – Line width of the tick marks. The default value is 1.

  • ticks (array-like, optional) – Positions of the ticks in radians.

  • ticklabels (array-like, optional) – Labels for the ticks.

  • ticklabels_pad (float, optional) – Radial offset for the tick labels. The default value is 0.05.

  • ticklabels_size (int, optional) – Font size for the tick labels. The default value is 10.

Return type:

matplotlib.collection.PatchCollection

Module contents#

pycolorbar.univariate.adapt_cmap(cmap, *, interval=None, n=None, alpha=None, bias=1)[source][source]#

Adapt a colormap by subsetting its colors and applying transparency, if specified.

Parameters:
  • cmap (matplotlib.colors.Colormap) – The original colormap to adapt (e.g., LinearSegmentedColormap or ListedColormap).

  • interval (tuple of float, optional) – A tuple (start, end) with values between 0 and 1, indicating the fraction of the colormap to use. Defaults to using the full colormap (0, 1).

  • n (int, optional) – The number of colors to return. If None, the colormap is not resampled.

  • alpha (float, optional) – A transparency value to apply to the colors, where 0 is fully transparent and 1 is fully opaque. If alpha is None (the default), the original transparency of the colors is preserved.

  • bias (float, optional) – A factor that skews the distribution of colors in the colormap. A bias of 1 (default) results in no bias. Values less than 1 space the colors more widely at the high end of the color map. Values greater than 1 space the colors more widely at the lower end of the colormap.

Returns:

A new colormap that reflects the specified interval, n, alpha and bias values.

Return type:

matplotlib.colors.Colormap

Notes

  • The function creates a new colormap by extracting a subset of the colors from the original colormap.

  • The resulting colormap has the same name as the original, unless specified otherwise in the internal logic.

pycolorbar.univariate.add_circular_colorbar_legend(*, cmap, ax, box_aspect=1, height=0.2, pad=0.005, loc='upper right', inside_figure=True, optimize_layout=True, fancybox=False, fancybox_pad=0, fancybox_fc='white', fancybox_ec='none', fancybox_lw=0.5, fancybox_alpha=0.4, fancybox_shape='square', use_wedges=True, **kwargs)[source][source]#

Add the circular colorbar legend to a plot.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes to which the colorbar legend will be added.

  • cmap (matplotlib.colors.Colormap) – A cyclic matplotlib colormap.

  • box_aspect (float, optional) – Aspect ratio of the inset Axes. Default is 1.

  • height (float, optional) – Height of the inset as a fraction [0-1] of the main Axes. Default is 0.2.

  • pad (float, optional) – Padding between the inset and main Axes in figure coordinates. Default is 0.005.

  • loc (str or tuple, optional) – Location of the inset. Default is ‘upper right’.

  • inside_figure (bool, optional) – Whether inset is inside the figure region. Default is True.

  • optimize_layout (bool, optional) – Whether to auto-adjust the inset position for ticklabels. Default is True. NOTE: If True, do not call fig.tight_layout() afterwards.

  • fancybox (bool, optional) – Whether to draw a fancy box behind the inset. Default is False.

  • fancybox_pad (float, optional) – Padding of the fancy box in figure coordinates. Default is 0.

  • fancybox_fc (str, optional) – Face color of the fancy box. Default is ‘white’.

  • fancybox_ec (str, optional) – Edge color of the fancy box. Default is ‘none’.

  • fancybox_lw (float, optional) – Line width of the fancy box. Default is 0.5.

  • fancybox_alpha (float, optional) – Alpha of the fancy box. Default is 0.4.

  • fancybox_shape ({'circle', 'square'}, optional) – Shape of the fancy box. Default is ‘square’.

  • discrete (float, optional) – Whether to plot a discrete or continuous circular colorbar. If True (the default) call the plot_circular_colorbar_discrete function. Otherwise call the plot_circular_colorbar function

  • **kwargs (dict) – Additional keyword arguments passed to the circular colorbar. See the plot_circular_colorbar documentation.

Returns:

The image object representing the circular colorbar.

Return type:

matplotlib.image.AxesImage

pycolorbar.univariate.combine_cmaps(cmaps: list[Colormap | str], *, nodes: list[float] | ndarray | None = None, n=None, output_n: int = 256, name: str = 'combined_cmap') LinearSegmentedColormap[source][source]#

Create a composite matplotlib colormap by combining multiple colormaps.

Parameters:
  • cmaps (list) – List of matplotlib.Colormap or registered colormap names to be combined.

  • nodes (list of float or np.ndarray, optional) – Blending points between colormaps, in the range [0, 1]. Nodes values should be one less than the number of colormaps. Defaults to equal divisions if None.

  • n (list of int or None, optional) – Number of colors for each colormap. Defaults to None, which uses the original number of colors for each colormap.

  • output_n (int, optional) – Number of colors in the output colormap. Default is 256.

  • name (str, optional) – Name for the combined colormap. Default is “combined_cmap”.

Returns:

The composite colormap created from the specified colormaps.

Return type:

LinearSegmentedColormap

Raises:
  • TypeError – If the list contains mixed datatypes or invalid colormap names.

  • ValueError – If the cmaps contain only one single colormap, or if the number of nodes is not one less than the number of colormaps, or if the nodes do not contain incrementing values between 0.0 and 1.0.

Notes

The colormaps are combined from low value to high value end. Code adapted from CMasher (1313e/CMasher).

Examples

Using predefined colormap names:

custom_cmap_1 = combine_cmaps(

[“ocean”, “prism”, “coolwarm”], nodes=[0.2, 0.75]

)

Using Colormap objects:

cmap_0 = plt.get_cmap(“Blues”) cmap_1 = plt.get_cmap(“Oranges”) cmap_2 = plt.get_cmap(“Greens”) custom_cmap_2 = combine_cmaps([cmap_0, cmap_1, cmap_2])

pycolorbar.univariate.get_cmap_colors(cmap, *, interval=None, n=None, alpha=None, bias=1)[source][source]#

Retrieve a list of RGB colors from a colormap, optionally subsetting by an interval and number of colors (n).

Parameters:
  • cmap (matplotlib.colors.Colormap) – A colormap instance (e.g., LinearSegmentedColormap or ListedColormap).

  • interval (tuple of float, optional) – A tuple (start, end) with values between 0 and 1, representing the fraction of the colormap to retain. Defaults to the full colormap (0, 1).

  • n (int, optional) – Number of colors to return. If None, the number of colors depends on the colormap (default: None).

  • alpha (float, optional) – A transparency value to apply to the colors, where 0 is fully transparent and 1 is fully opaque. If alpha is None (the default), the original transparency of the colors is preserved. If provided, all colors will be updated to have the specified alpha value.

  • bias (float, optional) – A factor that skews the distribution of colors in the colormap. A bias of 1 (default) results in no bias. Values less than 1 space the colors more widely at the high end of the color map. Values greater than 1 space the colors more widely at the lower end of the colormap.

Returns:

A NumPy array of RGB colors extracted from the colormap.

Return type:

np.ndarray

Notes

  • If the colormap is a LinearSegmentedColormap and does not have an N attribute, 256 colors are returned.

  • If interval is provided, only the specified range of the colormap will be returned.

pycolorbar.univariate.get_cmap_lab(cmap)[source][source]#

Convert a colormap’s RGB values into the CAM02-UCS color space.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

A NumPy array of LAB values corresponding to the colormap’s colors in the CAM02-UCS color space. The LAB values represent Lightness (L) and color components (A, B) in a perceptually uniform space.

Return type:

np.ndarray

Raises:

ImportError – If the colorspacious package is not installed.

Notes

This function converts the RGB values of the input colormap into the CAM02-UCS color space, which is designed to provide perceptually uniform color information, meaning that equal distances in this color space correspond to equal perceptual differences. The conversion is done using the colorspacious package.

The LAB values consist of: - L: Lightness - A and B: Unique color components

Examples

>>> import matplotlib.pyplot as plt
>>> from matplotlib import cm
>>> cmap = cm.viridis
>>> lab = get_cmap_lab(cmap)
>>> print(lab)
pycolorbar.univariate.get_cmap_lightness(cmap)[source][source]#

Extract the lightness component of a colormap using the CAM02-UCS color space.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

lightness – A 1D array of lightness values corresponding to the colors in the colormap. These values are derived from the CAM02-UCS color space’s lightness (L) component.

Return type:

ndarray

Raises:

ImportError – If the colorspacious package is not installed, an error is raised.

Notes

The function converts the RGB values of the input colormap into the CAM02-UCS color space, which provides perceptually uniform color information. The lightness component (L) is then extracted and returned as a 1D array.

Examples

>>> import matplotlib.pyplot as plt
>>> from matplotlib import cm
>>> cmap = cm.viridis
>>> lightness = get_cmap_lightness(cmap)
>>> print(lightness)
pycolorbar.univariate.get_cmap_segmentdata(cmap, n=None)[source][source]#

Retrieve the segment data of a colormap, or generate it if not present.

Parameters:
  • cmap (matplotlib.colors.Colormap) – A colormap instance (e.g., LinearSegmentedColormap or ListedColormap).

  • n (int, optional) – The number of discrete points to sample from the colormap. If None, the colormap’s N attribute is used.

Returns:

A dictionary representing the colormap’s segment data for red, green, and blue channels. Each entry in the dictionary corresponds to a list of (x, y0, y1) tuples, where: - x is the position (0 to 1) along the colormap. - y0 is the color value to the left of x. - y1 is the color value to the right of x.

Return type:

dict

Notes

  • The segment data is used to create LinearSegmentedColormap objects.

  • If the colormap has a _segmentdata attribute, it is returned directly.

  • If the colormap is sampled using n points, this function constructs the segment data manually.

pycolorbar.univariate.get_cvd_cmap(cmap, *, cvd_type, severity=50)[source][source]#

Return a Matplotlib colormap emulating a specified color-vision deficiency (CVD).

This function simulates how the colormap would appear to someone with a particular type of color-vision deficiency using the colorspacious package.

Parameters:
  • cmap (matplotlib.colors.Colormap) – The input colormap to be converted. It can be an instance of either ListedColormap or LinearSegmentedColormap.

  • cvd_type (str) – The type of color-vision deficiency to simulate. Valid options are: ‘deuteranomaly’, ‘protanomaly’, and ‘tritanomaly’.

  • severity (int, optional) – The severity of the color-vision deficiency on a scale from 0 (no deficiency) to 100 (complete deficiency), by default 50. For people suffering of tritanomaly, only severity = 100 actually exists in reality.

Returns:

A new colormap that simulates the appearance of the input colormap for individuals with the specified color-vision deficiency.

Return type:

matplotlib.colors.Colormap

Examples

>>> import matplotlib.pyplot as plt
>>> from matplotlib.colors import get_cmap
>>> cmap = get_cmap("viridis")
>>> cvd_cmap = get_cvd_cmap(cmap, cvd_type="deuteranomaly", severity=50)
>>> plt.imshow([list(range(256))], cmap=cvd_cmap)
>>> plt.show()

Notes

This function relies on the colorspacious package to perform color conversions. Make sure to install it using conda install -c conda-forge colorspacious if not already available.

pycolorbar.univariate.get_discrete_cyclic_cmap(cmap, n)[source][source]#

Create a discrete cyclic color palette.

pycolorbar.univariate.get_gray_cmap(cmap)[source][source]#

Convert a given colormap to its grayscale equivalent.

Grayscale conversion is based on the lightness component of CAM02-UCS color space.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

cmap_gray – The grayscale version of the input colormap, where the RGB values are set based on the lightness of the corresponding color in the CAM02-UCS color space. If the original colormap includes transparency (alpha), it is preserved.

Return type:

matplotlib.colors.Colormap

Raises:

ImportError – If the colorspacious package is not installed, an error is raised.

Notes

This function uses the CAM02-UCS color space to convert the colors of the input colormap to grayscale based on their perceived lightness. The grayscale colors are created by setting the R, G, and B channels to the normalized lightness values. If the original colormap contains an alpha channel, it is maintained in the resulting grayscale colormap.

Examples

>>> import matplotlib.pyplot as plt
>>> from matplotlib import cm
>>> cmap = cm.viridis
>>> cmap_gray = get_gray_cmap(cmap)
>>> plt.imshow([[0, 1]], cmap=cmap_gray)
>>> plt.show()
pycolorbar.univariate.get_shifted_cmap(cmap)[source][source]#

Shift the colors of a cyclic colormap, centering the midpoint of the color range.

This function is useful for cyclic colormaps, such as those representing angles or phases, where the start and end colors should seamlessly wrap around. The function shifts the colormap so that the midpoint of the color range becomes the new start.

Parameters:

cmap (matplotlib.colors.Colormap) – The original cyclic colormap to shift.

Returns:

A new colormap with its colors shifted so that the midpoint of the original colormap becomes the new starting point.

Return type:

matplotlib.colors.Colormap

Notes

  • This function is particularly useful for cyclic colormaps where symmetry or phase is important.

  • It works by dividing the colormap at its midpoint and swapping the two halves.

pycolorbar.univariate.infer_cmap_type(cmap)[source][source]#

Infer the type of a colormap based on its lightness values and color differences.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

A string indicating the type of colormap: - ‘misc’ if the colormap does not fit other categories. - ‘sequential’ if lightness values always increase or decrease. - ‘diverging’ if the colormap has a central extreme with sequential sides. - ‘cyclic’ if the perceptual differences between colors indicate a repeating pattern. - ‘isoluminant’ if all lightness values are the same.

Return type:

str

Notes

This function analyzes the lightness and color differences of the colormap to classify it into one of several categories: sequential, diverging, cyclic, or miscellaneous. It is adapted from the cmasher library’s get_cmap_type function.

pycolorbar.univariate.is_cyclic_cmap(cmap)[source][source]#

Check if the colormap is of type ‘cyclic’.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

True if the colormap is cyclic, False otherwise.

Return type:

bool

pycolorbar.univariate.is_diverging_cmap(cmap)[source][source]#

Check if the colormap is of type ‘diverging’.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

True if the colormap is diverging, False otherwise.

Return type:

bool

pycolorbar.univariate.is_isoluminant_cmap(cmap)[source][source]#

Check if the colormap is of type ‘isoluminant’.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

True if the colormap is isoluminant, False otherwise.

Return type:

bool

pycolorbar.univariate.is_sequential_cmap(cmap)[source][source]#

Check if the colormap is of type ‘sequential’.

Parameters:

cmap (matplotlib.colors.Colormap) – The input colormap, which can be a ListedColormap or a LinearSegmentedColormap.

Returns:

True if the colormap is sequential, False otherwise.

Return type:

bool

pycolorbar.univariate.plot_circular_colorbar(cmap, *, ax=None, cax=None, location='right', size='30%', pad=0.3, box_aspect=1, use_wedges=True, r_min=0.2, r_max=0.5, antialiased=False, center=(0.5, 0.5), adapt_limits=True, wedges_edgecolor='none', wedges_linewidths=None, zero_location='N', clockwise=True, add_contour=True, contour_color='black', contour_linewidth=None, add_ticks=True, ticklength=0.02, tickcolor='black', tickwidth=1, ticks=None, ticklabels=None, ticklabels_pad=None, ticklabels_size=10)[source][source]#

Plot a circular colorbar either drawing wedges or a mesh in polar projection.

You can either provide:

  • An existing Axes (ax) in which to place the colorbar (the colorbar will be appended to one of its sides).

  • A dedicated Axes object (cax) for direct drawing of the colorbar on the specified cax.

  • Or no Axes at all, in which case a new figure and Axes are created.

If both ax and cax are given, ax is ignored !.

Parameters:
  • cmap (matplotlib.colors.Colormap) – Colormap to use for the wedges.

  • ax (matplotlib.axes.Axes or cartopy.mpl.geoaxes.GeoAxesSubplot, optional) – The Axes to which the colorbar should be appended. Ignored if cax is provided. If both ax and cax are None, a new figure and Axes are created. If ax is specified and cax is None, arguments ‘pad’, ‘size’ and ‘box_aspect’ controls the appearance of the new axis.

  • cax (matplotlib.axes.Axes, optional) – The Axes in which to directly draw the colorbar. If provided, ax is ignored.

  • location (str, optional) – The side of the plot (‘right’, ‘left’, ‘top’, ‘bottom’) where the colorbar should be placed. The default location is “right”.

  • size (str, optional) – The size of the colorbar relative to the parent Axes when using append_axes. For instance, ‘30%’ means 30% of the parent Axes width (or height, depending on location). The default value is ‘30%’.

  • pad (float, optional) – Padding between the main axis and colorbar. The default value is 0.3.

  • box_aspect (float, optional) – Aspect ratio of the colorbar box. The default value is 1.

  • r_min (float, optional) – Inner and outer radius of the colorbar. If use_wedges=True, these define the annular wedge boundaries. If use_wedges=False,these define the radial range in the polar projection.

  • r_max (float, optional) – Inner and outer radius of the colorbar. If use_wedges=True, these define the annular wedge boundaries. If use_wedges=False,these define the radial range in the polar projection.

  • center (tuple, optional) – The coordinate center (x,y) around which to draw the circular colorbar. The default is (0.5, 0.5). Only used if use_wedges=True.

  • zero_location (str, optional) – Starting location of the colorbar (‘N’, ‘E’, ‘S’, ‘W’). The default zero location is “N”.

  • clockwise (bool, optional) – Direction of rotation. If True, clockwise; if False, counterclockwise. The default value is True.

  • adapt_limits (bool, optional) – If True, automatically adjusts the the limits of the plot to include the circle colorbar if center and r_min or r_max are changed. Only used if use_wedges=True. The default is True.

  • antialiased (bool, optional) – Whether to antialias the wedges. The default is False.

  • add_contour (bool, optional) – Whether to add contour circles. The default is True.

  • contour_color (str, optional) – Color of the contour circles. The default color is “black”.

  • contour_linewidth (float, optional) – Line width of the contour circles.

  • wedges_edgecolor (str, optional) – Edge color of the wedges. The default is “none”. Only used if use_wedges=True.

  • wedges_linewidths (float, optional) – Line widths of the wedges. Only used if use_wedges=True.

  • add_ticks (bool, optional) – Whether to add tick marks. The default is True. Only used if use_wedges=True.

  • ticklength (float, optional) – Length of the tick marks. The default value is 0.02. Only used if use_wedges=True.

  • tickcolor (str, optional) – Color of the tick marks. The default color is “black”. Only used if use_wedges=True.

  • tickwidth (float, optional) – Line width of the tick marks. The default value is 1. Only used if use_wedges=True.

  • ticks (array-like, optional) – Positions of the ticks in radians.

  • ticklabels (array-like, optional) – Labels for the ticks.

  • ticklabels_pad (float, optional) – Radial offset for the tick labels. The default value is 0.05.

  • ticklabels_size (int, optional) – Font size for the tick labels. The default value is 10.

Return type:

matplotlib.collection.PatchCollection or matplotlib.collection.Quadmesh

pycolorbar.univariate.plot_circular_colormap(cmap, r_min=0.2, r_max=1, ax=None, add_title=True, antialiased=False, clockwise=True, zero_location='N', add_contour=True, contour_color='black', contour_linewidth=None, n_cycles=0, amplitude=0.6283185307179586, power=4)[source][source]#

Plot a circular colormap with an optional sinusoidal pattern.

Parameters:
  • cmap (matplotlib.colors.Colormap) – The colormap to be used for the plot.

  • r_min (float, optional) – The minimum radius for the colormap circle. The default value is 0.2.

  • r_max (float, optional) – The maximum radius for the colormap circle. The default value is 1.

  • ax (matplotlib.axes._subplots.PolarAxesSubplot, optional) – The polar axis on which to plot. If None, a new figure and axis are created. The default is None.

  • antialiased (bool, optional) – Whether to apply antialiasing to the pcolormesh plot. Default is False.

  • add_title (bool, optional) – Whether to add the colormap name as a title. Default is True.

  • clockwise (bool, optional) – If True, the angles increase in the clockwise direction. Default is True.

  • zero_location (str, optional) – The location of the zero angle. For example, “N” for North. Default is “N”.

  • add_contour (bool, optional) – Whether to add contour lines at the inner and outer boundaries. The default is True..

  • contour_color (str or color, optional) – The color of the contour lines. Default is “black”.

  • contour_linewidth (float, optional) – The linewidth of the contour lines. If None, the default linewidth is used.

  • n_cycles (int, optional) – The number of sine wave cycles in the radial direction. Set to 0 to omit the spiral pattern. The default is 0.

  • amplitude (float, optional) – Amplitude of the sine wave component in the spiral pattern. The default value is np.pi/5.

  • power (int, optional) – Power of the radial distance in the spiral pattern. The default value is 4.

Returns:

The QuadMesh object representing the plotted circular colormap.

Return type:

matplotlib.collections.QuadMesh

References

Kovesi, P., 2015. “Good Colour Maps: How to Design Them.” arXiv preprint arXiv:1509.03700.

pycolorbar.univariate.plot_circular_colormaps(cmaps, cols=None, subplot_size=None, dpi=200, n_cycles=0, amplitude=0.6283185307179586, power=4, **plot_kwargs)[source][source]#

Plot a list of colormaps.

pycolorbar.univariate.plot_colormap(cmap, dpi=200, ax=None, **plot_kwargs)[source][source]#

Plot a single colormap.

pycolorbar.univariate.plot_colormaps(cmaps, cols=None, subplot_size=None, dpi=200, **plot_kwargs)[source][source]#

Plot a list of colormaps.