From 2f8a08b32c794d53e52e2997db89d3a2684f763c Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Mon, 26 Jun 2023 11:04:52 +0200 Subject: [PATCH] Deprecate removal of explicit legend handles whose label starts with _. --- doc/api/next_api_changes/deprecations/26190-AL.rst | 7 +++++++ lib/matplotlib/legend.py | 9 ++++++--- lib/matplotlib/tests/test_legend.py | 5 ++--- 3 files changed, 15 insertions(+), 6 deletions(-) create mode 100644 doc/api/next_api_changes/deprecations/26190-AL.rst diff --git a/doc/api/next_api_changes/deprecations/26190-AL.rst b/doc/api/next_api_changes/deprecations/26190-AL.rst new file mode 100644 index 000000000000..0bf4bd15097c --- /dev/null +++ b/doc/api/next_api_changes/deprecations/26190-AL.rst @@ -0,0 +1,7 @@ +Artists explicitly passed in will no longer be filtered by legend() based on their label +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Currently, artists explicitly passed to ``legend(handles=[...])`` are filtered +out if their label starts with an underscore. This behavior is deprecated; +explicitly filter out such artists +(``[art for art in artists if not art.get_label().startswith('_')]``) if +necessary. diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index 1857d48fc78c..abe1d906e561 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -465,9 +465,12 @@ def val_or_rc(val, rc_name): _lab, _hand = [], [] for label, handle in zip(labels, handles): if isinstance(label, str) and label.startswith('_'): - _api.warn_external(f"The label {label!r} of {handle!r} starts " - "with '_'. It is thus excluded from the " - "legend.") + _api.warn_deprecated("3.8", message=( + "An artist whose label starts with an underscore was passed to " + "legend(); such artists will no longer be ignored in the future. " + "To suppress this warning, explicitly filter out such artists, " + "e.g. with `[art for art in artists if not " + "art.get_label().startswith('_')]`.")) else: _lab.append(label) _hand.append(handle) diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index 801254332dd6..76aa90f4d435 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -17,7 +17,7 @@ import matplotlib.lines as mlines from matplotlib.legend_handler import HandlerTuple import matplotlib.legend as mlegend -from matplotlib import rc_context +from matplotlib import _api, rc_context from matplotlib.font_manager import FontProperties @@ -144,8 +144,7 @@ def test_legend_label_with_leading_underscore(): """ fig, ax = plt.subplots() line, = ax.plot([0, 1], label='_foo') - with pytest.warns(UserWarning, - match=r"starts with '_'.*excluded from the legend."): + with pytest.warns(_api.MatplotlibDeprecationWarning, match="with an underscore"): legend = ax.legend(handles=[line]) assert len(legend.legend_handles) == 0