|
15 | 15 | normalization.
|
16 | 16 | """
|
17 | 17 |
|
18 |
| -from collections.abc import MutableMapping |
| 18 | +from collections.abc import Mapping, MutableMapping |
| 19 | +import copy |
19 | 20 |
|
20 | 21 | import numpy as np
|
21 | 22 | from numpy import ma
|
@@ -91,13 +92,66 @@ def _warn_deprecated(self):
|
91 | 92 | )
|
92 | 93 |
|
93 | 94 |
|
| 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 | + |
94 | 144 | _cmap_registry = _gen_cmap_registry()
|
95 | 145 | globals().update(_cmap_registry)
|
96 | 146 | # This is no longer considered public API
|
97 | 147 | cmap_d = _DeprecatedCmapDictWrapper(_cmap_registry)
|
98 | 148 | __builtin_cmaps = tuple(_cmap_registry)
|
| 149 | +colormaps = ColormapRegistry(_cmap_registry) |
| 150 | +r""" |
| 151 | +Container for all registered colormaps. |
99 | 152 |
|
100 |
| -# Continue with definitions ... |
| 153 | +This is a read-only mapping of names to `.Colormap`\s. Use like a dict. |
| 154 | +""" |
101 | 155 |
|
102 | 156 |
|
103 | 157 | def register_cmap(name=None, cmap=None, *, override_builtin=False):
|
|
0 commit comments