Skip to content

Commit 7f63ce9

Browse files
committed
Add a dedicated ColormapRegistry class
1 parent 19aac39 commit 7f63ce9

File tree

1 file changed

+56
-2
lines changed

1 file changed

+56
-2
lines changed

lib/matplotlib/cm.py

+56-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@
1515
normalization.
1616
"""
1717

18-
from collections.abc import MutableMapping
18+
from collections.abc import Mapping, MutableMapping
19+
import copy
1920

2021
import numpy as np
2122
from numpy import ma
@@ -91,13 +92,66 @@ def _warn_deprecated(self):
9192
)
9293

9394

95+
class ColormapRegistry(Mapping):
96+
r"""
97+
Container for colormaps that are known to Matplotlib by name.
98+
99+
Read access uses a dict-like interface mapping names to `.Colormap`\s.
100+
Returned `.Colormap`.s are copies, so that their modification does not
101+
change the global definition of the colormap.
102+
103+
Additional colormaps can be added via `.ColormapRegistry.register`.
104+
"""
105+
def __init__(self, cmaps):
106+
self._cmaps = cmaps
107+
108+
def __getitem__(self, item):
109+
try:
110+
return copy.deepcopy(self._cmaps[item])
111+
except KeyError:
112+
raise KeyError(f"{item} is not a known colormap name")
113+
114+
def __iter__(self):
115+
return iter(self._cmaps)
116+
117+
def __len__(self):
118+
return len(self._cmaps)
119+
120+
def register(self, cmap, *, name=None):
121+
"""
122+
Register a new colormap.
123+
124+
The colormap name can then be used as a string argument to any ``cmap``
125+
parameter in Matplotlib. It is also available in `.pyplot.get_cmap`.
126+
127+
The colormap registry stores a copy of the given colormap, so that
128+
future changes to the original colormap instance do not affect the
129+
registered colormap. Think of this as the registry taking a snapshot
130+
of the colormap at registration.
131+
132+
Parameters
133+
----------
134+
cmap : matplotlib.colors.Colormap
135+
The colormap to register.
136+
137+
name : str, optional
138+
The name for the colormap. If not given, the :attr:`~.Colormap.name`
139+
attribute of *cmap* is used.
140+
"""
141+
register_cmap(name, copy.deepcopy(cmap))
142+
143+
94144
_cmap_registry = _gen_cmap_registry()
95145
globals().update(_cmap_registry)
96146
# This is no longer considered public API
97147
cmap_d = _DeprecatedCmapDictWrapper(_cmap_registry)
98148
__builtin_cmaps = tuple(_cmap_registry)
149+
colormaps = ColormapRegistry(_cmap_registry)
150+
r"""
151+
Container for all registered colormaps.
99152
100-
# Continue with definitions ...
153+
This is a read-only mapping of names to `.Colormap`\s. Use like a dict.
154+
"""
101155

102156

103157
def register_cmap(name=None, cmap=None, *, override_builtin=False):

0 commit comments

Comments
 (0)