Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b32de5c

Browse files
authored
Merge pull request #27972 from anntzer/gn
Fix ngrids support in axes_grid.Grid().
2 parents 56ecc15 + 62805c0 commit b32de5c

File tree

3 files changed

+51
-33
lines changed

3 files changed

+51
-33
lines changed
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
``axes_grid.Grid.ngrids``
2+
~~~~~~~~~~~~~~~~~~~~~~~~~
3+
This attribute has been deprecated and renamed ``n_axes``, consistently with
4+
the new name of the `~.axes_grid.Grid` constructor parameter that allows
5+
setting the actual number of axes in the grid (the old parameter, ``ngrids``,
6+
did not actually work since Matplotlib 3.3).
7+
8+
The same change has been made in ``axes_grid.ImageGrid``.

lib/mpl_toolkits/axes_grid1/axes_grid.py

Lines changed: 32 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -51,16 +51,17 @@ class Grid:
5151
in the usage pattern ``grid.axes_row[row][col]``.
5252
axes_llc : Axes
5353
The Axes in the lower left corner.
54-
ngrids : int
54+
n_axes : int
5555
Number of Axes in the grid.
5656
"""
5757

5858
_defaultAxesClass = Axes
5959

60+
@_api.rename_parameter("3.11", "ngrids", "n_axes")
6061
def __init__(self, fig,
6162
rect,
6263
nrows_ncols,
63-
ngrids=None,
64+
n_axes=None,
6465
direction="row",
6566
axes_pad=0.02,
6667
*,
@@ -83,8 +84,8 @@ def __init__(self, fig,
8384
``121``), or as a `~.SubplotSpec`.
8485
nrows_ncols : (int, int)
8586
Number of rows and columns in the grid.
86-
ngrids : int or None, default: None
87-
If not None, only the first *ngrids* axes in the grid are created.
87+
n_axes : int or None, default: None
88+
If not None, only the first *n_axes* axes in the grid are created.
8889
direction : {"row", "column"}, default: "row"
8990
Whether axes are created in row-major ("row by row") or
9091
column-major order ("column by column"). This also affects the
@@ -116,14 +117,12 @@ def __init__(self, fig,
116117
"""
117118
self._nrows, self._ncols = nrows_ncols
118119

119-
if ngrids is None:
120-
ngrids = self._nrows * self._ncols
120+
if n_axes is None:
121+
n_axes = self._nrows * self._ncols
121122
else:
122-
if not 0 < ngrids <= self._nrows * self._ncols:
123+
if not 0 < n_axes <= self._nrows * self._ncols:
123124
raise ValueError(
124-
"ngrids must be positive and not larger than nrows*ncols")
125-
126-
self.ngrids = ngrids
125+
"n_axes must be positive and not larger than nrows*ncols")
127126

128127
self._horiz_pad_size, self._vert_pad_size = map(
129128
Size.Fixed, np.broadcast_to(axes_pad, 2))
@@ -150,7 +149,7 @@ def __init__(self, fig,
150149
rect = self._divider.get_position()
151150

152151
axes_array = np.full((self._nrows, self._ncols), None, dtype=object)
153-
for i in range(self.ngrids):
152+
for i in range(n_axes):
154153
col, row = self._get_col_row(i)
155154
if share_all:
156155
sharex = sharey = axes_array[0, 0]
@@ -160,9 +159,9 @@ def __init__(self, fig,
160159
axes_array[row, col] = axes_class(
161160
fig, rect, sharex=sharex, sharey=sharey)
162161
self.axes_all = axes_array.ravel(
163-
order="C" if self._direction == "row" else "F").tolist()
164-
self.axes_column = axes_array.T.tolist()
165-
self.axes_row = axes_array.tolist()
162+
order="C" if self._direction == "row" else "F").tolist()[:n_axes]
163+
self.axes_row = [[ax for ax in row if ax] for row in axes_array]
164+
self.axes_column = [[ax for ax in col if ax] for col in axes_array.T]
166165
self.axes_llc = self.axes_column[0][-1]
167166

168167
self._init_locators()
@@ -177,7 +176,7 @@ def _init_locators(self):
177176
[Size.Scaled(1), self._horiz_pad_size] * (self._ncols-1) + [Size.Scaled(1)])
178177
self._divider.set_vertical(
179178
[Size.Scaled(1), self._vert_pad_size] * (self._nrows-1) + [Size.Scaled(1)])
180-
for i in range(self.ngrids):
179+
for i in range(self.n_axes):
181180
col, row = self._get_col_row(i)
182181
self.axes_all[i].set_axes_locator(
183182
self._divider.new_locator(nx=2 * col, ny=2 * (self._nrows - 1 - row)))
@@ -190,6 +189,9 @@ def _get_col_row(self, n):
190189

191190
return col, row
192191

192+
n_axes = property(lambda self: len(self.axes_all))
193+
ngrids = _api.deprecated(property(lambda self: len(self.axes_all)))
194+
193195
# Good to propagate __len__ if we have __getitem__
194196
def __len__(self):
195197
return len(self.axes_all)
@@ -254,7 +256,10 @@ def set_label_mode(self, mode):
254256
if mode == "keep":
255257
return
256258
for i, j in np.ndindex(self._nrows, self._ncols):
257-
ax = self.axes_row[i][j]
259+
try:
260+
ax = self.axes_row[i][j]
261+
except IndexError:
262+
continue
258263
if isinstance(ax.axis, MethodType):
259264
bottom_axis = SimpleAxisArtist(ax.xaxis, 1, ax.spines["bottom"])
260265
left_axis = SimpleAxisArtist(ax.yaxis, 1, ax.spines["left"])
@@ -293,7 +298,7 @@ class ImageGrid(Grid):
293298
def __init__(self, fig,
294299
rect,
295300
nrows_ncols,
296-
ngrids=None,
301+
n_axes=None,
297302
direction="row",
298303
axes_pad=0.02,
299304
*,
@@ -317,8 +322,8 @@ def __init__(self, fig,
317322
as a three-digit subplot position code (e.g., "121").
318323
nrows_ncols : (int, int)
319324
Number of rows and columns in the grid.
320-
ngrids : int or None, default: None
321-
If not None, only the first *ngrids* axes in the grid are created.
325+
n_axes : int or None, default: None
326+
If not None, only the first *n_axes* axes in the grid are created.
322327
direction : {"row", "column"}, default: "row"
323328
Whether axes are created in row-major ("row by row") or
324329
column-major order ("column by column"). This also affects the
@@ -372,7 +377,7 @@ def __init__(self, fig,
372377
# The colorbar axes are created in _init_locators().
373378

374379
super().__init__(
375-
fig, rect, nrows_ncols, ngrids,
380+
fig, rect, nrows_ncols, n_axes,
376381
direction=direction, axes_pad=axes_pad,
377382
share_all=share_all, share_x=True, share_y=True, aspect=aspect,
378383
label_mode=label_mode, axes_class=axes_class)
@@ -408,7 +413,7 @@ def _init_locators(self):
408413
_cbaraxes_class_factory(self._defaultAxesClass)(
409414
self.axes_all[0].get_figure(root=False), self._divider.get_position(),
410415
orientation=self._colorbar_location)
411-
for _ in range(self.ngrids)]
416+
for _ in range(self.n_axes)]
412417

413418
cb_mode = self._colorbar_mode
414419
cb_location = self._colorbar_location
@@ -429,7 +434,7 @@ def _init_locators(self):
429434
v.append(Size.from_any(self._colorbar_size, sz))
430435
v.append(Size.from_any(self._colorbar_pad, sz))
431436
locator = self._divider.new_locator(nx=0, nx1=-1, ny=0)
432-
for i in range(self.ngrids):
437+
for i in range(self.n_axes):
433438
self.cbar_axes[i].set_visible(False)
434439
self.cbar_axes[0].set_axes_locator(locator)
435440
self.cbar_axes[0].set_visible(True)
@@ -490,7 +495,7 @@ def _init_locators(self):
490495
v_cb_pos.append(len(v))
491496
v.append(Size.from_any(self._colorbar_size, sz))
492497

493-
for i in range(self.ngrids):
498+
for i in range(self.n_axes):
494499
col, row = self._get_col_row(i)
495500
locator = self._divider.new_locator(nx=h_ax_pos[col],
496501
ny=v_ax_pos[self._nrows-1-row])
@@ -530,12 +535,12 @@ def _init_locators(self):
530535
v.append(Size.from_any(self._colorbar_size, sz))
531536
locator = self._divider.new_locator(nx=0, nx1=-1, ny=-2)
532537
if cb_location in ("right", "top"):
533-
for i in range(self.ngrids):
538+
for i in range(self.n_axes):
534539
self.cbar_axes[i].set_visible(False)
535540
self.cbar_axes[0].set_axes_locator(locator)
536541
self.cbar_axes[0].set_visible(True)
537542
elif cb_mode == "each":
538-
for i in range(self.ngrids):
543+
for i in range(self.n_axes):
539544
self.cbar_axes[i].set_visible(True)
540545
elif cb_mode == "edge":
541546
if cb_location in ("right", "left"):
@@ -544,10 +549,10 @@ def _init_locators(self):
544549
count = self._ncols
545550
for i in range(count):
546551
self.cbar_axes[i].set_visible(True)
547-
for j in range(i + 1, self.ngrids):
552+
for j in range(i + 1, self.n_axes):
548553
self.cbar_axes[j].set_visible(False)
549554
else:
550-
for i in range(self.ngrids):
555+
for i in range(self.n_axes):
551556
self.cbar_axes[i].set_visible(False)
552557
self.cbar_axes[i].set_position([1., 1., 0.001, 0.001],
553558
which="active")

lib/mpl_toolkits/axes_grid1/tests/test_axes_grid1.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,6 @@ def test_axesgrid_colorbar_log_smoketest():
104104
fig = plt.figure()
105105
grid = AxesGrid(fig, 111, # modified to be only subplot
106106
nrows_ncols=(1, 1),
107-
ngrids=1,
108107
label_mode="L",
109108
cbar_location="top",
110109
cbar_mode="single",
@@ -638,15 +637,15 @@ def test_grid_axes_position(direction):
638637
assert loc[3].args[1] == loc[2].args[1]
639638

640639

641-
@pytest.mark.parametrize('rect, ngrids, error, message', (
640+
@pytest.mark.parametrize('rect, n_axes, error, message', (
642641
((1, 1), None, TypeError, "Incorrect rect format"),
643-
(111, -1, ValueError, "ngrids must be positive"),
644-
(111, 7, ValueError, "ngrids must be positive"),
642+
(111, -1, ValueError, "n_axes must be positive"),
643+
(111, 7, ValueError, "n_axes must be positive"),
645644
))
646-
def test_grid_errors(rect, ngrids, error, message):
645+
def test_grid_errors(rect, n_axes, error, message):
647646
fig = plt.figure()
648647
with pytest.raises(error, match=message):
649-
Grid(fig, rect, (2, 3), ngrids=ngrids)
648+
Grid(fig, rect, (2, 3), n_axes=n_axes)
650649

651650

652651
@pytest.mark.parametrize('anchor, error, message', (
@@ -780,3 +779,9 @@ def test_anchored_locator_base_call():
780779
def test_grid_with_axes_class_not_overriding_axis():
781780
Grid(plt.figure(), 111, (2, 2), axes_class=mpl.axes.Axes)
782781
RGBAxes(plt.figure(), 111, axes_class=mpl.axes.Axes)
782+
783+
784+
def test_grid_n_axes():
785+
fig = plt.figure()
786+
grid = Grid(fig, 111, (3, 3), n_axes=5)
787+
assert len(fig.axes) == grid.n_axes == 5

0 commit comments

Comments
 (0)