@@ -202,6 +202,29 @@ def get_grid_positions(self, fig, raw=False):
202
202
fig_lefts , fig_rights = (left + cell_ws ).reshape ((- 1 , 2 )).T
203
203
return fig_bottoms , fig_tops , fig_lefts , fig_rights
204
204
205
+ @staticmethod
206
+ def _check_gridspec_exists (figure , nrows , ncols ):
207
+ """
208
+ Check if the figure already has a gridspec with these dimensions...
209
+ """
210
+ gs = None
211
+ for ax in figure .get_axes ():
212
+ if hasattr (ax , 'get_subplotspec' ):
213
+ ggs = ax .get_subplotspec ().get_gridspec ()
214
+ if hasattr (ggs , 'get_topmost_subplotspec' ):
215
+ # This is needed for colorbar gridspec layouts.
216
+ # This is probably OK becase this whole logic tree
217
+ # is for when the user is doing simple things with the
218
+ # add_subplot command. Complicated stuff, the proper
219
+ # gridspec is passed in...
220
+ ggs = ggs .get_topmost_subplotspec ().get_gridspec ()
221
+
222
+ (nrow , ncol ) = ggs .get_geometry ()
223
+ if nrow == nrows and ncol == ncols :
224
+ gs = ggs
225
+ return gs
226
+
227
+
205
228
def __getitem__ (self , key ):
206
229
"""Create and return a `.SubplotSpec` instance."""
207
230
nrows , ncols = self .get_geometry ()
@@ -690,21 +713,11 @@ def _from_subplot_args(figure, args):
690
713
else :
691
714
raise TypeError (f"subplot() takes 1 or 3 positional arguments but "
692
715
f"{ len (args )} were given" )
693
- for ax in figure .get_axes ():
694
- if hasattr (ax , 'get_subplotspec' ):
695
- gs = ax .get_subplotspec ().get_gridspec ()
696
- if hasattr (gs , 'get_topmost_subplotspec' ):
697
- # This is needed for colorbar gridspec layouts.
698
- # This is probably OK becase this whole logic tree
699
- # is for when the user is doing simple things with the
700
- # add_subplot command. Complicated stuff, the proper
701
- # gridspec is passed in...
702
- gs = gs .get_topmost_subplotspec ().get_gridspec ()
703
716
704
- ( nrow , ncol ) = gs . get_geometry ( )
705
- if nrow == rows and ncol == cols :
706
- return gs [ i - 1 : j ]
707
- return GridSpec ( rows , cols , figure = figure ) [i - 1 :j ]
717
+ gs = GridSpec . _check_gridspec_exists ( figure , rows , cols )
718
+ if gs is None :
719
+ gs = GridSpec ( rows , cols , figure = figure )
720
+ return gs [i - 1 :j ]
708
721
709
722
710
723
# num2 is a property only to handle the case where it is None and someone
0 commit comments