8000 Add a dedicated ColormapRegistry class · matplotlib/matplotlib@a19b3ba · GitHub
[go: up one dir, main page]

Skip to content

Commit a19b3ba

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

File tree

1 file changed

+57
-2
lines changed

1 file changed

+57
-2
lines changed

lib/matplotlib/cm.py

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@
1515
normalization.
1616
"""
1717

18-
from collections.abc import MutableMapping
18+
from collections.abc import Mapping, MutableMapping
19+
import copy
20+
import functools
1921

2022
import numpy as np
2123
from numpy import ma
@@ -91,13 +93,66 @@ def _warn_deprecated(self):
9193
)
9294

9395

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

102157

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

0 commit comments

Comments
 (0)
0