8000 Merge pull request #23550 from oscargus/mpltoolkitcleanups · oscargus/matplotlib@80d79eb · GitHub
[go: up one dir, main page]

Skip to content

Commit 80d79eb

Browse files
authored
Merge pull request matplotlib#23550 from oscargus/mpltoolkitcleanups
Change exception types, improve argument checking, and cleanups in mpl_toolkits
2 parents 02e93e2 + e94dfed commit 80d79eb

File tree

5 files changed

+65
-29
lines changed

5 files changed

+65
-29
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
Specified exception types in Grid
2+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3+
4+
In a few cases an `Exception` was thrown when an incorrect argument value
5+
was set in the `mpl_toolkits.axes_grid1.axes_grid.Grid`
6+
(= `mpl_toolkits.axisartist.axes_grid.Grid`) constructor. These are replaced
7+
as follows:
8+
9+
* Providing an incorrect value for *ngrids* now raises a `ValueError`
10+
* Providing an incorrect type for *rect* now raises a `TypeError`

lib/mpl_toolkits/axes_grid1/axes_divider.py

Lines changed: 19 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ def __init__(self, fig, pos, horizontal, vertical,
3939
aspect : bool
4040
Whether overall rectangular area is reduced so that the relative
4141
part of the horizontal and vertical scales have the same scale.
42-
anchor : {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W'}
42+
anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
43+
'NW', 'W'}
4344
Placement of the reduced rectangle, when *aspect* is True.
4445
"""
4546

@@ -48,6 +49,7 @@ def __init__(self, fig, pos, horizontal, vertical,
4849
self._horizontal = horizontal
4950
self._vertical = vertical
5051
self._anchor = anchor
52+
self.set_anchor(anchor)
5153
self._aspect = aspect
5254
self._xrefindex = 0
5355
self._yrefindex = 0
@@ -106,7 +108,8 @@ def set_anchor(self, anchor):
106108
"""
107109
Parameters
108110
----------
109-
anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
111+
anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
112+
'NW', 'W'}
110113
Either an (*x*, *y*) pair of relative coordinates (0 is left or
111114
bottom, 1 is right or top), 'C' (center), or a cardinal direction
112115
('SW', southwest, is bottom left, etc.).
@@ -115,8 +118,10 @@ def set_anchor(self, anchor):
115118
--------
116119
.Axes.set_anchor
117120
"""
118-
if len(anchor) != 2:
121+
if isinstance(anchor, str):
119122
_api.check_in_list(mtransforms.Bbox.coefs, anchor=anchor)
123+
elif not isinstance(anchor, (tuple, list)) or len(anchor) != 2:
124+
raise TypeError("anchor must be str or 2-tuple")
120125
self._anchor = anchor
121126

122127
def get_anchor(self):
@@ -250,6 +255,8 @@ def new_locator(self, nx, ny, nx1=None, ny1=None):
250255
ny1 if ny1 is not None else ny + 1)
251256

252257
def append_size(self, position, size):
258+
_api.check_in_list(["left", "right", "bottom", "top"],
259+
position=position)
253260
if position == "left":
254261
self._horizontal.insert(0, size)
255262
self._xrefindex += 1
@@ -258,11 +265,8 @@ def append_size(self, position, size):
258265
elif position == "bottom":
259266
self._vertical.insert(0, size)
260267
self._yrefindex += 1
261-
elif position == "top":
268+
else: # 'top'
262269
self._vertical.append(size)
263-
else:
264-
_api.check_in_list(["left", "right", "bottom", "top"],
265-
position=position)
266270

267271
def add_auto_adjustable_area(self, use_axes, pad=0.1, adjust_dirs=None):
268272
"""
@@ -512,21 +516,14 @@ def append_axes(self, position, size, pad=None, add_to_figure=True, *,
512516
**kwargs
513517
All extra keywords arguments are passed to the created axes.
514518
"""
515-
if position == "left":
516-
ax = self.new_horizontal(
517-
size, pad, pack_start=True, axes_class=axes_class, **kwargs)
518-
elif position == "right":
519-
ax = self.new_horizontal(
520-
size, pad, pack_start=False, axes_class=axes_class, **kwargs)
521-
elif position == "bottom":
522-
ax = self.new_vertical(
523-
size, pad, pack_start=True, axes_class=axes_class, **kwargs)
524-
elif position == "top":
525-
ax = self.new_vertical(
526-
size, pad, pack_start=False, axes_class=axes_class, **kwargs)
527-
else:
528-
_api.check_in_list(["left", "right", "bottom", "top"],
529-
position=position)
519+
create_axes, pack_start = _api.check_getitem({
520+
"left": (self.new_horizontal, True),
521+
"right": (self.new_horizontal, False),
522+
"bottom": (self.new_vertical, True),
523+
"top": (self.new_vertical, False),
524+
}, position=position)
525+
ax = create_axes(
526+
size, pad, pack_start=pack_start, axes_class=axes_class, **kwargs)
530527
if add_to_figure:
531528
self._fig.add_axes(ax)
532529
return ax

lib/mpl_toolkits/axes_grid1/axes_grid.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,8 @@ def __init__(self, fig,
123123
ngrids = self._nrows * self._ncols
124124
else:
125125
if not 0 < ngrids <= self._nrows * self._ncols:
126-
raise Exception("")
126+
raise ValueError(
127+
"ngrids must be positive and not larger than nrows*ncols")
127128

128129
self.ngrids = ngrids
129130

@@ -147,7 +148,7 @@ def __init__(self, fig,
147148
elif len(rect) == 4:
148149
self._divider = Divider(fig, rect, **kw)
149150
else:
150-
raise Exception("")
151+
raise TypeError("Incorrect rect format")
151152

152153
rect = self._divider.get_position()
153154

@@ -270,6 +271,7 @@ def set_label_mode(self, mode):
270271
- "1": Only the bottom left axes is labelled.
271272
- "all": all axes are labelled.
272273
"""
274+
_api.check_in_list(["all", "L", "1"], mode=mode)
273275
if mode == "all":
274276
for ax in self.axes_all:
275277
_tick_only(ax, False, False)
@@ -290,7 +292,7 @@ def set_label_mode(self, mode):
290292
ax = col[-1]
291293
_tick_only(ax, bottom_on=False, left_on=True)
292294

293-
elif mode == "1":
295+
else: # "1"
294296
for ax in self.axes_all:
295297
_tick_only(ax, bottom_on=True, left_on=True)
296298

@@ -378,6 +380,10 @@ def __init__(self, fig,
378380
to associated *cbar_axes*.
379381
axes_class : subclass of `matplotlib.axes.Axes`, default: None
380382
"""
383+
_api.check_in_list(["each", "single", "edge", None],
384+
cbar_mode=cbar_mode)
385+
_api.check_in_list(["left", "right", "bottom", "top"],
386+
cbar_location=cbar_location)
381387
self._colorbar_mode = cbar_mode
382388
self._colorbar_location = cbar_location
383389
self._colorbar_pad = cbar_pad

lib/mpl_toolkits/mplot3d/axes3d.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -813,7 +813,7 @@ def set_proj_type(self, proj_type, focal_length=None):
813813
raise ValueError(f"focal_length = {focal_length} must be "
814814
"greater than 0")
815815
self._focal_length = focal_length
816-
elif proj_type == 'ortho':
816+
else: # 'ortho':
817817
if focal_length not in (None, np.inf):
818818
raise ValueError(f"focal_length = {focal_length} must be "
819819
f"None for proj_type = {proj_type}")

lib/mpl_toolkits/tests/test_axes_grid1.py

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from mpl_toolkits.axes_grid1.anchored_artists import (
1818
AnchoredSizeBar, AnchoredDirectionArrows)
1919
from mpl_toolkits.axes_grid1.axes_divider import (
20-
HBoxDivider, make_axes_area_auto_adjustable)
20+
Divider, HBoxDivider, make_axes_area_auto_adjustable)
2121
from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes
2222
from mpl_toolkits.axes_grid1.inset_locator import (
2323
zoomed_inset_axes, mark_inset, inset_axes, BboxConnectorPatch)
@@ -376,10 +376,9 @@ def test_image_grid():
376376

377377
fig = plt.figure(1, (4, 4))
378378
grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=0.1)
379-
379+
assert grid.get_axes_pad() == (0.1, 0.1)
380380
for i in range(4):
381381
grid[i].imshow(im, interpolation='nearest')
382-
grid[i].set_title('test {0}{0}'.format(i))
383382

384383

385384
def test_gettightbbox():
@@ -492,6 +491,7 @@ def test_grid_axes_lists():
492491
assert_array_equal(grid, grid.axes_all)
493492
assert_array_equal(grid.axes_row, np.transpose(grid.axes_column))
494493
assert_array_equal(grid, np.ravel(grid.axes_row), "row")
494+
assert grid.get_geometry() == (2, 3)
495495
grid = Grid(fig, 111, (2, 3), direction="column")
496496
assert_array_equal(grid, np.ravel(grid.axes_column), "column")
497497

@@ -507,6 +507,29 @@ def test_grid_axes_position(direction):
507507
assert loc[3]._nx == loc[1]._nx and loc[3]._ny == loc[2]._ny
508508

509509

510+
@pytest.mark.parametrize('rect, ngrids, error, message', (
511+
((1, 1), None, TypeError, "Incorrect rect format"),
512+
(111, -1, ValueError, "ngrids must be positive"),
513+
(111, 7, ValueError, "ngrids must be positive"),
514+
))
515+
def test_grid_errors(rect, ngrids, error, message):
516+
fig = plt.figure()
517+
with pytest.raises(error, match=message):
518+
Grid(fig, rect, (2, 3), ngrids=ngrids)
519+
520+
521+
@pytest.mark.parametrize('anchor, error, message', (
522+
(None, TypeError, "anchor must be str"),
523+
("CC", ValueError, "'CC' is not a valid value for anchor"),
524+
((1, 1, 1), TypeError, "anchor must be str"),
525+
))
526+
def test_divider_errors(anchor, error, message):
527+
fig = plt.figure()
528+
with pytest.raises(error, match=message):
529+
Divider(fig, [0, 0, 1, 1], [Size.Fixed(1)], [Size.Fixed(1)],
530+
anchor=anchor)
531+
532+
510533
@check_figures_equal(extensions=["png"])
511534
def test_mark_inset_unstales_viewlim(fig_test, fig_ref):
512535
inset, full = fig_test.subplots(1, 2)

0 commit comments

Comments
 (0)
0