diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index 14249cb73442..58e5dfcfe3b8 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -1337,6 +1337,12 @@ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs): _api.warn_external("You have mixed positional and keyword arguments, " "some input may be discarded.") + if (hasattr(handles, "__len__") and + hasattr(labels, "__len__") and + len(handles) != len(labels)): + _api.warn_external(f"Mismatched number of handles and labels: " + f"len(handles) = {len(handles)} " + f"len(labels) = {len(labels)}") # if got both handles and labels as kwargs, make same length if handles and labels: handles, labels = zip(*zip(handles, labels)) diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index 1549354ba56b..3a35b4051c71 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -1357,3 +1357,21 @@ def test_loc_validation_string_value(): ax.legend(loc='upper center') with pytest.raises(ValueError, match="'wrong' is not a valid value for"): ax.legend(loc='wrong') + + +def test_legend_handle_label_mismatch(): + pl1, = plt.plot(range(10)) + pl2, = plt.plot(range(10)) + with pytest.warns(UserWarning, match="number of handles and labels"): + legend = plt.legend(handles=[pl1, pl2], labels=["pl1", "pl2", "pl3"]) + assert len(legend.legend_handles) == 2 + assert len(legend.get_texts()) == 2 + + +def test_legend_handle_label_mismatch_no_len(): + pl1, = plt.plot(range(10)) + pl2, = plt.plot(range(10)) + legend = plt.legend(handles=iter([pl1, pl2]), + labels=iter(["pl1", "pl2", "pl3"])) + assert len(legend.legend_handles) == 2 + assert len(legend.get_texts()) == 2 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