Skip to content

Commit 1c059fb

Browse files
committed
Add a helper to copy a colormap and set its extreme colors.
See changelog. See also the number of explicit copies in the examples, which suggest that the old setter-based API is a bit of a footgun (as forgetting to copy seems easy).
1 parent 745dcae commit 1c059fb

File tree

7 files changed

+48
-33
lines changed

7 files changed

+48
-33
lines changed
+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
`.Colormap.set_extremes` and `.Colormap.with_extremes`
2+
``````````````````````````````````````````````````````
3+
4+
Because the `.Colormap.set_bad`, `.Colormap.set_under` and `.Colormap.set_over`
5+
methods modify the colormap in place, the user must be careful to first make a
6+
copy of the colormap if setting the extreme colors e.g. for a builtin colormap.
7+
8+
The new ``Colormap.with_extremes(bad=..., under=..., over=...)`` can be used to
9+
first copy the colormap and set the extreme colors on that copy.
10+
11+
The new `.Colormap.set_extremes` method is provided for API symmetry with
12+
`.Colormap.with_extremes`, but note that it suffers from the same issue as the
13+
earlier individual setters.

examples/images_contours_and_fields/image_masked.py

+1-6
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
The second subplot illustrates the use of BoundaryNorm to
99
get a filled contour effect.
1010
"""
11-
from copy import copy
1211

1312
import numpy as np
1413
import matplotlib.pyplot as plt
@@ -25,11 +24,7 @@
2524
Z = (Z1 - Z2) * 2
2625

2726
# Set up a colormap:
28-
# use copy so that we do not mutate the global colormap instance
29-
palette = copy(plt.cm.gray)
30-
palette.set_over('r', 1.0)
31-
palette.set_under('g', 1.0)
32-
palette.set_bad('b', 1.0)
27+
palette = plt.cm.gray.with_extremes(over='r', under='g', bad='b')
3328
# Alternatively, we could use
3429
# palette.set_bad(alpha = 0.0)
3530
# to make the bad region transparent. This is the default.

examples/images_contours_and_fields/quadmesh_demo.py

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

12-
import copy
13-
1412
from matplotlib import cm, pyplot as plt
1513
import numpy as np
1614

@@ -30,10 +28,8 @@
3028
axs[0].pcolormesh(Qx, Qz, Z, shading='gouraud')
3129
axs[0].set_title('Without masked values')
3230

33-
# You can control the color of the masked region. We copy the default colormap
34-
# before modifying it.
35-
cmap = copy.copy(cm.get_cmap(plt.rcParams['image.cmap']))
36-
cmap.set_bad('y', 1.0)
31+
# You can control the color of the masked region.
32+
cmap = cm.get_cmap(plt.rcParams['image.cmap']).with_extremes(bad='y')
3733
axs[1].pcolormesh(Qx, Qz, Zm, shading='gouraud', cmap=cmap)
3834
axs[1].set_title('With masked values')
3935

examples/specialty_plots/leftventricle_bulleye.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -163,9 +163,8 @@ def bullseye_plot(ax, data, seg_bold=None, cmap=None, norm=None):
163163
# The second example illustrates the use of a ListedColormap, a
164164
# BoundaryNorm, and extended ends to show the "over" and "under"
165165
# value colors.
166-
cmap3 = mpl.colors.ListedColormap(['r', 'g', 'b', 'c'])
167-
cmap3.set_over('0.35')
168-
cmap3.set_under('0.75')
166+
cmap3 = (mpl.colors.ListedColormap(['r', 'g', 'b', 'c'])
167+
.with_extremes(over='0.35', under='0.75'))
169168
# If a ListedColormap is used, the length of the bounds array must be
170169
# one greater than the length of the color list. The bounds must be
171170
# monotonically increasing.

lib/matplotlib/colors.py

+24-2
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@
6666
"""
6767

6868
from collections.abc import Sized
69+
import copy
6970
import functools
7071
import itertools
7172
from numbers import Number
@@ -612,8 +613,7 @@ def __copy__(self):
612613
return cmapobject
613614

614615
def set_bad(self, color='k', alpha=None):
615-
"""Set color to be used for masked values.
616-
"""
616+
"""Set color to be used for masked values."""
617617
self._rgba_bad = to_rgba(color, alpha)
618618
if self._isinit:
619619
self._set_extremes()
@@ -634,6 +634,28 @@ def set_over(self, color='k', alpha=None):
634634
if self._isinit:
635635
self._set_extremes()
636636

637+
def set_extremes(self, *, bad=None, under=None, over=None):
638+
"""
639+
Set the colors for masked (*bad*) values and, when ``norm.clip =
640+
False``, low (*under*) and high (*over*) out-of-range values.
641+
"""
642+
if bad is not None:
643+
self.set_bad(bad)
644+
if under is not None:
645+
self.set_under(under)
646+
if over is not None:
647+
self.set_over(over)
648+
649+
def with_extremes(self, *, bad=None, under=None, over=None):
650+
"""
651+
Return a copy of the colormap, for which the colors for masked (*bad*)
652+
values and, when ``norm.clip = False``, low (*under*) and high (*over*)
653+
out-of-range values, have been set accordingly.
654+
"""
655+
new_cm = copy.copy(self)
656+
new_cm.set_extremes(bad=bad, under=under, over=over)
657+
return new_cm
658+
637659
def _set_extremes(self):
638660
if self._rgba_under:
639661
self._lut[self._i_under] = self._rgba_under

lib/matplotlib/tests/test_image.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from contextlib import ExitStack
2-
from copy import copy
32
import io
43
import os
54
from pathlib import Path
@@ -885,10 +884,7 @@ def test_mask_image_over_under():
885884
(2 * np.pi * 0.5 * 1.5))
886885
Z = 10*(Z2 - Z1) # difference of Gaussians
887886

888-
palette = copy(plt.cm.gray)
889-
palette.set_over('r', 1.0)
890-
palette.set_under('g', 1.0)
891-
palette.set_bad('b', 1.0)
887+
palette = plt.cm.gray.with_extremes(over='r', under='g', bad='b')
892888
Zm = ma.masked_where(Z > 1.2, Z)
893889
fig, (ax1, ax2) = plt.subplots(1, 2)
894890
im = ax1.imshow(Zm, interpolation='bilinear',
@@ -946,10 +942,7 @@ def test_imshow_endianess():
946942
remove_text=True, style='mpl20')
947943
def test_imshow_masked_interpolation():
948944

949-
cm = copy(plt.get_cmap('viridis'))
950-
cm.set_over('r')
951-
cm.set_under('b')
952-
cm.set_bad('k')
945+
cm = plt.get_cmap('viridis').with_extremes(over='r', under='b', bad='k')
953946

954947
N = 20
955948
n = colors.Normalize(vmin=0, vmax=N*N-1)

tutorials/colors/colorbar_only.py

+4-7
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,8 @@
6363
fig, ax = plt.subplots(figsize=(6, 1))
6464
fig.subplots_adjust(bottom=0.5)
6565

66-
cmap = mpl.colors.ListedColormap(['red', 'green', 'blue', 'cyan'])
67-
cmap.set_over('0.25')
68-
cmap.set_under('0.75')
66+
cmap = (mpl.colors.ListedColormap(['red', 'green', 'blue', 'cyan'])
67+
.with_extremes(over='0.25', under='0.75'))
6968

7069
bounds = [1, 2, 4, 7, 8]
7170
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
@@ -91,10 +90,8 @@
9190
fig, ax = plt.subplots(figsize=(6, 1))
9291
fig.subplots_adjust(bottom=0.5)
9392

94-
cmap = mpl.colors.ListedColormap(['royalblue', 'cyan',
95-
'yellow', 'orange'])
96-
cmap.set_over('red')
97-
cmap.set_under('blue')
93+
cmap = (mpl.colors.ListedColormap(['royalblue', 'cyan', 'yellow', 'orange'])
94+
.with_extremes(over='red', under='blue'))
9895

9996
bounds = [-1.0, -0.5, 0.0, 0.5, 1.0]
10097
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

0 commit comments

Comments
 (0)