CMasher
Scientific colormaps for making accessible, informative and cmashing plots.
- cmasher.combine_cmaps(*cmaps: Colormap | str, nodes: list[float] | ndarray | None = None, n_rgb_levels: int = 256, combined_cmap_name: str = 'combined_cmap') LinearSegmentedColormap [source]
Create a composite matplotlib colormap by combining multiple colormaps.
- Parameters:
*cmaps (Colormap or colormap name (str) to be combined.)
nodes (list or numpy array of nodes (float). Defaults: equal divisions.) – The blending points between colormaps, in the range [0, 1].
n_rgb_levels (int. Defaults: 256.) – Number of RGB levels for each colormap segment.
combined_cmap_name (str. Defaults: “combined_cmap”.) – name of the combined Colormap.
- Returns:
Colormap (The composite colormap.)
- 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.
Note
The colormaps are combined from low value to high value end.
References
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])
- cmasher.create_cmap_mod(cmap: str, *, save_dir: str | PathLike[str] = '.', _copy_name: str | None = None) str [source]
Creates a standalone Python module of the provided CMasher cmap and saves it in the given save_dir as ‘<cmap>.py’.
A standalone colormap module can be used to quickly share a colormap with someone without adding the CMasher dependency. Importing the created module allows the colormap to be used in the same way as usual through MPL (including the ‘cmr.’ prefix).
- Parameters:
cmap (str) – The name of the CMasher colormap a standalone Python module must be made for. An added ‘cmr.’ prefix will be ignored.
- Other Parameters:
save_dir (str or os.PathLike[str] Default: ‘.’) – The path to the directory where the module must be saved. By default, the current directory is used.
- Returns:
cmap_path (str) – The path to the Python file containing the colormap module.
Example
Creating a standalone Python module of the ‘rainforest’ colormap:
>>> create_cmap_mod('rainforest')
One can now import the ‘rainforest’ colormap in any script by moving the created ‘rainforest.py’ file to the proper working directory and importing it with
import rainforest
.Note
Unlike other CMasher utility functions, cmap solely accepts names of colormaps that are registered in CMasher (
cmasher.cm
).
- cmasher.create_cmap_overview(cmaps: list[str | Colormap] | dict[str, list[Colormap]] | None = None, *, savefig: str | PathLike[str] | None = None, use_types: bool = True, sort: str | Callable | None = 'alphabetical', show_grayscale: bool = True, show_info: bool = False, plot_profile: bool | float = False, dark_mode: bool = False, title: str | None = 'Colormap Overview', wscale: float = 1, hscale: float = 1) None [source]
Creates an overview plot containing all colormaps defined in the provided cmaps.
- Other Parameters:
cmaps (list of {str;
Colormap
objects}, dict of lists or None. Default: None) – A list of all colormaps that must be included in the overview plot. If dict of lists, the keys define categories for the colormaps. If None, all colormaps defined in CMasher are used instead.savefig (str, os.PathLike or None. Default: None) – If not None, the path where the overview plot must be saved to. Else, the plot will simply be shown.
use_types (bool. Default: True) – Whether all colormaps in cmaps should be categorized into their colormap types (sequential; diverging; cyclic; qualitative; misc). If cmaps is a dict, this value is ignored.
sort ({‘alphabetical’/’name’; ‘lightness’; ‘perceptual’}, function or None. Default: ‘alphabetical’) – String or function indicating how the colormaps should be sorted in the overview. If ‘alphabetical’, the colormaps are sorted alphabetically on their name. If ‘lightness’, the colormaps are sorted based on their lightness profile, which is given by
_get_cmap_lightness_rank()
. If ‘perceptual’, the colormaps sorted based on their perceptual range in addition to their lightness profile, which is given by_get_cmap_perceptual_rank()
. Note that this is only meaningful if all cmaps are perceptually uniform sequential. If function, a function definition that takes aColormap
object and returns the sorted position of that colormap. If None, the colormaps retain the order they were given in.show_grayscale (bool. Default: True) – Whether to show the grayscale versions of the given cmaps in the overview.
show_info (bool. Default: False) – Whether the statistics information of all sequential, diverging and cyclic colormaps should be shown under their names. This is a series of numbers representing, in order, the starting (sequential) or central (diverging/cyclic) lightness value; the final/outer lightness value; and the perceptual range of the colormap.
plot_profile (bool or float. Default: False) – Whether the lightness profiles of all non-qualitative colormaps should be plotted. If not False, the lightness profile of a colormap is plotted on top of its gray-scale version and plot_profile is used for setting the alpha (opacity) value. If plot_profile is True, it will be set to 0.25. If show_grayscale is False, this value is ignored.
dark_mode (bool. Default: False) – Whether the colormap overview should be created using mostly dark colors.
title (str or None. Default: “Colormap Overview”) – String to be used as the title of the colormap overview. If empty or None, no title will be used.
wscale, hscale (float. Default: (1, 1)) – Floats that determine with what factor the colormap subplot dimensions in the overview should be scaled with. The default values uses the default dimensions for the subplots (which are determined by other input arguments).
Notes
The colormaps in cmaps can either be provided as their registered name in
matplotlib.cm
, or their correspondingColormap
object. Any provided reversed colormaps (colormaps that end their name with ‘_r’) are ignored if their normal versions were provided as well.When sort is ‘lightness’ or ‘perceptual’, qualitative and miscellaneous colormaps are solely sorted on their names, as the lightness/perceptual profile of these colormaps is meaningless.
If plot_profile is not set to False, the lightness profiles are plotted on top of the gray-scale colormap versions, where the y-axis ranges from 0% lightness to 100% lightness. The lightness profile transitions between black and white at 50% lightness.
- cmasher.get_bibtex() None [source]
Prints a string that gives the BibTeX entry for citing the CMasher paper (Van der Velden 2020, JOSS, 5, 2004).
- cmasher.get_cmap_list(cmap_type: str = 'all') list[str] [source]
Returns a list with the names of all colormaps available in CMasher of the given cmap_type.
Note that CMasher colormaps registered in MPL have an added ‘cmr.’ prefix.
- Other Parameters:
cmap_type ({‘a’/’all’; ‘s’/’seq’/’sequential’; ‘d’/’div’/’diverging’; ‘c’/’cyc’/’cyclic’}. Default: ‘all’) – The colormap type that should be in the returned list.
- Returns:
cmap_list (list of str) – List containing the names of all colormaps available in CMasher.
- cmasher.get_cmap_type(cmap: str | Colormap) str [source]
Checks what the colormap type (sequential; diverging; cyclic; qualitative; misc) of the provided cmap is and returns it.
- Parameters:
cmap (str or
Colormap
object) – The registered name of the colormap inmatplotlib.cm
or its correspondingColormap
object.- Returns:
cm_type ({‘sequential’; ‘diverging’; ‘cyclic’; ‘qualitative’; ‘misc’}) – A string stating which of the defined colormap types the provided cmap has.
- cmasher.get_sub_cmap(cmap: str | Colormap, start: float, stop: float, *, N: int | None = None) ListedColormap [source]
Creates a
ListedColormap
object using the colors in the range [start, stop] of the provided cmap and returns it.This function can be used to create a colormap that only uses a portion of an existing colormap. If N is not set to None, this function creates a qualitative colormap from cmap instead.
- Parameters:
cmap (str or
Colormap
object) – The registered name of the colormap inmatplotlib.cm
or its correspondingColormap
object.start, stop (float) – The normalized range of the colors in cmap that must be in the sub-colormap.
- Other Parameters:
N (int or None. Default: None) – The number of color segments to take from the provided cmap within the range given by the provided start and stop. If None, take all colors in cmap within this range.
- Returns:
sub_cmap (
ListedColormap
) – The created colormap that uses a subset of the colors in cmap. If N is not None, this will be a qualitative colormap.
Example
Creating a colormap using the first 80% of the ‘rainforest’ colormap:
>>> get_sub_cmap('cmr.rainforest', 0, 0.8)
Creating a qualitative colormap containing five colors from the middle 60% of the ‘lilac’ colormap:
>>> get_sub_cmap('cmr.lilac', 0.2, 0.8, N=5)
Notes
As it can create artifacts, this function does not interpolate between the colors in cmap to fill up the space. Therefore, using values for start and stop that are too close to each other, may result in a colormap that contains too few different colors to be smooth. It is recommended to use at least 128 different colors in a colormap for optimal results (CMasher colormaps have 256 or 511/510 different colors, for sequential or diverging/cyclic colormaps respectively). One can check the number of colors in a colormap with
matplotlib.colors.Colormap.N
.Any colormaps created using this function are not registered in either CMasher or MPL.
- cmasher.import_cmaps(cmap_path: str | PathLike[str], *, _skip_registration: bool = False) None [source]
Reads in custom colormaps from a provided file or directory cmap_path; transforms them into
ListedColormap
objects; and makes them available in thecmasher.cm
module, in addition to registering them in thematplotlib.cm
module. Both the imported colormap and its reversed version will be registered.If a provided colormap is a ‘cyclic’ colormap, its shifted version will also be registered with the _s suffix.
- Parameters:
cmap_path (str or os.PathLike[str]) – Relative or absolute path to a custom colormap file; or directory that contains custom colormap files. A colormap file can be a NumPy binary file (‘.npy’); a viscm source file (‘.jscm’); or any text file. If the file is not a JSCM-file, it must contain the normalized; 8-bit; or hexadecimal string RGB values that define the colormap.
Notes
All colormap files must have names starting with the ‘cm_’ prefix. The resulting colormaps will have the name of their file without the prefix and extension.
In MPL, the colormaps will have the added ‘cmr.’ prefix to avoid name clashes.
Example
Importing a colormap named ‘test’ can be done by saving its normalized RGB values in a file called ‘cm_test.txt’ and executing
>>> import_cmaps('/path/to/dir/cm_test.txt')
The ‘test’ colormap is now available in CMasher and MPL using
>>> cmr.cm.test # CMasher >>> plt.get_cmap('cmr.test') # MPL
- cmasher.register_cmap(name: str, data: list[tuple[float, float, float]]) None [source]
Creates a
ListedColormap
object using the provided name and data, and registers the colormap in thecmasher.cm
andmatplotlib.cm
modules. A reversed version of the colormap will be registered as well.- Parameters:
name (str) – The name that this colormap must have.
data (2D array_like of {float; int} with shape (N, 3) or 1D array_like of str with shape (N, )) – An array containing the RGB values of all segments in the colormap. If float, the array contains normalized RGB values. If int, the array contains 8-bit RGB values. If str, the array contains hexadecimal string RGB values.
Note
In MPL, the colormap will have the added ‘cmr.’ prefix to avoid name clashes.
- cmasher.set_cmap_legend_entry(artist: Artist, label: str) None [source]
Sets the label of the provided artist to label, and creates a legend entry using a miniature version of the colormap of artist as the legend icon.
This function can be used to add legend entries for MPL artists that use a colormap, like those made with
hexbin()
;hist2d()
;scatter()
; or anypyplot
function that takes cmap as an input argument. Keep in mind that using this function will override any legend entry that already exists for artist.- Parameters:
artist (
Artist
object) – Any artist object that has the cmap attribute, for which a legend entry must be made using its colormap as the icon.label (str) – The string that must be set as the label of artist.
- cmasher.take_cmap_colors(cmap: str | Colormap, N: int | None, *, cmap_range: tuple[float, float] = (0, 1), return_fmt: str = 'float') list[tuple[float, float, float]] [source]
Takes N equally spaced colors from the provided colormap cmap and returns them.
- Parameters:
cmap (str or
Colormap
object) – The registered name of the colormap inmatplotlib.cm
or its correspondingColormap
object.N (int or None) – The number of colors to take from the provided cmap within the given cmap_range. If None, take all colors in cmap within this range.
- Other Parameters:
cmap_range (tuple of float. Default: (0, 1)) – The normalized value range in the colormap from which colors should be taken. By default, colors are taken from the entire colormap.
return_fmt ({‘float’/’norm’; ‘int’/’8bit’; ‘str’/’hex’}. Default: ‘float’) – The format of the requested colors. If ‘float’/’norm’, the colors are returned as normalized RGB tuples. If ‘int’/’8bit’, the colors are returned as 8-bit RGB tuples. If ‘str’/’hex’, the colors are returned using their hexadecimal string representations.
- Returns:
colors (list of {tuple; str}) – The colors that were taken from the provided cmap.
Examples
Taking five equally spaced colors from the ‘rainforest’ colormap:
>>> take_cmap_colors('cmr.rainforest', 5) [(0.0, 0.0, 0.0), (0.226123592, 0.124584033, 0.562997277), (0.0548210513, 0.515835251, 0.45667819), (0.709615979, 0.722863985, 0.0834727592), (1.0, 1.0, 1.0)]
Requesting their 8-bit RGB values instead:
>>> take_cmap_colors('cmr.rainforest', 5, return_fmt='int') [(0, 0, 0), (58, 32, 144), (14, 132, 116), (181, 184, 21), (255, 255, 255)]
Requesting HEX-code values instead:
>>> take_cmap_colors('cmr.rainforest', 5, return_fmt='hex') ['#000000', '#3A2090', '#0E8474', '#B5B815', '#FFFFFF']
Requesting colors in a specific range:
>>> take_cmap_colors('cmr.rainforest', 5, cmap_range=(0.2, 0.8), return_fmt='hex') ['#3E0374', '#10528A', '#0E8474', '#5CAD3C', '#D6BF4A']
Note
Using this function on a perceptually uniform sequential colormap, like those in CMasher, allows one to pick a number of line colors that are different but still sequential. This is useful when plotting a set of lines that describe the same property, but have a different initial state.
- cmasher.view_cmap(cmap: str | Colormap, *, savefig: str | None = None, show_test: bool = False, show_grayscale: bool = False) None [source]
Shows a simple plot of the provided cmap.
- Parameters:
cmap (str or
Colormap
object) – The registered name of the colormap inmatplotlib.cm
or its correspondingColormap
object.- Other Parameters:
savefig (str or None. Default: None) – If not None, the path where the plot must be saved to. Else, the plot will simply be shown.
show_test (bool. Default: False) – If True, show a colormap test in the plot instead.
show_grayscale (bool. Default: False) – If True, also show the grayscale version of cmap.