From ef6fa3da7e3a2d71b0bf241fc95152df971c64aa Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Fri, 7 Jun 2024 00:04:42 +0200 Subject: [PATCH] MNT: Re-add matplotlib.cm.get_cmap This was removed in 3.9, but apparently caused more user trouble than expected. Re-added for 3.9.1 and extended the deprecation period for two additional minor releases. --- lib/matplotlib/cm.py | 38 ++++++++++++++++++++++++++++++++++++++ lib/matplotlib/cm.pyi | 2 ++ 2 files changed, 40 insertions(+) diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index cec9f0be4355..071c93f9f0b3 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -239,6 +239,44 @@ def get_cmap(self, cmap): globals().update(_colormaps) +# This is an exact copy of pyplot.get_cmap(). It was removed in 3.9, but apparently +# caused more user trouble than expected. Re-added for 3.9.1 and extended the +# deprecation period for two additional minor releases. +@_api.deprecated( + '3.7', + removal='3.11', + alternative="``matplotlib.colormaps[name]`` or ``matplotlib.colormaps.get_cmap()``" + " or ``pyplot.get_cmap()``" + ) +def get_cmap(name=None, lut=None): + """ + Get a colormap instance, defaulting to rc values if *name* is None. + + Parameters + ---------- + name : `~matplotlib.colors.Colormap` or str or None, default: None + If a `.Colormap` instance, it will be returned. Otherwise, the name of + a colormap known to Matplotlib, which will be resampled by *lut*. The + default, None, means :rc:`image.cmap`. + lut : int or None, default: None + If *name* is not already a Colormap instance and *lut* is not None, the + colormap will be resampled to have *lut* entries in the lookup table. + + Returns + ------- + Colormap + """ + if name is None: + name = mpl.rcParams['image.cmap'] + if isinstance(name, colors.Colormap): + return name + _api.check_in_list(sorted(_colormaps), name=name) + if lut is None: + return _colormaps[name] + else: + return _colormaps[name].resampled(lut) + + def _auto_norm_from_scale(scale_cls): """ Automatically generate a norm class from *scale_cls*. diff --git a/lib/matplotlib/cm.pyi b/lib/matplotlib/cm.pyi index da78d940ba4a..be8f10b39cb6 100644 --- a/lib/matplotlib/cm.pyi +++ b/lib/matplotlib/cm.pyi @@ -19,6 +19,8 @@ class ColormapRegistry(Mapping[str, colors.Colormap]): _colormaps: ColormapRegistry = ... +def get_cmap(name: str | colors.Colormap | None = ..., lut: int | None = ...) -> colors.Colormap: ... + class ScalarMappable: cmap: colors.Colormap | None colorbar: Colorbar | None