diff --git a/doc/source/whatsnew/v1.5.2.rst b/doc/source/whatsnew/v1.5.2.rst index 4f6274b9084da..c95f563a77708 100644 --- a/doc/source/whatsnew/v1.5.2.rst +++ b/doc/source/whatsnew/v1.5.2.rst @@ -14,6 +14,8 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`Series.replace` raising ``RecursionError`` with numeric dtype and when specifying ``value=None`` (:issue:`45725`) +- Fixed regression in :meth:`DataFrame.plot` preventing :class:`~matplotlib.colors.Colormap` instance + from being passed using the ``colormap`` argument if Matplotlib 3.6+ is used (:issue:`49374`) - .. --------------------------------------------------------------------------- diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index fb44082aa5b58..8f21823ddcd02 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -3610,7 +3610,7 @@ def _background_gradient( if cmap is None: rgbas = mpl.colormaps[mpl.rcParams["image.cmap"]](norm(gmap)) else: - rgbas = mpl.colormaps[cmap](norm(gmap)) + rgbas = mpl.colormaps.get_cmap(cmap)(norm(gmap)) else: rgbas = plt.cm.get_cmap(cmap)(norm(gmap)) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 9bcb51a7b032a..8292ffd0425f5 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1231,7 +1231,7 @@ def _make_plot(self): if self.colormap is not None: if mpl_ge_3_6_0(): - cmap = mpl.colormaps[self.colormap] + cmap = mpl.colormaps.get_cmap(self.colormap) else: cmap = self.plt.cm.get_cmap(self.colormap) else: @@ -1311,7 +1311,7 @@ def _make_plot(self) -> None: # pandas uses colormap, matplotlib uses cmap. cmap = self.colormap or "BuGn" if mpl_ge_3_6_0(): - cmap = mpl.colormaps[cmap] + cmap = mpl.colormaps.get_cmap(cmap) else: cmap = self.plt.cm.get_cmap(cmap) cb = self.kwds.pop("colorbar", True) diff --git a/pandas/tests/io/formats/style/test_matplotlib.py b/pandas/tests/io/formats/style/test_matplotlib.py index c5b05b4e0d0c1..f0c4152e3339b 100644 --- a/pandas/tests/io/formats/style/test_matplotlib.py +++ b/pandas/tests/io/formats/style/test_matplotlib.py @@ -288,3 +288,17 @@ def test_bar_color_raises(df): msg = "`color` and `cmap` cannot both be given" with pytest.raises(ValueError, match=msg): df.style.bar(color="something", cmap="something else").to_html() + + +@pytest.mark.parametrize( + "plot_method", + ["scatter", "hexbin"], +) +def test_pass_colormap_instance(df, plot_method): + # https://github.com/pandas-dev/pandas/issues/49374 + cmap = mpl.colors.ListedColormap([[1, 1, 1], [0, 0, 0]]) + df["c"] = df.A + df.B + kwargs = dict(x="A", y="B", c="c", colormap=cmap) + if plot_method == "hexbin": + kwargs["C"] = kwargs.pop("c") + getattr(df.plot, plot_method)(**kwargs)