Skip to content

cmap.Colormap#

cmap.Colormap #

A colormap is a mapping from scalar values to RGB(A) colors.

Parameters:

Name Type Description Default
value Color | ColorStop | Iterable[Color | ColorStop] | dict[float, Color]

The color data to use for the colormap. Can be a single color, a single color stop, a sequence of colors and/or color stops, or a dictionary mapping scalar values to colors.

Any of the following are valid:

  • a str containing a recognized string colormap name (e.g. "viridis", "magma"), optionally suffixed with "_r" to reverse the colormap (e.g. "viridis", "magma_r").
  • An iterable of ColorLike values (any object that can be cast to a Color), or "color-stop-like" tuples ( (float, ColorLike) where the first element is a scalar value specifying the position of the color in the gradient. When using color stops, the stop position values should be in the range [0, 1]. If no scalar stop positions are given, they will be linearly interpolated between any neighboring stops (or 0-1 if there are no stops).
  • a dict mapping scalar values to color-like values: e.g. {0.0: "red", 0.5: (0, 1, 0), 1.0: "#0000FF"}.
  • a matplotlib-style segmentdata dict, with keys "red", "green", and "blue", each of which maps to a list of tuples of the form (x, y0, y1), or a callable that takes an array of values in the range [0, 1] and returns an array of values in the range [0, 1]. See the matplotlib docs for more.
  • a Callable that takes an array of N values in the range [0, 1] and returns an (N, 4) array of RGBA values in the range [0, 1].
required
name str | None

A name for the colormap. If None, will be set to the identifier or the string "custom colormap".

None
identifier str | None

The identifier of the colormap. If None, will be set to the name, converted to lowercase and with spaces and dashes replaced by underscores.

None
category str | None

An optional category of the colormap (e.g. "diverging", "sequential"). Not used internally.

None
interpolation str | bool | None

The interpolation mode to use when mapping scalar values to colors. Can be "linear" (default) or "nearest". If True, will use "linear", if False, will use "nearest". Providing this value will override any interpolation from a catalog entry.

None
under ColorLike | None

The color to use for values below the colormap's range.

None
over ColorLike | None

The color to use for values above the colormap's range.

None
bad ColorLike | None

The color to use for bad (NaN, inf) values.

None

__call__(x: float | NDArray | Iterable[float], *, N: int = 256, gamma: float = 1, bytes: bool = False) -> Color | NDArray[np.float64] #

Map scalar values in X to an RGBA array.

This is the primary API for "using" a cmap.Colormap to map scalar values to colors.

The dtype of x matters. If x is an integer dtype, then it is interpreted as (fancy) indexing directly into the LUT. If x is a float, then it is assumed to be a normalized value in [0, 1] and will be mapped linearly to the nearest color in the LUT (use a higher N for finer sampling).

Parameters:

Name Type Description Default
x float | array - like

The scalar values to map to colors. If x is a float, a single color object will be returned. If x is an array-like, an array of RGBA colors will be returned with shape x.shape + (4,). See note above about the dtype of x.

required
N int

Number of samples in the LUT. This is used to determine the resolution of the mapping (by default, 256). Note that depending on the data being mapped, N can cause slight rounding errors in some cases. N of 256 is the default in matplotlib, so it is here as well, but note that N=255 (odd numbered) will result in an exact color match being returned for a value of 0.5 in a colormap with an odd number of colors.

256
gamma float

The gamma value to use when creating the LUT.

1
bytes bool

If False (default), the returned RGBA values will be floats in the interval [0, 1] otherwise they will be numpy.uint8\s in the interval [0, 255].

False

Returns:

Name Type Description
color Color | NDArray

If X is a float, a single RGBA color will be returned. If x is an array-like, an array of RGBA colors will be returned with shape x.shape + (4,)

Examples:

>>> from cmap import Colormap
>>> from tifffile import imread
>>> cmap = Colormap("viridis")
>>> data = imread('some_path.tif')
>>> data = data - data.min()  # normalize to 0-1
>>> data = data / data.max()  # normalize to 0-1
>>> colored_img = cmap(data)

as_dict() -> ColormapDict #

Return a dictionary representation of the colormap.

The returned dictionary is suitable for serialization, or for passing to the Colormap constructor.

catalog() -> Catalog classmethod #

Return the global colormaps catalog.

iter_colors(N: Iterable[float] | int | None = None) -> Iterator[Color] #

Return a list of N color objects sampled evenly over the range of the LUT.

If N is an integer, it will return a list of N colors spanning the full range of the colormap. If N is an iterable, it will return a list of colors at the positions specified by the iterable.

Parameters:

Name Type Description Default
N int | Iterable[float] | None

The number of colors to return, or an iterable of positions to sample. If not provided (the default), N will be set to the number of colors in the colormap.

None

Yields:

Name Type Description
color Color

Color objects.

lut(N: int = 256, gamma: float = 1, *, with_over_under: bool = False) -> np.ndarray #

Return a lookup table (LUT) for the colormap.

The returned LUT is a numpy array of RGBA values, with shape (N, 4), where N is the number of requested colors in the LUT. If with_over_under is True the returned shape will be (N + 3, 4), where index N is the under color, index N + 1 is the over color, and index N + 2 is the bad (NaN) color.

The LUT can be used to map scalar values (that have been normalized to 0-1) to colors, using fancy indexing or np.take.

The output of this function is used by the __call__ method, but may also be used directly by users.

LUTs of a particular size and gamma value are cached.

Parameters:

Name Type Description Default
N int

The number of colors in the LUT.

256
gamma float

The gamma value to use for the LUT.

1
with_over_under bool

If True, the LUT will include the under, over, and bad colors as the last three colors in the LUT. If False, the LUT will only include the colors defined by the color_stops.

False

reversed(name: str | None = None) -> Colormap #

Return a new Colormap, with reversed colors.

Parameters:

Name Type Description Default
name str | None

By default, the name of the new colormap will be the name of the original colormap with "_r" appended. If the original colormap name ends in "_r", the new colormap name will be the original name with "_r" removed. If the name argument is provided, it will be used as the name of the new colormap.

None

shifted(shift: float = 0.5, name: str | None = None, mode: Literal['wrap', 'clip'] = 'wrap') -> Colormap #

Return a new Colormap, with colors shifted by a scalar value.

This method shifts the stops in the colormap by a scalar value. It makes most sense for cyclic colormaps, but can be used with any colormap.

Parameters:

Name Type Description Default
shift float

The amount to shift the colormap. Positive values shift the colormap towards the end, negative values shift the colormap towards the beginning.

0.5
name str

A new name for the colormap. If not provided, the name of the new colormap will be the name of the original colormap with "_shifted{shift}" appended.

None
mode ('wrap', 'clip')

The mode to use when shifting the colormap. Must be one of 'wrap' or 'clip'. If 'wrap', the colormap will be shifted and wrapped around the ends. If 'clip', the colormap will be shifted and the colors at the ends will be clipped and/or repeated as necessary.

'wrap'

Returns:

Type Description
Colormap

A new colormap with the colors shifted.

to_altair(N: int = 256) -> list[str] #

Return an altair colorscale with N color samples from the colormap.

Suitable for passing to the range parameter of altair.Scale. https://altair-viz.github.io/user_guide/customization.html#color-domain-and-range

to_bokeh(N: int = 256) -> bokeh.models.LinearColorMapper #

Return a bokeh colorscale, with N color samples from the colormap.

https://docs.bokeh.org/en/latest/docs/reference/models/mappers.html

Parameters:

Name Type Description Default
N int

Number of colors to sample from the colormap, by default 256.

256

to_css(max_stops: int | None = None, angle: int = 90, radial: bool = False, as_hex: bool = False) -> str #

Return a CSS representation of the colormap as a linear or radial gradient.

Parameters:

Name Type Description Default
max_stops int

May be used to limit the number of color stops in the css.

None
angle int

Angle of the gradient in degrees. by default 90. (ignored for radial)

90
radial bool

If True, return a radial gradient, by default False.

False
as_hex bool

If True, return colors as hex strings, by default use rgba() strings.

False

Examples:

>>> from cmap import Colormap
>>> print(Colormap("brg").to_css())
background: rgb(0, 0, 255);
background: linear-gradient(
    90deg, rgb(0, 0, 255) 0%, rgb(255, 0, 0) 50%, rgb(0, 255, 0) 100%
);

to_matplotlib(N: int = 256, gamma: float = 1.0) -> matplotlib.colors.Colormap #

Return a matplotlib colormap.

to_napari() -> napari.utils.colormaps.Colormap #

Return a napari colormap.

https://napari.org/stable/api/napari.utils.Colormap.html

to_plotly() -> list[list[float | str]] #

Return a plotly colorscale.

to_pygfx(N: int = 256, *, as_view: bool | None = None) -> pygfx.Texture #

Return a pygfx Texture.

to_pyqtgraph() -> pyqtgraph.ColorMap #

Return a pyqtgraph.ColorMap.

to_viscm(dpi: int = 100, dest: str | None = None) -> matplotlib.figure.Figure #

Plot colormap using viscm. (Requires viscm to be installed.).

See https://github.com/matplotlib/viscm for details

Parameters:

Name Type Description Default
dpi int

dpi for saved image. Defaults to 100.

100
dest str

If provided, the image will be saved to this path. Defaults to None.

None

Returns:

Name Type Description
fig matplotlib.figure.Figure

The figure object containing the plot.

to_vispy() -> vispy.color.Colormap #

Return a vispy colormap.

with_extremes(*, bad: ColorLike | None = None, under: ColorLike | None = None, over: ColorLike | None = None) -> Colormap #

Return a copy of the colormap with new extreme values.