Backport PR #24111 on branch v3.6.x (FIX: add missing method to ColormapRegistry) by meeseeksmachine · Pull Request #24124 · matplotlib/matplotlib · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions doc/api/prev_api_changes/api_changes_3.6.0/deprecations.rst
48 changes: 41 additions & 7 deletions lib/matplotlib/cm.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,6 @@ class ColormapRegistry(Mapping):
r"""
Container for colormaps that are known to Matplotlib by name.

.. admonition:: Experimental

While we expect the API to be final, we formally mark it as
experimental for 3.5 because we want to keep the option to still adapt
the API for 3.6 should the need arise.

The universal registry instance is `matplotlib.colormaps`. There should be
no need for users to instantiate `.ColormapRegistry` themselves.

Expand Down Expand Up @@ -193,6 +187,38 @@ def unregister(self, name):
"colormap.")
self._cmaps.pop(name, None)

def get_cmap(self, cmap):
"""
Return a color map specified through *cmap*.

Parameters
----------
cmap : str or `~matplotlib.colors.Colormap` or None

- if a `.Colormap`, return it
- if a string, look it up in ``mpl.colormaps``
- if None, return the Colormap defined in :rc:`image.cmap`

Returns
-------
Colormap
"""
# get the default color map
if cmap is None:
return self[mpl.rcParams["image.cmap"]]

# if the user passed in a Colormap, simply return it
if isinstance(cmap, colors.Colormap):
return cmap
if isinstance(cmap, str):
_api.check_in_list(sorted(_colormaps), cmap=cmap)
# otherwise, it must be a string so look it up
return self[cmap]
raise TypeError(
'get_cmap expects None or an instance of a str or Colormap . ' +
f'you passed {cmap!r} of type {type(cmap)}'
)


# public access to the colormaps should be via `matplotlib.colormaps`. For now,
# we still create the registry here, but that should stay an implementation
Expand Down Expand Up @@ -281,7 +307,12 @@ def _get_cmap(name=None, lut=None):
# pyplot.
get_cmap = _api.deprecated(
'3.6',
name='get_cmap', pending=True, alternative="``matplotlib.colormaps[name]``"
name='get_cmap',
pending=True,
alternative=(
"``matplotlib.colormaps[name]`` " +
"or ``matplotlib.colormaps.get_cmap(obj)``"
)
)(_get_cmap)


Expand Down Expand Up @@ -687,6 +718,8 @@ def _ensure_cmap(cmap):
"""
Ensure that we have a `.Colormap` object.

For internal use to preserve type stability of errors.

Parameters
----------
cmap : None, str, Colormap
Expand All @@ -698,6 +731,7 @@ def _ensure_cmap(cmap):
Returns
-------
Colormap

"""
if isinstance(cmap, colors.Colormap):
return cmap
Expand Down
20 changes: 20 additions & 0 deletions lib/matplotlib/tests/test_colors.py