@@ -197,6 +197,29 @@ def get_grid_positions(self, fig, raw=False):
197
197
fig_lefts , fig_rights = (left + cell_ws ).reshape ((- 1 , 2 )).T
198
198
return fig_bottoms , fig_tops , fig_lefts , fig_rights
199
199
200
+ @staticmethod
201
+ def _check_gridspec_exists (figure , nrows , ncols ):
202
+ """
203
+ Check if the figure already has a gridspec with these dimensions...
204
+ """
205
+ gs = None
206
+ for ax in figure .get_axes ():
207
+ if hasattr (ax , 'get_subplotspec' ):
208
+ ggs = ax .get_subplotspec ().get_gridspec ()
209
+ if hasattr (ggs , 'get_topmost_subplotspec' ):
210
+ # This is needed for colorbar gridspec layouts.
211
+ # This is probably OK becase this whole logic tree
212
+ # is for when the user is doing simple things with the
213
+ # add_subplot command. Complicated stuff, the proper
214
+ # gridspec is passed in...
215
+ ggs = ggs .get_topmost_subplotspec ().get_gridspec ()
216
+
217
+ (nrow , ncol ) = ggs .get_geometry ()
218
+ if nrow == nrows and ncol == ncols :
219
+ gs = ggs
220
+ return gs
221
+
222
+
200
223
def __getitem__ (self , key ):
201
224
"""Create and return a `.SubplotSpec` instance."""
202
225
nrows , ncols = self .get_geometry ()
@@ -558,21 +581,11 @@ def _from_subplot_args(figure, args):
558
581
else :
559
582
raise TypeError (f"subplot() takes 1 or 3 positional arguments but "
560
583
f"{ len (args )} were given" )
561
- for ax in figure .get_axes ():
562
- if hasattr (ax , 'get_subplotspec' ):
563
- gs = ax .get_subplotspec ().get_gridspec ()
564
- if hasattr (gs , 'get_topmost_subplotspec' ):
565
- # This is needed for colorbar gridspec layouts.
566
- # This is probably OK becase this whole logic tree
567
- # is for when the user is doing simple things with the
568
- # add_subplot command. Complicated stuff, the proper
569
- # gridspec is passed in...
570
- gs = gs .get_topmost_subplotspec ().get_gridspec ()
571
584
572
- ( nrow , ncol ) = gs . get_geometry ( )
573
- if nrow == rows and ncol == cols :
574
- return gs [ ii - 1 : jj ]
575
- return GridSpec ( rows , cols , figure = figure ) [ii - 1 :jj ]
585
+ gs = GridSpec . _check_gridspec_exists ( figure , rows , cols )
586
+ if gs is None :
587
+ gs = GridSpec ( rows , cols , figure = figure )
588
+ return gs [ii - 1 :jj ]
576
589
577
590
578
591
# num2 is a property only to handle the case where it is None and someone
0 commit comments