From 4ff34abd85b85030dc591b12c2d8ec77f00e7a75 Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Fri, 7 Mar 2025 23:10:25 +0100 Subject: [PATCH] FIX: Warn when trying to set_facecolor on a array-mapped Collection Colormapping array data takes precedence and an explicit facecolor is thus ignored. We now issue a warning because this should not pass silently. Closes #27555. --- lib/matplotlib/collections.py | 10 ++++++++++ lib/matplotlib/tests/test_collections.py | 8 ++++++++ 2 files changed, 18 insertions(+) diff --git a/lib/matplotlib/collections.py b/lib/matplotlib/collections.py index a3f245bbc2c8..a594165d8594 100644 --- a/lib/matplotlib/collections.py +++ b/lib/matplotlib/collections.py @@ -778,6 +778,16 @@ def _get_default_facecolor(self): return mpl.rcParams['patch.facecolor'] def _set_facecolor(self, c): + if self.get_array() is not None: + # Note: we cannot use self._face_is_mapped here because it is + # lazily calculated in update_scalarmappable(), but the equivalent + # logic there is that colormapping from an array takes precedence + # over an explicit facecolor. + _api.warn_external( + "Setting the facecolor has no effect because there is colormapped " + "array data, which takes precedence. Use `set_array(None)` before " + "setting the facecolor to override this.") + if c is None: c = self._get_default_facecolor() diff --git a/lib/matplotlib/tests/test_collections.py b/lib/matplotlib/tests/test_collections.py index db9c4be81a44..77efa6b2fa8d 100644 --- a/lib/matplotlib/tests/test_collections.py +++ b/lib/matplotlib/tests/test_collections.py @@ -333,6 +333,14 @@ def test_add_collection(): assert ax.dataLim.bounds == bounds +def test_collection_facecolor(): + pc = plt.figure().subplots().scatter([0, 1, 2], [0, 1, 2], c=[0, 0.5, 1]) + with pytest.warns(match="Setting the facecolor has no effect"): + pc.set_facecolor(['r', 'g', 'b']) + # the returned facecolor is the colormapped one: + pc.get_facecolor() == plt.get_cmap()([0, 0.5, 1]) + + @mpl.style.context('mpl20') @check_figures_equal(extensions=['png']) def test_collection_log_datalim(fig_test, fig_ref):