cmap.Colormap#
cmap.Colormap(value: ColorStopsLike, *, name: str | None = None, identifier: str | None = None, category: str | None = None, interpolation: Interpolation | bool | None = None, under: ColorLike | None = None, over: ColorLike | None = None, bad: ColorLike | None = None)
#
A colormap is a mapping from scalar values to RGB(A) colors.
The primary way to apply a colormap to data is to call the colormap object with scalar values, which will return an array of RGBA colors. See Colormap.__call__
for details.
Parameters:
-
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].
- a
-
name
(str | None
, default:None
) –A name for the colormap. If None, will be set to the identifier or the string
"custom colormap"
. -
identifier
(str | None
, default: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.
-
category
(str | None
, default:None
) –An optional category of the colormap (e.g.
"diverging"
,"sequential"
). Not used internally. -
interpolation
(str | bool | None
, default:None
) –The interpolation mode to use when mapping scalar values to colors. Can be
"linear"
(default) or"nearest"
. IfTrue
, will use"linear"
, ifFalse
, will use"nearest"
. Providing this value will override any interpolation from a catalog entry. -
under
(ColorLike | None
, default:None
) –The color to use for values below the colormap's range.
-
over
(ColorLike | None
, default:None
) –The color to use for values above the colormap's range.
-
bad
(ColorLike | None
, default:None
) –The color to use for bad (NaN, inf) values.
bad_color: Color | None = None if bad is None else Color(bad)
instance-attribute
#
A color to use for missing/bad values when converting scalars to colors.
If provided, and Colormap.lut
is called with with_over_under=True
, bad_color
will be the last color in the LUT (lut[-1]
).
category: str | None = category
instance-attribute
#
An optional category for the colormap.
If not provided, and if the colormap is a catalog colormap, this will be set to the category of the colormap.
color_stops: ColorStops = stops
instance-attribute
#
The color stops in the colormap.
This object is a sequence of color stops: a color (RGBA) and a scalar position (0-1) in the gradient. This is the primary data structure used to represent the colormap. See ColorStops
docstring for more information.
identifier: str = _make_identifier(identifier or name)
instance-attribute
#
An identifier for the colormaps.
If not provided, it will be generated from name
by discarding any characters that are not alphanumeric, spaces, dashes, or underscores, converting to lowercase, replacing spaces and dashes with underscores, and prefacing with "_"
if the first character is a digit.
interpolation: Interpolation = _norm_interp(interpolation)
instance-attribute
#
The interpolation mode to use when mapping scalar values to colors.
Either "linear"
or "nearest"
, where "linear"
is the default.
name: str = name
instance-attribute
#
A display name for the colormap.
If not provided explicitly, and if the colormap is a catalog colormap, this will be set to "namespace:name"
. If not a catalog colormap, it will be set to the identifier
, or fallback to "custom colormap"
.
num_colors: int
property
#
The number of colors in this colormap.
over_color: Color | None = None if over is None else Color(over)
instance-attribute
#
A color to use for values above 1 when converting scalars to colors.
If provided, and Colormap.lut
is called with with_over_under=True
, over_color
will be the second-to-last color in the LUT (lut[-2]
).
under_color: Color | None = None if under is None else Color(under)
instance-attribute
#
A color to use for values below 0 when converting scalars to colors.
If provided, and Colormap.lut
is called with with_over_under=True
, under_color
will be the third-to-last color in the LUT (lut[-3]
).
__call__(x: float | NDArray | Iterable[float], *, N: int = 256, gamma: float = 1, bytes: bool = False) -> Color | NDArray[np.float64]
#
__call__(x: NDArray | Iterable[float], *, N: int = 256, gamma: float = 1, bytes: bool = False) -> NDArray[np.float64]
__call__(x: float, *, N: int = 256, gamma: float = 1, bytes: bool = False) -> Color
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:
-
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 shapex.shape + (4,)
. See note above about the dtype of x. -
N
(int
, default:256
) –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.
-
gamma
(float
, default:1
) –The gamma value to use when creating the LUT.
-
bytes
(bool
, default:False
) –If False (default), the returned RGBA values will be floats in the interval
[0, 1]
otherwise they will benumpy.uint8
\s in the interval[0, 255]
.
Returns:
-
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:
-
N
(int | Iterable[float] | None
, default: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.
Yields:
-
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:
-
N
(int
, default:256
) –The number of colors in the LUT.
-
gamma
(float
, default:1
) –The gamma value to use for the LUT.
-
with_over_under
(bool
, default:False
) –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.
reversed(name: str | None = None) -> Colormap
#
Return a new Colormap, with reversed colors.
Parameters:
-
name
(str | None
, default: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.
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:
-
shift
(float
, default:0.5
) –The amount to shift the colormap. Positive values shift the colormap towards the end, negative values shift the colormap towards the beginning.
-
name
(str
, default:None
) –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.
-
mode
(('wrap', 'clip')
, default:'wrap'
) –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.
Returns:
-
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:
-
N
(int
, default:256
) –Number of colors to sample from the colormap, by default 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:
-
max_stops
(int
, default:None
) –May be used to limit the number of color stops in the css.
-
angle
(int
, default:90
) –Angle of the gradient in degrees. by default 90. (ignored for radial)
-
radial
(bool
, default:False
) –If
True
, return a radial gradient, by default False. -
as_hex
(bool
, default:False
) –If
True
, return colors as hex strings, by default usergba()
strings.
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:
-
dpi
(int
, default:100
) –dpi for saved image. Defaults to 100.
-
dest
(str
, default:None
) –If provided, the image will be saved to this path. Defaults to None.
Returns:
-
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.
cmap.ColorStops(stops: np.ndarray | Iterable[tuple[float, Color]] | None = None, *, lut_func: LutCallable | None = None, interpolation: Interpolation | bool = 'linear')
#
A sequence of color stops in a color gradient.
Convenience class allowing various operations on a sequence of color stops, including casting to an (N, 5) array (e.g. np.asarray(ColorStops(...))
)
This is the main internal representation of a colormap, and is used to construct the LUT used in the Colormap.call method.
Parameters:
-
stops
(array - like
, default:None
) –An array of color stops, by default None (must provide either stops or lut_func) The array must be an (N, 5) array, where the first column is the position (0-1) and the remaining columns are the color (RGBA, 0-1).
-
lut_func
(callable
, default:None
) –A callable that takes a single argument (an (N, 1) array of positions) and returns an (N, 4) array of colors. This will be used to generate the LUT instead of the stops array. If provided, the stops argument will be ignored.
-
interpolation
(str
, default:'linear'
) –Interpolation mode. Must be one of 'linear' (or
True
) or 'nearest' (orFalse
). Defaults to 'linear'.
color_array: np.ndarray
property
#
Return an (N, 4) array of RGBA values.
colors: tuple[Color, ...]
property
#
Return all colors as Color objects.
stops: tuple[float, ...]
property
#
Return tuple of color stop positions.
__array__(dtype: npt.DTypeLike = None) -> np.ndarray
#
Return (N, 5) array, N rows of (position, r, g, b, a).
__getitem__(key: int | slice | tuple) -> ColorStop | ColorStops | np.ndarray
#
__getitem__(key: int) -> ColorStop
__getitem__(key: slice) -> ColorStops
__getitem__(key: tuple) -> np.ndarray
Get an item or slice of the color stops.
If key is an integer, return a single ColorStop
tuple. If key is a slice, return a new ColorStops
object. If key is a tuple, return a numpy array (standard numpy indexing).
__repr__() -> str
#
Return a string representation of the ColorStops.
parse(colors: ColorStopsLike) -> ColorStops
classmethod
#
Parse any colorstops-like object into a ColorStops object.
Each item in colors
can be a color, or a 2-tuple of (position, color), where position (the "stop" along a color gradient) is a float between 0 and 1. Where not provided, color positions will be evenly distributed between neighboring specified positions (if fill_mode
is 'neighboring') or will be replaced with index / (len(colors)-1)
(if fill_mode
is 'fractional').
Colors can be expressed as anything that can be converted to a Color, including a string, or 3/4-sequence of RGB(A) values.
Parameters:
Returns:
-
ColorStops
–A sequence of color stops.
reversed() -> ColorStops
#
Return a new ColorStops object with reversed colors.
shifted(shift: float, mode: Literal['wrap', 'clip'] = 'wrap') -> ColorStops
#
Return a new ColorStops object with all positions shifted by shift
.
Parameters:
-
shift
(float
) –The amount to shift the colormap. Positive values shift the colormap towards the end, negative values shift the colormap towards the beginning.
-
mode
(('wrap', 'clip')
, default:'wrap'
) –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.
to_css(max_stops: int | None = None, angle: int = 90, radial: bool = False, as_hex: bool = False) -> str
#
Return a CSS representation of the color stops.
Parameters:
-
max_stops
(int
, default:None
) –May be used to limit the number of color stops in the css.
-
angle
(int
, default:90
) –Angle of the gradient in degrees. by default 90. (ignored for radial)
-
radial
(bool
, default:False
) –If
True
, return a radial gradient, by default False. -
as_hex
(bool
, default:False
) –If
True
, return colors as hex strings, by default usergba()
strings.
cmap._colormap.ColorStop
#
A color stop in a color gradient.
Just a named tuple with a position
(float
) and a color
(cmap.Color
).