Skip to content

Commit 03813be

Browse files
committed
#24605 add check to validate loc tuples
1 parent cf30ce7 commit 03813be

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

lib/matplotlib/legend.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,14 @@ def val_or_rc(val, rc_name):
472472
loc = 'upper right'
473473
if isinstance(loc, str):
474474
loc = _api.check_getitem(self.codes, loc=loc)
475+
elif isinstance(loc, tuple):
476+
if len(loc) != 2:
477+
raise ValueError(
478+
"loc must be string or pair of floats")
479+
for loc_elt in loc:
480+
# int can be converted to float, so ints are fine
481+
if not isinstance(loc_elt, (float, int)):
482+
raise ValueError(f"{loc_elt} is not a valid value for loc")
475483
if not self.isaxes and loc == 0:
476484
raise ValueError(
477485
"Automatic legend placement (loc='best') not implemented for "

lib/matplotlib/tests/test_legend.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1090,3 +1090,22 @@ 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 floats"):
1101+
ax.legend(loc=(1.1, ))
1102+
ax.legend(loc=(0.481, 0.4227, 0.4523))
1103+
with pytest.raises(ValueError,
1104+
match="go blue is not a valid value for loc"):
1105+
ax.legend(loc=(0.481, "go blue"))
1106+
1107+
1108+
def test_loc_valid_tuple():
1109+
fig, ax = plt.subplots()
1110+
ax.legend(loc=(0.481, 0.442))
1111+
ax.legend(loc=(1, 2))

0 commit comments

Comments
 (0)