From 214999a2e47ec3a175ce78ce2f42ed1575f21675 Mon Sep 17 00:00:00 2001 From: hannah Date: Mon, 19 May 2025 15:32:16 -0400 Subject: [PATCH] Backport PR #30079: FIX: cast legend handles to list --- lib/matplotlib/legend.py | 1 + lib/matplotlib/tests/test_legend.py | 12 ++++++++++++ 2 files changed, 13 insertions(+) diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index 0c2dfc19705c..4d8238c307ef 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -459,6 +459,7 @@ def __init__( labels = [*reversed(labels)] handles = [*reversed(handles)] + handles = list(handles) if len(handles) < 2: ncols = 1 self._ncols = ncols if ncols != 1 else ncol diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index 5e69044866db..eb3bfca7c293 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -42,6 +42,18 @@ def test_legend_ordereddict(): loc='center left', bbox_to_anchor=(1, .5)) +def test_legend_generator(): + # smoketest that generator inputs work + fig, ax = plt.subplots() + ax.plot([0, 1]) + ax.plot([0, 2]) + + handles = (line for line in ax.get_lines()) + labels = (label for label in ['spam', 'eggs']) + + ax.legend(handles, labels, loc='upper left') + + @image_comparison(['legend_auto1.png'], remove_text=True) def test_legend_auto1(): """Test automatic legend placement"""