Skip to content
Closed
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
9 changes: 9 additions & 0 deletions lib/matplotlib/legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import itertools
import logging
import numbers
import time

import numpy as np
Expand Down Expand Up @@ -472,6 +473,14 @@ def val_or_rc(val, rc_name):
loc = 'upper right'
if isinstance(loc, str):
loc = _api.check_getitem(self.codes, loc=loc)
elif isinstance(loc, tuple):
if len(loc) != 2 or not (all(isinstance(e, numbers.Real)
for e in loc)):
raise ValueError(
f"loc must be string or pair of numbers, not {loc!r}")
else:
raise ValueError(
f"loc must be string or pair of numbers, not {loc!r}")
if not self.isaxes and loc == 0:
raise ValueError(
"Automatic legend placement (loc='best') not implemented for "
Expand Down
24 changes: 24 additions & 0 deletions lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,3 +1090,27 @@ def test_ncol_ncols(fig_test, fig_ref):
ncols = 3
fig_test.legend(strings, ncol=ncols)
fig_ref.legend(strings, ncols=ncols)


def test_loc_invalid_tuple_exception():
# check that exception is raised if the loc arg
# of legend is not a 2-tuple of numbers
fig, ax = plt.subplots()
with pytest.raises(ValueError,
match="loc must be string or pair of numbers, not "
"\\(1.1\\,\\)"): # regex escape special chars
ax.legend(loc=(1.1, ))
with pytest.raises(ValueError,
match="loc must be string or pair of numbers, not "
"\\(0.481\\, 0.4227\\, 0.4523\\)"):
ax.legend(loc=(0.481, 0.4227, 0.4523))
with pytest.raises(ValueError,
match="loc must be string or pair of numbers, not "
"\\(0.481\\, \\'go blue\\'\\)"):
ax.legend(loc=(0.481, "go blue"))


def test_loc_valid_tuple():
fig, ax = plt.subplots()
ax.legend(loc=(0.481, 0.442))
ax.legend(loc=(1, 2))