Skip to content

Commit d72116b

Browse files
BUG/PLT: Multiple plots with different cmap, colorbars legends use first cmap (#33392)
1 parent 2a68c12 commit d72116b

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

doc/source/whatsnew/v1.1.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,7 @@ Plotting
523523
- :func:`.plot` for line/bar now accepts color by dictonary (:issue:`8193`).
524524
- Bug in :meth:`DataFrame.plot.hist` where weights are not working for multiple columns (:issue:`33173`)
525525
- Bug in :meth:`DataFrame.boxplot` and :meth:`DataFrame.plot.boxplot` lost color attributes of ``medianprops``, ``whiskerprops``, ``capprops`` and ``medianprops`` (:issue:`30346`)
526+
- Bug in :meth:`DataFrame.plot.scatter` that when adding multiple plots with different ``cmap``, colorbars alway use the first ``cmap`` (:issue:`33389`)
526527

527528

528529
Groupby/resample/rolling

pandas/plotting/_matplotlib/core.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -902,7 +902,11 @@ def _plot_colorbar(self, ax, **kwds):
902902
# For a more detailed description of the issue
903903
# see the following link:
904904
# https://github.com/ipython/ipython/issues/11215
905-
img = ax.collections[0]
905+
906+
# GH33389, if ax is used multiple times, we should always
907+
# use the last one which contains the latest information
908+
# about the ax
909+
img = ax.collections[-1]
906910
cbar = self.fig.colorbar(img, ax=ax, **kwds)
907911

908912
if _mpl_ge_3_0_0():

pandas/tests/plotting/test_frame.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1332,6 +1332,20 @@ def test_scatter_colors(self):
13321332
np.array([1, 1, 1, 1], dtype=np.float64),
13331333
)
13341334

1335+
def test_scatter_colorbar_different_cmap(self):
1336+
# GH 33389
1337+
import matplotlib.pyplot as plt
1338+
1339+
df = pd.DataFrame({"x": [1, 2, 3], "y": [1, 3, 2], "c": [1, 2, 3]})
1340+
df["x2"] = df["x"] + 1
1341+
1342+
fig, ax = plt.subplots()
1343+
df.plot("x", "y", c="c", kind="scatter", cmap="cividis", ax=ax)
1344+
df.plot("x2", "y", c="c", kind="scatter", cmap="magma", ax=ax)
1345+
1346+
assert ax.collections[0].cmap.name == "cividis"
1347+
assert ax.collections[1].cmap.name == "magma"
1348+
13351349
@pytest.mark.slow
13361350
def test_plot_bar(self):
13371351
df = DataFrame(

0 commit comments

Comments
 (0)