diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index 75c909418c98..34924a5f955e 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -543,7 +543,7 @@ def _warn_if_global_cmap_modified(cmap): "colormap. In future versions, you will not be able to " "modify a registered colormap in-place. To remove this " "warning, you can make a copy of the colormap first. " - f'cmap = copy.copy(mpl.cm.get_cmap("{cmap.name}"))' + f'cmap = mpl.cm.get_cmap("{cmap.name}").copy()' ) @@ -827,6 +827,10 @@ def color_block(color): f'over {color_block(self.get_over())}' '') + def copy(self): + """Return a copy of the colormap.""" + return self.__copy__() + class LinearSegmentedColormap(Colormap): """ diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index fff69da380bf..d9c31a148a9b 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -150,6 +150,16 @@ def test_colormap_copy(): with np.errstate(invalid='ignore'): ret2 = copied_cmap([-1, 0, .5, 1, np.nan, np.inf]) assert_array_equal(ret1, ret2) + # again with the .copy method: + cmap = plt.cm.Reds + copied_cmap = cmap.copy() + with np.errstate(invalid='ignore'): + ret1 = copied_cmap([-1, 0, .5, 1, np.nan, np.inf]) + cmap2 = copy.copy(copied_cmap) + cmap2.set_bad('g') + with np.errstate(invalid='ignore'): + ret2 = copied_cmap([-1, 0, .5, 1, np.nan, np.inf]) + assert_array_equal(ret1, ret2) def test_colormap_endian():