Skip to content

Commit 4aa7efe

Browse files
authored
Merge pull request #27004 from borgesaugusto/iss_24050
Warning if handles and labels have a len mismatch
2 parents 7f63a18 + 38a17d6 commit 4aa7efe

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

lib/matplotlib/legend.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1337,6 +1337,12 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
13371337
_api.warn_external("You have mixed positional and keyword arguments, "
13381338
"some input may be discarded.")
13391339

1340+
if (hasattr(handles, "__len__") and
1341+
hasattr(labels, "__len__") and
1342+
len(handles) != len(labels)):
1343+
_api.warn_external(f"Mismatched number of handles and labels: "
1344+
f"len(handles) = {len(handles)} "
1345+
f"len(labels) = {len(labels)}")
13401346
# if got both handles and labels as kwargs, make same length
13411347
if handles and labels:
13421348
handles, labels = zip(*zip(handles, labels))

lib/matplotlib/tests/test_legend.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1357,3 +1357,21 @@ def test_loc_validation_string_value():
13571357
ax.legend(loc='upper center')
13581358
with pytest.raises(ValueError, match="'wrong' is not a valid value for"):
13591359
ax.legend(loc='wrong')
1360+
1361+
1362+
def test_legend_handle_label_mismatch():
1363+
pl1, = plt.plot(range(10))
1364+
pl2, = plt.plot(range(10))
1365+
with pytest.warns(UserWarning, match="number of handles and labels"):
1366+
legend = plt.legend(handles=[pl1, pl2], labels=["pl1", "pl2", "pl3"])
1367+
assert len(legend.legend_handles) == 2
1368+
assert len(legend.get_texts()) == 2
1369+
1370+
1371+
def test_legend_handle_label_mismatch_no_len():
1372+
pl1, = plt.plot(range(10))
1373+
pl2, = plt.plot(range(10))
1374+
legend = plt.legend(handles=iter([pl1, pl2]),
1375+
labels=iter(["pl1", "pl2", "pl3"]))
1376+
assert len(legend.legend_handles) == 2
1377+
assert len(legend.get_texts()) == 2

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy