Skip to content

Commit 0b7fcba

Browse files
committed
#24605 add check to validate loc tuples
1 parent e710123 commit 0b7fcba

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

lib/matplotlib/legend.py

+9
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
import itertools
2525
import logging
26+
import numbers
2627
import time
2728

2829
import numpy as np
@@ -472,6 +473,14 @@ def val_or_rc(val, rc_name):
472473
loc = 'upper right'
473474
if isinstance(loc, str):
474475
loc = _api.check_getitem(self.codes, loc=loc)
476+
elif isinstance(loc, tuple):
477+
if len(loc) != 2 or not (all(isinstance(e, numbers.Real)
478+
for e in loc)):
479+
raise ValueError(
480+
f"loc must be string or pair of numbers, not {loc!r}")
481+
else:
482+
raise ValueError(
483+
f"loc must be string or pair of numbers, not {loc!r}")
475484
if not self.isaxes and loc == 0:
476485
raise ValueError(
477486
"Automatic legend placement (loc='best') not implemented for "

lib/matplotlib/tests/test_legend.py

+24
Original file line numberDiff line numberDiff line change
@@ -1090,3 +1090,27 @@ def test_ncol_ncols(fig_test, fig_ref):
10901090
ncols = 3
10911091
fig_test.legend(strings, ncol=ncols)
10921092
fig_ref.legend(strings, ncols=ncols)
1093+
1094+
1095+
def test_loc_invalid_tuple_exception():
1096+
# check that exception is raised if the loc arg
1097+
# of legend is not a 2-tuple of numbers
1098+
fig, ax = plt.subplots()
1099+
with pytest.raises(ValueError,
1100+
match="loc must be string or pair of numbers, not "
1101+
"\\(1.1\\,\\)"): # regex escape special chars
1102+
ax.legend(loc=(1.1, ))
1103+
with pytest.raises(ValueError,
1104+
match="loc must be string or pair of numbers, not "
1105+
"\\(0.481\\, 0.4227\\, 0.4523\\)"):
1106+
ax.legend(loc=(0.481, 0.4227, 0.4523))
1107+
with pytest.raises(ValueError,
1108+
match="loc must be string or pair of numbers, not "
1109+
"\\(0.481\\, \\'go blue\\'\\)"):
1110+
ax.legend(loc=(0.481, "go blue"))
1111+
1112+
1113+
def test_loc_valid_tuple():
1114+
fig, ax = plt.subplots()
1115+
ax.legend(loc=(0.481, 0.442))
1116+
ax.legend(loc=(1, 2))

0 commit comments

Comments
 (0)