pycolorbar.bivariate package#

Submodules#

pycolorbar.bivariate.cmap module#

Module defining BivariateColormap functionalities.

class pycolorbar.bivariate.cmap.BivariateColormap(rgba_array, *, luminance_factor=None, n=None, interp_method=None)[source][source]#

Bases: object

Class representing a bivariate colormap.

Initialize the bivariate colormap with an RGBA array of shape (n_y, n_x, 4).

Parameters:
  • rgba_array (numpy.ndarray) – 2D RGBA array (n_y, n_x, 4) providing colors from top to bottom. The (x, 0) values are mapped to the corresponding color in the bottom row of the 2D RGBA array. The (x, 1) values are mapped to the corresponding color in the top row of the 2D RGBA array.

  • n (int or tuple, optional) – Either a single integer or a (n_y, n_x) tuple specifying the number of colormap colors.

  • luminance_factor (float or None, optional) – If set, apply radial-based luminance gradient. Radial darkening is obtained with values < 1. Radial whitening is obtained with values > 1. None or 1 produce no change.

  • interp_method (str, optional) – The interpolation method to use for generating the colormap. The default is ‘cubic’.

adapt_interval(interval_x=None, interval_y=None)[source][source]#

Subset the bivariate colormap based on the specified interval fractions.

Parameters:
  • interval_x (tuple) – A tuple of two float values between 0 and 1, indicating the fraction of the colors to retain on the x axis. If None, no subsetting is performed.

  • interval_y (tuple) – A tuple of two float values between 0 and 1, indicating the fraction of the colors to retain on the y axis. If None, no subsetting is performed.

Return type:

pycolorbar.BiviariateColormap

add_legend(ax, **kwargs)[source][source]#

Add the bivariate colorbar legend to a plot.

Parameters:
  • bivariate_cmap (pycolorbar.BivariateColormap) – The bivariate colormap to be used for the legend.

  • 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 bivariate colorbar. See the add_bivariate_colorbar documentation.

Returns:

The image object representing the bivariate colorbar.

Return type:

matplotlib.image.AxesImage

change_luminance_gradient(luminance_factor=None)[source][source]#

Change the luminance gradient of the colormap.

It add a radial whitening/darkening effect.

Parameters:

luminance_factor (float or None) – Radial darkening is obtained with values < 1. Radial whitening is obtained with values > 1. None or 1 produce no change.

Returns:

The colormap with the new luminance gradient.

Return type:

pycolorbar.BiviariateColormap

copy()[source][source]#

Create a copy of the BivariateColormap instance.

fliplr()[source][source]#

Flip the colormap array in the left/right direction.

This method flips the RGBA array of the colormap horizontally, creating a mirror image along the vertical axis.

flipud()[source][source]#

Flip the colormap array in the up/down direction.

This method flips the RGBA array of the colormap in the vertical direction, effectively reversing the order of the rows.

classmethod from_cmaps(cmap_x=<matplotlib.colors.LinearSegmentedColormap object>, cmap_y=<matplotlib.colors.LinearSegmentedColormap object>, n=256, *, luminance_factor=None)[source][source]#

Generate a bivariate colormap by blending two univariate colormaps along x and y axes.

Parameters:
  • cmap_x (matplotlib.colors.Colormap or str) – Univariate colormap for the x axis.

  • cmap_y (matplotlib.colors.Colormap or str) – Univariate colormap for the y axis.

  • n (int or tuple, optional) – Either a single integer or a (n_x, n_y) tuple specifying the number of colormap colors on the x and y axis. Default is 256.

  • luminance_factor (float or None, optional) – If set, apply radial-based luminance gradient. Radial darkening is obtained with values < 1. Radial whitening is obtained with values > 1. None or 1 produce no change.

Return type:

pycolorbar.BiviariateColormap

classmethod from_colors(colors, n, *, luminance_factor=None, interp_method=None)[source][source]#

Generate a bivariate colormap from a set of color points interpolated onto an 2D (n_y, n_x) grid.

Parameters:
  • color_list (list of color specs) – E.g. [‘red’, ‘blue’, ‘green’, ‘black’] or precomputed array of RGBA.

  • n (int or tuple) – Either a single integer or a (n_y, n_x) tuple specifying the number of colormap colors.

  • luminance_factor (float or None, optional) – If set, apply radial-based luminance gradient. Radial darkening is obtained with values < 1. Radial whitening is obtained with values > 1. None or 1 produce no change.

  • interp_method (str, optional) – The interpolation method to use for generating the colormap. The default is ‘cubic’.

Return type:

pycolorbar.BiviariateColormap

classmethod from_corners(colors, n, *, luminance_factor=None, interp_method=None)[source][source]#

Generate a bivariate colormap from the colors at four corners.

Parameters:
  • color_list (list of color specs) – E.g. [‘red’, ‘blue’, ‘green’, ‘black’] or precomputed array of RGBA.

  • n (int or tuple) – Either a single integer or a (n_y, n_x) tuple specifying the number of colormap colors.

  • luminance_factor (float or None, optional) – If set, apply radial-based luminance gradient. Radial darkening is obtained with values < 1. Radial whitening is obtained with values > 1. None or 1 produce no change.

  • interp_method (str, optional) – The interpolation method to use for generating the colormap. The default is ‘cubic’.

Return type:

pycolorbar.BiviariateColormap

classmethod from_name(name, n, *, diagonal_tilt=0.8, offdiag_tilt=1.0, luminance_factor=None, interp_method=None)[source][source]#

Load a predefined bivariate colormap.

Parameters:
  • name (str) – The name of the predefined bivariate colormap to load. See available_biviariate_colormaps().

  • n (int) – The number of colors in the colormap.

  • diagonal_tilt (float, optional) – The tilt of the diagonal in the colormap, by default 0.8. Used only for Teuling colormaps.

  • offdiag_tilt (float, optional) – The tilt of the off-diagonal in the colormap, by default 1. Used only for Teuling colormaps.

  • interp_method (str or None, optional) – The interpolation method to use, by default None.

  • luminance_factor (float or None, optional) – If set, apply radial-based luminance gradient. Radial darkening is obtained with values < 1. Radial whitening is obtained with values > 1. None or 1 produce no change.

Return type:

pycolorbar.BiviariateColormap

map(x, y, *, norm_x=None, norm_y=None)[source]#

Map (x, y) data to RGBA colors based on this bivariate colormap.

Parameters:
  • x (array-like, pd.Series, or xarray.DataArray) – Data arrays to be mapped. Must be of the same type and shape.

  • y (array-like, pd.Series, or xarray.DataArray) – Data arrays to be mapped. Must be of the same type and shape.

  • norm_x (None or mpl.colors.Normalize or BoundaryNorm) – Normalization for the x dimension. If None, default 0-1 scaling is used or computed from data.

  • norm_y (None or mpl.colors.Normalize or BoundaryNorm) – Normalization for the y dimension. If None, default 0-1 scaling is used or computed from data.

Returns:

  • A numpy.ndarray with shape = x.shape + (4,) if x is a numpy array or pd.Series

  • An xarray.DataArray with shape = x.shape + (“rgba”,) if x is an xarray.DataArray

Return type:

Mapped result

plot(ax=None, disable_axis=True, **kwargs)[source][source]#

Plot the bivariate colormap.

Parameters:
  • rgba_array (numpy.ndarray) – A 2D array of RGBA values representing the bivariate colormap.

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

  • xlim (list or tuple, optional) – The x-axis limits for the plot. If None, defaults to [0, n_x - 1].

  • ylim (list or tuple, optional) – The y-axis limits for the plot. If None, defaults to [0, n_y - 1].

  • disable_axis (bool, optional) – If True, the axis will be turned off. Default is False.

  • origin ({'upper', 'lower'}, optional) – The origin of the colormap. Default is ‘upper’.

  • aspect (str or float) – Either ‘equal’ or ‘auto’ or float. Controls the axes scaling (y/x-scale). If ‘auto’ fill the Axes position rectangle with data. If ‘equal’, ensure same scaling between x and y axis. The default is ‘auto’.

  • **imshow_kwargs (dict, optional) – Additional keyword arguments to pass to imshow.

Returns:

The image object created by imshow representing the bivariate colormap.

Return type:

matplotlib.image.AxesImage

Notes

If no axes are provided, a new figure and axes are created. The x and y limits can be specified, and the axis can be disabled if desired. The origin parameter determines the placement of the origin axis.

plot_colorbar(ax=None, cax=None, **kwargs)[source][source]#

Plot a bivariate colorbar.

This function plots a 2D colorbar representing the specified bivariate 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:
  • bivariate_cmap (pycolorbar.BivariateColormap) – The colormap to be used for the bivariate 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.

  • origin ({'lower', 'upper'}, optional) – Indicates where to locate the origin in the colorbar Axes. Default is ‘lower’.

  • location ({'right', 'left', 'top', 'bottom'}, optional) – The side of the plot where the colorbar should be placed (when ax is used). Default is ‘right’.

  • size (float or 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). Default is ‘30%’.

  • pad (float, optional) – The padding between the parent Axes and the colorbar, in inches. Default is 0.45.

  • box_aspect (float, optional) – The aspect ratio of the colorbar Axes box. Default is 1.

  • **kwargs (dict) – Additional keyword arguments passed to the internal add_bivariate_colorbar function, which is responsible for actually rendering the colorbar content.

Returns:

The image object representing the bivariate colorbar.

Return type:

matplotlib.image.AxesImage

resampled(*, n_x=None, n_y=None, interp_method='linear')[source][source]#

Create a new BivariateColormap instance with the desired number of colors.

Parameters:
  • n_x (int, optional) – The desired number of colormap colors along the x axis. If None, the original number of colors is kept.

  • n_y (int, optional) – The desired number of colormap colors along the y axis. If None, the original number of colors is kept.

  • interp_method (str) – Interpolation method (e.g. “nearest”, “linear”, “cubic”). The default method is “nearest”.

Returns:

A new BivariateCmap instance resampled to have an rgba_array of shape (n_y, n_x).

Return type:

BivariateCmap

rot180(*, clockwise=True)[source][source]#

Rotate the colormap by 180 degrees.

Parameters:

clockwise (bool, optional) – If True, rotate clockwise. If False, rotate counterclockwise. Default is True.

Returns:

The colormap rotated by 180 degrees.

Return type:

pycolorbar.BiviariateColormap

rot90(*, clockwise=True)[source][source]#

Rotate the colormap by 90 degrees.

Parameters:

clockwise (bool, optional) – If True, rotate clockwise. If False, rotate counterclockwise. Default is True.

Returns:

The colormap rotated by 90 degrees.

Return type:

pycolorbar.BiviariateColormap

set_alpha(alpha)[source][source]#

Set the alpha (transparency) value for the entire colormap.

Parameters:

alpha (float) – The alpha value to set, where 0 is fully transparent and 1 is fully opaque.

set_bad(color, alpha=None)[source][source]#

Set the color for bad (masked) values.

Parameters:

color (color spec) – The color to use for bad values.

class pycolorbar.bivariate.cmap.BivariateTransparencyColormap(cmap, alpha_min=0.2, alpha_max=1, n=None)[source][source]#

Bases: BivariateColormap

Class representing a bivariate transparency colormap.

Initialize the bivariate colormap with transparency.

Parameters:
  • cmap (matplotlib.colors.Colormap or str) – The colormap to be used.

  • alpha_min (float, optional) – The minimum alpha (transparency) value, by default 0.2.

  • alpha_max (float, optional) – The maximum alpha (transparency) value, by default 1.

  • n (int or tuple of int, optional) – The number of discrete colors in the colormap. If an integer is provided, it is used for both dimensions. If a tuple is provided, it should be of the form (n_x, n_y), where n_x is the number of colors in the x dimension and n_y is the number of colors in the y dimension. If None, a default value is used.

Notes

The y dimension corresponds to the transparency levels.

pycolorbar.bivariate.cmap.add_bivariate_colorbar(*, bivariate_cmap, cax, origin='lower', aspect='auto', xlabel=None, ylabel=None, title=None, title_kwargs=None, xlabel_kwargs=None, ylabel_kwargs=None, xticks_kwargs=None, yticks_kwargs=None, **imshow_kwargs)[source][source]#

Add a bivariate colorbar to the specified axis.

Parameters:
  • bivariate_cmap (pycolorbar.BivariateColormap) – The bivariate colormap object containing the color mapping and norms.

  • cax (matplotlib.axes.Axes) – The axis on which to draw the colorbar.

  • origin ({'lower', 'upper'}, optional) – The origin of the colorbar. Default is ‘lower’.

  • aspect (str, optional) – Either ‘equal’ or ‘auto’. If ‘auto’ fill the Axes position rectangle with data. If ‘equal’, ensure same scaling between x and y axis. The default is ‘auto’.

  • xlabel (str, optional) – The label for the x-axis. Default is None.

  • ylabel (str, optional) – The label for the y-axis. Default is None.

  • title (str, optional) – The title for the colorbar. Default is None.

  • title_kwargs (dict, optional) – Additional keyword arguments for the title. Default is None.

  • xlabel_kwargs (dict, optional) – Additional keyword arguments for the x-axis label. Default is None.

  • ylabel_kwargs (dict, optional) – Additional keyword arguments for the y-axis label. Default is None.

  • xticks_kwargs (dict, optional) – Additional keyword arguments for the x-axis ticks. Default is None.

  • yticks_kwargs (dict, optional) – Additional keyword arguments for the y-axis ticks. Default is None.

  • **imshow_kwargs (dict, optional) – Additional keyword arguments for the imshow function.

Returns:

The image object representing the bivariate colorbar.

Return type:

matplotlib.image.AxesImage

Raises:

ValueError – If the norms for the bivariate colormap are not defined. It occurs when the bivariate colormaps has not yet been used to map some values to RGBA colors.

pycolorbar.bivariate.cmap.add_bivariate_legend(*, bivariate_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', **kwargs)[source][source]#

Add the bivariate colorbar legend to a plot.

Parameters:
  • bivariate_cmap (pycolorbar.BivariateColormap) – The bivariate colormap to be used for the legend.

  • 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 bivariate colorbar. See the add_bivariate_colorbar documentation.

Returns:

The image object representing the bivariate colorbar.

Return type:

matplotlib.image.AxesImage

pycolorbar.bivariate.cmap.apply_luminance_gradient(image_rgb, luminance_factor=None)[source][source]#

Apply a bivariate luminance gradient to an RGB image.

It add a radial whitening/darkening effect.

Parameters:
  • image_rgb (numpy.ndarray) – An (N, N, 4) or (N, N, 3) array of RGBA or RGB values.

  • luminance_factor (float or None) – Radial darkening is obtained with values < 1. Radial whitening is obtained with values > 1. None or 1 produce no change.

Returns:

The luminance-adjusted image array, same shape as image_rgb.

Return type:

numpy.ndarray

pycolorbar.bivariate.cmap.available_bivariate_colormaps()[source][source]#

Get the list of the predefined available bivariate colormaps.

pycolorbar.bivariate.cmap.check_cmap_ncolors(norm, n, dim_name)[source][source]#

Check for the number of colors for categorical norms.

pycolorbar.bivariate.cmap.check_expected_number_categories(n, n_categories, dim_name, obj='norm')[source][source]#

Check that number of color matches the number of categories.

pycolorbar.bivariate.cmap.check_n(n, both_integers=True)[source][source]#

Check n value validity.

pycolorbar.bivariate.cmap.check_name(name)[source][source]#

Check name validity.

pycolorbar.bivariate.cmap.create_pandas_category_norm(series)[source][source]#

Create a CategoryNorm object for a pandas Categorical series.

Parameters:

series (pandas.Series or geopandas.GeoSeries) – A pandas or geopandas Series with categorical data.

Returns:

A CategoryNorm object that maps category integer indices to category names.

Return type:

pycolorbar.norm.CategoryNorm

Notes

This function assumes that the input series is of categorical dtype. It creates a dictionary mapping category integer indices to category names and uses this dictionary to initialize a CategoryNorm object.

pycolorbar.bivariate.cmap.define_norm(arr)[source][source]#

Define a matplotlib.Normalize object based on array’s values.

Parameters:

arr (array-like) – Input array to be normalized.

Returns:

A Normalize object with the minimum and maximum values of the array, or None if the array contains non-numeric data.

Return type:

Normalize or None

Raises:

ValueError – If the array has all identical values or contains only NaNs.

Notes

If the array contains non-numeric data, it returns None.

pycolorbar.bivariate.cmap.ensure_rgba_array(rgba_array)[source][source]#

Ensure a RGBA array is returned.

pycolorbar.bivariate.cmap.get_axis_defaults(norm)[source][source]#

Extract axis configuration from a matplotlib normalization object.

Generates appropriate axis limits, tick positions, and tick labels based on the type of normalization applied to the data.

Parameters:

norm (matplotlib.colors.Normalize) – A matplotlib normalization object. Supported types include: - CategoryNorm, CategorizeNorm: categorical data - BoundaryNorm: discrete binned data - LogNorm: logarithmic scaling - SymLogNorm: symmetric logarithmic scaling - Normalize, CenterNorm, and other standard norms: linear scaling

Returns:

A tuple of (value_lims, ticks, ticklabels) where: - value_lims : tuple of (float, float)

The (min, max) range for the axis

  • ticksnumpy.ndarray or None

    Tick positions in data coordinates

  • ticklabelslist or None

    Formatted tick labels, or None for automatic formatting

Return type:

tuple

Raises:

NotImplementedError – If the norm type is not supported.

pycolorbar.bivariate.cmap.get_bivariate_cmap_from_colors(colors, n=5, interp_method=None)[source][source]#

Create a bivariate colormap from a set of color points.

This function takes a set of RGBA (or named) colors arranged in a clockwise layout (plus an optional center color if 5 or 9 points), and interpolates them over an (n_y, n_x) grid in sRGB colorspace.

Parameters:
  • colors (list or tuple) – A list or array of color specifications recognized by Matplotlib (e.g., [‘red’, ‘blue’, ‘green’, ‘black’]) or an array of shape (N, 4) in RGBA format. The length of colors must be one of {4, 5, 8, 9}. See the Notes below.

  • n (int or tuple) – Either a single integer or a (n_x, n_y) tuple specifying the number of colormap colors on the x and y axis.

  • interp_method (str, optional) – The interpolation method to use for generating the colormap. The default is ‘cubic’.

Notes

  • The color points are assumed to be laid out clockwise, with optional center colors for 5 or 9 entries. Specifically:

  • For 4 colors: [top_left, top_right, bottom_right, bottom_left].

  • For 5 or 9 colors: the extra point(s) become center row (or center cell).

  • For 8 colors: midpoints along each side plus corners.

Returns:

Shape (n_y, n_x, 4) array of interpolated RGBA.

Return type:

numpy.ndarray

pycolorbar.bivariate.cmap.get_bivariate_cmap_from_name(name, n, diagonal_tilt=0.8, offdiag_tilt=1, interp_method=None)[source][source]#

Retrieve a bivariate colormap based on the specified name and parameters.

Parameters:
  • name (str) – The name of the bivariate colormap to retrieve. See available_biviariate_colormaps().

  • n (int) – The number of colors in the colormap.

  • diagonal_tilt (float, optional) – The tilt of the diagonal in the colormap, by default 0.8. Used only for Teuling colormaps.

  • offdiag_tilt (float, optional) – The tilt of the off-diagonal in the colormap, by default 1. Used only for Teuling colormaps.

  • interp_method (str or None, optional) – The interpolation method to use, by default None.

Returns:

rgba_array – An array of RGBA values representing the colormap.

Return type:

numpy.ndarray

pycolorbar.bivariate.cmap.get_bivariate_cmap_from_two_cmaps(cmap_x=<matplotlib.colors.LinearSegmentedColormap object>, cmap_y=<matplotlib.colors.LinearSegmentedColormap object>, n=256)[source][source]#

Construct a bivariate colormap by blending two univariate colormaps along x and y axes.

Parameters:
  • cmap_x (matplotlib.colors.Colormap or str) – Univariate colormap for the x axis.

  • cmap_y (matplotlib.colors.Colormap or str) – Univariate colormap for the y axis.

  • n (int or tuple) – Either a single integer or a (n_x, n_y) tuple specifying the number of colormap colors on the x and y axis.

Returns:

Shape (n_y, n_x, 4) array of RGBA representing the combined colormap.

Return type:

numpy.ndarray

pycolorbar.bivariate.cmap.get_bivariate_cmap_labspace(n)[source][source]#

Generate a bivariate colormap in CIELAB space.

This function creates a 2D grid of (L, a, b) values, applies non-linear transformations to the ‘a’ and ‘b’ channels, and converts the result to an RGB image.

Parameters:

n (int or tuple) –

  • If int, produce an (n, n) 2D grid.

  • If tuple (n_x, n_y), produce a (n_y, n_x) 2D grid.

Returns:

rgb_array – A 3D array of shape (n_y, n_x, 3), representing the RGB image. Pixel values lie in [0, 1].

Return type:

numpy.ndarray

Notes

  • LAB color space is perceptually uniform, so small changes in L, a, b correspond to relatively uniform changes in visual perception.

  • The tanh scaling on ‘a’ and ‘b’ compresses large values, preventing extreme color shifts.

pycolorbar.bivariate.cmap.get_bivariate_cmap_teuling(name, n, diagonal_tilt, offdiag_tilt, interp_method=None)[source][source]#

Generate a bivariate colormap using the Teuling method.

Parameters:
  • name (str) – The name of the colormap.

  • n (int) – The number of colors in the colormap.

  • diagonal_tilt (float) – The tilt angle for the diagonal colors.

  • offdiag_tilt (float) – The tilt angle for the off-diagonal colors.

  • interp_method (str, optional) – The interpolation method to use for generating the colormap.

Returns:

rgba_array – An array of RGBA colors representing the bivariate colormap.

Return type:

numpy.ndarray

pycolorbar.bivariate.cmap.get_bivariate_transparancy_rgba_array(cmap, n_x, n_y, alpha_min=0.1, alpha_max=1)[source][source]#

Create the RGBA array for the bivariate transparency colormap.

pycolorbar.bivariate.cmap.get_log_ticks(vmin, vmax)[source][source]#

Generate logarithmic tick values for a given data range.

Generates ticks at powers of 10 within the specified range, suitable for logarithmic scaling of axes.

Parameters:
  • vmin (float) – Minimum value (must be positive).

  • vmax (float) – Maximum value (must be positive).

Returns:

Array of tick positions at powers of 10 within [vmin, vmax].

Return type:

numpy.ndarray

Raises:

ValueError – If vmin or vmax are not positive or if vmin >= vmax.

pycolorbar.bivariate.cmap.get_symlog_ticks(vmin, vmax, linthresh, base=10)[source][source]#

Generate symmetric logarithmic tick values for a given data range.

For symmetric log (SymLogNorm), the scale is linear near zero (within ±linthresh) and logarithmic outside this region. This function generates ticks that respect both regions.

Parameters:
  • vmin (float) – Minimum value of the data range (typically negative).

  • vmax (float) – Maximum value of the data range (typically positive).

  • linthresh (float) – The range around zero where scaling is linear (±linthresh). Must be positive.

  • base (int, optional) – The logarithmic base. Default is 10.

Returns:

Array of tick positions suitable for symmetric log scaling. The array is symmetric around zero.

Return type:

numpy.ndarray

Raises:

ValueError – If linthresh is not positive or if vmin >= vmax.

Notes

The returned ticks respect the linear region [-linthresh, linthresh] and include logarithmically-spaced ticks outside this region.

pycolorbar.bivariate.cmap.interpolate_bivariate_cmap_colors(coords, rgba_colors, n_x, n_y, method='cubic')[source][source]#

Interpolate RGBA colors for a bivariate colormap.

Parameters:
  • coords (array-like, shape (n_points, 2)) – The coordinates of the known data points.

  • rgba_colors (array-like, shape (n_points, 4)) – The RGBA color values at the known data points.

  • n_x (int) – The number of points along the x-axis for the output grid.

  • n_y (int) – The number of points along the y-axis for the output grid.

  • method (str, optional) – The interpolation method to use. Options are ‘linear’, ‘nearest’, and ‘cubic’. Default is ‘cubic’.

Returns:

rgba_array – The interpolated RGBA color values on a grid of shape (n_y, n_x).

Return type:

ndarray, shape (n_y, n_x, 4)

pycolorbar.bivariate.cmap.load_bivariate_palette(name, n, interp_method=None)[source][source]#

Load predefined bivariate palette.

pycolorbar.bivariate.cmap.map_array_data(x, y, norm_x, norm_y, rgba_array, bad_color=(0.0, 0.0, 0.0, 0.0))[source][source]#

Map two numeric arrays (x, y) to a bivariate colormap.

Parameters:
  • x (array-like) – Numeric array for the x dimension.

  • y (array-like) – Numeric array for the y dimension. Must match shape of x.

  • norm_x (None or matplotlib.colors.Normalize) – Normalization for x dimension. If None, do min-max scaling.

  • norm_y (None or matplotlib.colors.Normalize) – Normalization for y dimension. If None, do min-max scaling.

  • rgba_array (numpy.ndarray) – The base bivariate colormap of shape (n_y, n_x, 4).

  • bad_color (tuple) – RGBA color for invalid points.

Returns:

Mapped RGBA array of shape = x.shape + (4,).

Return type:

numpy.ndarray

pycolorbar.bivariate.cmap.map_colors(x_normalized, y_normalized, n_x, n_y, rgba_array, mask, bad_color=(0.0, 0.0, 0.0, 0.0), origin='lower')[source][source]#

Map normalized (x,y) data in [0..1] to RGBA by interpolating in the 2D colormap RGBA array.

Parameters:
  • x_normalized (numpy.ndarray) – Values in [0..1], same shape as y_normalized.

  • y_normalized (numpy.ndarray) – Values in [0..1], same shape as x_normalized. Note y=0 corresponds to the bottom row, y=1 to the top row.

  • n_x (int) – Number of columns (x-axis) and rows (y-axis) in the colormap.

  • n_y (int) – Number of columns (x-axis) and rows (y-axis) in the colormap.

  • rgba_array (numpy.ndarray) – The bivariate colormap RGBA array of shape (n_y, n_x, 4).

  • mask (numpy.ndarray) – Boolean mask of shape (n_y, n_x) where True indicates NaN or invalid data.

  • bad_color (tuple of float) – RGBA color to assign to invalid points or out-of-bounds values.

  • origin (str) – Either “upper” or “lower”. The default is “lower”. When “lower”, the axis origin is on the bottom left and values (0,0) and (0,1) are mapped respectively to rgba_array[-1, 0, :] and rgba_array[0, 0, :]

Returns:

rgba_mapped – An RGBA array with out-of-range values or masked points set to bad_color.

Return type:

numpy.ndarray

pycolorbar.bivariate.cmap.map_pandas_data(x, y, norm_x, norm_y, rgba_array, bad_color=(0.0, 0.0, 0.0, 0.0))[source][source]#

Map two pandas Series (x, y) to a bivariate colormap.

Supports categorical Series and geopandas.GeoSeries.

Parameters:
  • x (pandas.Series or geopandas.Series) – Data for the x dimension.

  • y (pandas.Series or geopandas.Series) – Data for the y dimension. Must match shape of x.

  • norm_x (None or matplotlib.colors.Normalize) – Normalization for x dimension. If None, do min-max or categorical scaling.

  • norm_y (None or matplotlib.colors.Normalize) – Normalization for y dimension.

  • rgba_array (numpy.ndarray) – The bivariate colormap, shape (n_y, n_x, 4).

  • bad_color (tuple) – RGBA color for invalid or out-of-bounds points.

Returns:

Mapped RGBA array of shape = x.shape + (4,).

Return type:

numpy.ndarray

pycolorbar.bivariate.cmap.map_xarray_data(x, y, norm_x, norm_y, rgba_array, bad_color=(0.0, 0.0, 0.0, 0.0))[source][source]#

Map two xarray DataArrays (x, y) to a bivariate colormap.

Broadcasts x and y if needed, then returns an xarray DataArray with a new “rgba” dimension.

Parameters:
  • x (xarray.DataArray) – Data for x dimension.

  • y (xarray.DataArray) – Data for y dimension.

  • norm_x (None or matplotlib.colors.Normalize) – Normalization for x dimension.

  • norm_y (None or matplotlib.colors.Normalize) – Normalization for y dimension.

  • rgba_array (numpy.ndarray) – Bivariate colormap of shape (n_y, n_x, 4).

  • bad_color (tuple) – RGBA color for invalid points.

Returns:

Same shape as x,y plus a final “rgba” dimension of size 4.

Return type:

xarray.DataArray

pycolorbar.bivariate.cmap.normalize_array(arr, norm)[source][source]#

Normalize a numeric numpy array to [0..1] using either a Matplotlib norm or min-max scaling.

If norm is a BoundaryNorm, we also scale the resulting integer bin indices from [0..(N-1)] to [0..1].

Parameters:
  • arr (array-like) – Numeric array (possibly containing NaNs).

  • norm (None or matplotlib.colors.Normalize) – If not None, norm(arr) is called. If it’s a BoundaryNorm, we further scale the integer output to [0..1].

Returns:

Array of same shape as arr with values in [0..1], except for NaNs in arr, which propagate as NaNs here.

Return type:

numpy.ndarray

pycolorbar.bivariate.cmap.normalize_pandas_series(series, norm)[source][source]#

Normalize or encode a pandas Series to [0..1].

  • If it’s categorical, we map category indices -> [0..1].

  • Otherwise, it relies on normalize_array.

Parameters:
  • series (pandas.Series or geopandas.GeoSeries) – The data series to normalize.

  • norm (None or matplotlib.colors.Normalize) – Same as in normalize_array.

Returns:

Array of float in [0..1] (except for NaNs).

Return type:

numpy.ndarray

pycolorbar.bivariate.cmap.plot_bivariate_colorbar(*, bivariate_cmap, ax=None, cax=None, origin='lower', location='right', size='30%', pad=0.45, box_aspect=1, **kwargs)[source][source]#

Plot a bivariate colorbar.

This function plots a 2D colorbar representing the specified bivariate 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:
  • bivariate_cmap (pycolorbar.BivariateColormap) – The colormap to be used for the bivariate 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.

  • origin ({'lower', 'upper'}, optional) – Indicates where to locate the origin in the colorbar Axes. Default is ‘lower’.

  • location ({'right', 'left', 'top', 'bottom'}, optional) – The side of the plot where the colorbar should be placed (when ax is used). Default is ‘right’.

  • size (float or 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). Default is ‘30%’.

  • pad (float, optional) – The padding between the parent Axes and the colorbar, in inches. Default is 0.45.

  • box_aspect (float, optional) – The aspect ratio of the colorbar Axes box. Default is 1.

  • **kwargs (dict) – Additional keyword arguments passed to the internal add_bivariate_colorbar function, which is responsible for actually rendering the colorbar content.

Returns:

The image object representing the bivariate colorbar.

Return type:

matplotlib.image.AxesImage

pycolorbar.bivariate.cmap.plot_bivariate_palette(rgba_array, ax=None, *, xlim=None, ylim=None, disable_axis=False, origin='upper', aspect='auto', **imshow_kwargs)[source][source]#

Plot the bivariate colormap.

Parameters:
  • rgba_array (numpy.ndarray) – A 2D array of RGBA values representing the bivariate colormap.

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

  • xlim (list or tuple, optional) – The x-axis limits for the plot. If None, defaults to [0, n_x - 1].

  • ylim (list or tuple, optional) – The y-axis limits for the plot. If None, defaults to [0, n_y - 1].

  • disable_axis (bool, optional) – If True, the axis will be turned off. Default is False.

  • origin ({'upper', 'lower'}, optional) – The origin of the colormap. Default is ‘upper’.

  • aspect (str or float) – Either ‘equal’ or ‘auto’ or float. Controls the axes scaling (y/x-scale). If ‘auto’ fill the Axes position rectangle with data. If ‘equal’, ensure same scaling between x and y axis. The default is ‘auto’.

  • **imshow_kwargs (dict, optional) – Additional keyword arguments to pass to imshow.

Returns:

The image object created by imshow representing the bivariate colormap.

Return type:

matplotlib.image.AxesImage

Notes

If no axes are provided, a new figure and axes are created. The x and y limits can be specified, and the axis can be disabled if desired. The origin parameter determines the placement of the origin axis.

pycolorbar.bivariate.cmap.resample_rgba_array(rgba_array, n_x=None, n_y=None, interp_method=None)[source][source]#

Resample an RGBA array to a new number of colors.

Parameters:
  • rgba_array (numpy.ndarray) – Input RGBA array of shape (height, width, 4).

  • n_x (int, optional) – Desired width of the resampled array. If None, the original width is used.

  • n_y (int, optional) – Desired height of the resampled array. If None, the original height is used.

  • interp_method (str, optional) – Interpolation method to use. If None, ‘nearest’ is used for downsampling and ‘cubic’ for upsampling.

Returns:

Resampled RGBA array of shape (n_y, n_x, 4).

Return type:

numpy.ndarray

Notes

  • If both n_x and n_y are None, the original rgba_array is returned without resampling.

  • If the desired size (n_x, n_y) is the same as the input size, the original rgba_array is returned.

  • The interpolation method defaults to ‘nearest’ for downsampling and ‘cubic’ for upsampling if not specified.

pycolorbar.bivariate.cmap.set_log_axis(ax, major_ticks, axis)[source][source]#

Set logarithmic-like ticks on a linear axis for imshow plots.

Positions major and minor ticks using logarithmic transformation. Only suitable for data with values that are all positive.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes object to modify.

  • major_ticks (array-like) – The positions for major ticks in data coordinates (must be positive).

  • axis ({'x', 'y'}) – The axis to modify (“x” or “y”).

Raises:

ValueError – If major_ticks contain non-positive values.

pycolorbar.bivariate.cmap.set_symlog_axis(ax, major_ticks, axis, linthresh, base=10, linscale=1.0)[source][source]#

Set symmetric logarithmic ticks on a linear axis for imshow plots.

Positions major and minor ticks using symmetric logarithmic transformation. Suitable for data that includes both positive and negative values with a linear region near zero.

Parameters:
  • ax (matplotlib.axes.Axes) – The axes object to modify.

  • major_ticks (array-like) – The positions for major ticks in data coordinates (can include negative values).

  • axis ({'x', 'y'}) – The axis to modify (“x” or “y”).

  • linthresh (float) – The range around zero where scaling is linear (±linthresh). Must be positive.

  • base (int, optional) – The logarithmic base. Default is 10.

  • linscale (float, optional) – The number of decades to use for the linear part. Default is 1.0.

Raises:

ValueError – If linthresh is not positive.

Module contents#