Skip to content

Add multiple label support for Axes.plot() #16178

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 22 commits into from
Dec 24, 2020
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
19 changes: 19 additions & 0 deletions doc/users/next_whats_new/multiple_labels_for_Axes_plot.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
An iterable object with labels can be passed to `.Axes.plot`
------------------------------------------------------------

When plotting multiple datasets by passing 2D data as *y* value to
`~.Axes.plot`, labels for the datasets can be passed as a list, the
length matching the number of columns in *y*.

.. plot::

import matplotlib.pyplot as plt

x = [1, 2, 3]

y = [[1, 2],
[2, 5],
[4, 9]]

plt.plot(x, y, label=['low', 'high'])
plt.legend()
2 changes: 2 additions & 0 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1499,6 +1499,8 @@ def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs):

If you make multiple lines with one plot call, the kwargs
apply to all those lines.
In case if label object is iterable, each its element is
used as label for a separate line.

Here is a list of available `.Line2D` properties:

Expand Down
24 changes: 22 additions & 2 deletions lib/matplotlib/axes/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,12 @@ def __call__(self, *args, data=None, **kwargs):
replaced[label_namer_idx], args[label_namer_idx])
args = replaced

if len(args) >= 4 and not cbook.is_scalar_or_string(
kwargs.get("label")):
raise ValueError("plot() with multiple groups of data (i.e., "
"pairs of x and y) does not support multiple "
"labels")

# Repeatedly grab (x, y) or (x, y, format) from the front of args and
# massage them into arguments to plot() or fill().

Expand Down Expand Up @@ -446,8 +452,22 @@ def _plot_args(self, tup, kwargs, return_kwargs=False):
ncx, ncy = x.shape[1], y.shape[1]
if ncx > 1 and ncy > 1 and ncx != ncy:
raise ValueError(f"x has {ncx} columns but y has {ncy} columns")
result = (func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
for j in range(max(ncx, ncy)))

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.")
labels = label
else:
labels = [label] * n_datasets

result = (func(x[:, j % ncx], y[:, j % ncy], kw,
{**kwargs, 'label': label})
for j, label in enumerate(labels))

if return_kwargs:
return list(result)
else:
Expand Down
62 changes: 62 additions & 0 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,3 +671,65 @@ def test_no_warn_big_data_when_loc_specified():
ax.plot(np.arange(5000), label=idx)
legend = ax.legend('best')
fig.draw_artist(legend) # Check that no warning is emitted.


@pytest.mark.parametrize('label_array', [['low', 'high'],
('low', 'high'),
np.array(['low', 'high'])])
def test_plot_multiple_input_multiple_label(label_array):
# test ax.plot() with multidimensional input
# and multiple labels
x = [1, 2, 3]
y = [[1, 2],
[2, 5],
[4, 9]]

fig, ax = plt.subplots()
ax.plot(x, y, label=label_array)
leg = ax.legend()
legend_texts = [entry.get_text() for entry in leg.get_texts()]
assert legend_texts == ['low', 'high']


@pytest.mark.parametrize('label', ['one', 1, int])
def test_plot_multiple_input_single_label(label):
# test ax.plot() with multidimensional input
# and single label
x = [1, 2, 3]
y = [[1, 2],
[2, 5],
[4, 9]]

fig, ax = plt.subplots()
ax.plot(x, y, label=label)
leg = ax.legend()
legend_texts = [entry.get_text() for entry in leg.get_texts()]
assert legend_texts == [str(label)] * 2


@pytest.mark.parametrize('label_array', [['low', 'high'],
('low', 'high'),
np.array(['low', 'high'])])
def test_plot_single_input_multiple_label(label_array):
# test ax.plot() with 1D array like input
# and iterable label
x = [1, 2, 3]
y = [2, 5, 6]
fig, ax = plt.subplots()
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_multiple_label_incorrect_length_exception():
# check that excepton is raised if multiple labels
# are given, but number of on labels != number of lines
with pytest.raises(ValueError):
x = [1, 2, 3]
y = [[1, 2],
[2, 5],
[4, 9]]
label = ['high', 'low', 'medium']
fig, ax = plt.subplots()
ax.plot(x, y, label=label)
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