Skip to content

Commit 3aedb5e

Browse files
authored
Merge pull request #20935 from timhoffm/experimental-colormaps
ENH: Add ColormapsRegistry as experimental and add it to pyplot
2 parents fbafb06 + abd8213 commit 3aedb5e

File tree

12 files changed

+44
-274
lines changed

12 files changed

+44
-274
lines changed

doc/api/pyplot_summary.rst

+2-1
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,5 @@ For a more in-depth look at colormaps, see the
2929

3030
.. currentmodule:: matplotlib.pyplot
3131

32-
.. autofunction:: colormaps
32+
.. autodata:: colormaps
33+
:no-value:
+14-10
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
1-
Colormap registry
2-
------------------
1+
Colormap registry (experimental)
2+
--------------------------------
33

4-
Colormaps are now managed via `matplotlib.colormaps`, which is a
5-
`.ColormapRegistry`.
4+
Colormaps are now managed via `matplotlib.colormaps` (or `.pyplot.colormaps`),
5+
which is a `.ColormapRegistry`. While we are confident that the API is final,
6+
we formally mark it as experimental for 3.5 because we want to keep the option
7+
to still adapt the API for 3.6 should the need arise.
68

79
Colormaps can be obtained using item access::
810

9-
import matplotlib as mpl
10-
cmap = mpl.colormaps['viridis']
11+
import matplotlib.pyplot as plt
12+
cmap = plt.colormaps['viridis']
1113

1214
To register new colormaps use::
1315

14-
mpl.colormaps.register(my_colormap)
16+
plt.colormaps.register(my_colormap)
1517

16-
The use of `matplotlib.cm.get_cmap` and `matplotlib.cm.register_cmap` is
17-
discouraged in favor of the above. Within `.pyplot` the use of
18-
``plt.get_cmap()`` and ``plt.register_cmap()`` will continue to be supported.
18+
We recommend to use the new API instead of the `~.cm.get_cmap` and
19+
`~.cm.register_cmap` functions for new code. `matplotlib.cm.get_cmap` and
20+
`matplotlib.cm.register_cmap` will eventually be deprecated and removed.
21+
Within `.pyplot` ``plt.get_cmap()`` and ``plt.register_cmap()`` will continue
22+
to be supported for backward compatibility.

examples/images_contours_and_fields/contourf_demo.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
How to use the `.axes.Axes.contourf` method to create filled contour plots.
77
"""
88
import numpy as np
9-
import matplotlib as mpl
109
import matplotlib.pyplot as plt
1110

1211
origin = 'lower'
@@ -87,7 +86,7 @@
8786

8887
# Illustrate all 4 possible "extend" settings:
8988
extends = ["neither", "both", "min", "max"]
90-
cmap = mpl.colormaps["winter"].with_extremes(under="magenta", over="yellow")
89+
cmap = plt.colormaps["winter"].with_extremes(under="magenta", over="yellow")
9190
# Note: contouring simply excludes masked or nan regions, so
9291
# instead of using the "bad" colormap value for them, it draws
9392
# nothing at all in them. Therefore the following would have

examples/images_contours_and_fields/demo_bboximage.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
a bounding box. This demo shows how to show an image inside a `.text.Text`'s
88
bounding box as well as how to manually create a bounding box for the image.
99
"""
10-
import matplotlib as mpl
1110
import matplotlib.pyplot as plt
1211
import numpy as np
1312
from matplotlib.image import BboxImage
@@ -39,7 +38,7 @@
3938
a = np.vstack((a, a))
4039

4140
# List of all colormaps; skip reversed colormaps.
42-
cmap_names = sorted(m for m in mpl.colormaps if not m.endswith("_r"))
41+
cmap_names = sorted(m for m in plt.colormaps if not m.endswith("_r"))
4342

4443
ncol = 2
4544
nrow = len(cmap_names) // ncol + 1

examples/images_contours_and_fields/pcolormesh_levels.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@
9494

9595
# pick the desired colormap, sensible levels, and define a normalization
9696
# instance which takes data values and translates those into levels.
97-
cmap = plt.get_cmap('PiYG')
97+
cmap = plt.colormaps['PiYG']
9898
norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
9999

100100
fig, (ax0, ax1) = plt.subplots(nrows=2)

examples/images_contours_and_fields/quadmesh_demo.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
This demo illustrates a bug in quadmesh with masked data.
1010
"""
1111

12-
import matplotlib as mpl
1312
from matplotlib import pyplot as plt
1413
import numpy as np
1514

@@ -30,7 +29,7 @@
3029
axs[0].set_title('Without masked values')
3130

3231
# You can control the color of the masked region.
33-
cmap = mpl.colormaps[mpl.rcParams['image.cmap']].with_extremes(bad='y')
32+
cmap = plt.colormaps[plt.rcParams['image.cmap']].with_extremes(bad='y')
3433
axs[1].pcolormesh(Qx, Qz, Zm, shading='gouraud', cmap=cmap)
3534
axs[1].set_title('With masked values')
3635

examples/lines_bars_and_markers/horizontal_barchart_distribution.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def survey(results, category_names):
4343
labels = list(results.keys())
4444
data = np.array(list(results.values()))
4545
data_cum = data.cumsum(axis=1)
46-
category_colors = plt.get_cmap('RdYlGn')(
46+
category_colors = plt.colormaps['RdYlGn'](
4747
np.linspace(0.15, 0.85, data.shape[1]))
4848

4949
fig, ax = plt.subplots(figsize=(9.2, 5))

examples/mplot3d/polys3d.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def polygon_under_graph(x, y):
3232

3333
# verts[i] is a list of (x, y) pairs defining polygon i.
3434
verts = [polygon_under_graph(x, poisson.pmf(l, x)) for l in lambdas]
35-
facecolors = plt.get_cmap('viridis_r')(np.linspace(0, 1, len(verts)))
35+
facecolors = plt.colormaps['viridis_r'](np.linspace(0, 1, len(verts)))
3636

3737
poly = PolyCollection(verts, facecolors=facecolors, alpha=.7)
3838
ax.add_collection3d(poly, zs=lambdas, zdir='y')

examples/pie_and_polar_charts/nested_pie.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
99
"""
1010

11-
import matplotlib as mpl
1211
import matplotlib.pyplot as plt
1312
import numpy as np
1413

@@ -31,7 +30,7 @@
3130
size = 0.3
3231
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
3332

34-
cmap = mpl.colormaps["tab20c"]
33+
cmap = plt.colormaps["tab20c"]
3534
outer_colors = cmap(np.arange(3)*4)
3635
inner_colors = cmap([1, 2, 5, 6, 9, 10])
3736

@@ -62,7 +61,7 @@
6261
# Obtain the ordinates of the bar edges
6362
valsleft = np.cumsum(np.append(0, valsnorm.flatten()[:-1])).reshape(vals.shape)
6463

65-
cmap = mpl.colormaps["tab20c"]
64+
cmap = plt.colormaps["tab20c"]
6665
outer_colors = cmap(np.arange(3)*4)
6766
inner_colors = cmap([1, 2, 5, 6, 9, 10])
6867

examples/userdemo/colormap_interactive_adjustment.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def adjust_colorbar(mouseevent):
5454
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
5555
Z = (0.9*Z1 - 0.5*Z2) * 2
5656

57-
cmap = plt.get_cmap('viridis').with_extremes(
57+
cmap = plt.colormaps['viridis'].with_extremes(
5858
over='xkcd:orange', under='xkcd:dark red')
5959
axesimage = plt.imshow(Z, cmap=cmap)
6060
colorbar = plt.colorbar(axesimage, ax=ax, use_gridspec=True)

lib/matplotlib/cm.py

+16
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,12 @@ class ColormapRegistry(Mapping):
102102
r"""
103103
Container for colormaps that are known to Matplotlib by name.
104104
105+
.. admonition:: Experimental
106+
107+
While we expect the API to be final, we formally mark it as
108+
experimental for 3.5 because we want to keep the option to still adapt
109+
the API for 3.6 should the need arise.
110+
105111
The universal registry instance is `matplotlib.colormaps`. There should be
106112
no need for users to instantiate `.ColormapRegistry` themselves.
107113
@@ -136,6 +142,16 @@ def __str__(self):
136142
return ('ColormapRegistry; available colormaps:\n' +
137143
', '.join(f"'{name}'" for name in self))
138144

145+
def __call__(self):
146+
"""
147+
Return a list of the registered colormap names.
148+
149+
This exists only for backward-compatibilty in `.pyplot` which had a
150+
``plt.colormaps()`` method. The recommended way to get this list is
151+
now ``list(colormaps)``.
152+
"""
153+
return list(self)
154+
139155
def register(self, cmap, *, name=None, force=False):
140156
"""
141157
Register a new colormap.

0 commit comments

Comments
 (0)