Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Update handling of sequence labels for plot #27767

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
Feb 15, 2024
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/behavior/27767-REC.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Legend labels for ``plot``
~~~~~~~~~~~~~~~~~~~~~~~~~~

Previously if a sequence was passed to the *label* parameter of `~.Axes.plot` when
plotting a single dataset, the sequence was automatically cast to string for the legend
label. Now, if the sequence has only one element, that element will be the legend
label. To keep the old behavior, cast the sequence to string before passing.
9 changes: 9 additions & 0 deletions doc/api/next_api_changes/deprecations/27767-REC.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Legend labels for ``plot``
~~~~~~~~~~~~~~~~~~~~~~~~~~

Previously if a sequence was passed to the *label* parameter of `~.Axes.plot` when
plotting a single dataset, the sequence was automatically cast to string for the legend
label. This behavior is now deprecated and in future will error if the sequence length
is not one (consistent with multi-dataset behavior, where the number of elements must
match the number of datasets). To keep the old behavior, cast the sequence to string
before passing.
20 changes: 14 additions & 6 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,14 +513,22 @@ def _plot_args(self, axes, tup, kwargs, *,

label = kwargs.get('label')
n_datasets = max(ncx, ncy)
if n_datasets > 1 and not cbook.is_scalar_or_string(label):
if len(label) != n_datasets:
raise ValueError(f"label must be scalar or have the same "
f"length as the input data, but found "
f"{len(label)} for {n_datasets} datasets.")

if cbook.is_scalar_or_string(label):
labels = [label] * n_datasets
elif len(label) == n_datasets:
labels = label
elif n_datasets == 1:
msg = (f'Passing label as a length {len(label)} sequence when '
'plotting a single dataset is deprecated in Matplotlib 3.9 '
'and will error in 3.11. To keep the current behavior, '
'cast the sequence to string before passing.')
_api.warn_deprecated('3.9', message=msg)
labels = [label]
else:
labels = [label] * n_datasets
raise ValueError(
f"label must be scalar or have the same length as the input "
f"data, but found {len(label)} for {n_datasets} datasets.")

result = (make_artist(axes, x[:, j % ncx], y[:, j % ncy], kw,
{**kwargs, 'label': label})
Expand Down
10 changes: 9 additions & 1 deletion lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -1197,12 +1197,20 @@ def test_plot_single_input_multiple_label(label_array):
x = [1, 2, 3]
y = [2, 5, 6]
fig, ax = plt.subplots()
ax.plot(x, y, label=label_array)
with pytest.warns(mpl.MatplotlibDeprecationWarning,
match='Passing label as a length 2 sequence'):
ax.plot(x, y, label=label_array)
leg = ax.legend()
assert len(leg.get_texts()) == 1
assert leg.get_texts()[0].get_text() == str(label_array)


def test_plot_single_input_list_label():
fig, ax = plt.subplots()
line, = ax.plot([[0], [1]], label=['A'])
assert line.get_label() == 'A'


def test_plot_multiple_label_incorrect_length_exception():
# check that exception is raised if multiple labels
# are given, but number of on labels != number of lines
Expand Down