Skip to content

Deprecate removal of explicit legend handles whose label starts with _. #26190

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions doc/api/next_api_changes/deprecations/26190-AL.rst
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 6 additions & 3 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
5 changes: 2 additions & 3 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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

Expand Down