From 4630a4a28b2afbdb41e37a45ef440c403d39d9f5 Mon Sep 17 00:00:00 2001 From: Elliott Sales de Andrade Date: Tue, 21 Dec 2021 01:18:00 -0500 Subject: [PATCH] Backport PR #22009: FIX: Prevent set_alpha from changing color of legend patch --- lib/matplotlib/legend_handler.py | 2 ++ lib/matplotlib/tests/test_legend.py | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/lib/matplotlib/legend_handler.py b/lib/matplotlib/legend_handler.py index b289e26cc1f5..c6bd96dc84fb 100644 --- a/lib/matplotlib/legend_handler.py +++ b/lib/matplotlib/legend_handler.py @@ -815,6 +815,8 @@ def get_first(prop_array): # Directly set Patch color attributes (must be RGBA tuples). legend_handle._facecolor = first_color(orig_handle.get_facecolor()) legend_handle._edgecolor = first_color(orig_handle.get_edgecolor()) + legend_handle._original_facecolor = orig_handle._original_facecolor + legend_handle._original_edgecolor = orig_handle._original_edgecolor legend_handle._fill = orig_handle.get_fill() legend_handle._hatch = orig_handle.get_hatch() # Hatch color is anomalous in having no getters and setters. diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index 21c8ab748d9b..fe8a8dd5f61b 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -880,3 +880,11 @@ def test_subfigure_legend(): ax.plot([0, 1], [0, 1], label="line") leg = subfig.legend() assert leg.figure is subfig + + +def test_setting_alpha_keeps_polycollection_color(): + pc = plt.fill_between([0, 1], [2, 3], color='#123456', label='label') + patch = plt.legend().get_patches()[0] + patch.set_alpha(0.5) + assert patch.get_facecolor()[:3] == tuple(pc.get_facecolor()[0][:3]) + assert patch.get_edgecolor()[:3] == tuple(pc.get_edgecolor()[0][:3])