@@ -1072,10 +1072,10 @@ def cla():
10721072@docstring .dedent_interpd
10731073def subplot (* args , ** kwargs ):
10741074 """
1075- Add a subplot to the current figure.
1075+ Add an Axes to the current figure or retrieve an existing Axes .
10761076
1077- Wrapper of `.Figure.add_subplot` with a difference in
1078- behavior explained in the notes section.
1077+ This is a wrapper of `.Figure.add_subplot` which provides additional
1078+ behavior when working with the implicit API (see the notes section) .
10791079
10801080 Call signatures::
10811081
@@ -1142,8 +1142,8 @@ def subplot(*args, **kwargs):
11421142
11431143 Notes
11441144 -----
1145- Creating a subplot will delete any pre-existing subplot that overlaps
1146- with it beyond sharing a boundary::
1145+ Creating a new Axes will delete any pre-existing Axes that
1146+ overlaps with it beyond sharing a boundary::
11471147
11481148 import matplotlib.pyplot as plt
11491149 # plot a line, implicitly creating a subplot(111)
@@ -1156,18 +1156,19 @@ def subplot(*args, **kwargs):
11561156 If you do not want this behavior, use the `.Figure.add_subplot` method
11571157 or the `.pyplot.axes` function instead.
11581158
1159- If the figure already has a subplot with key (*args*,
1160- *kwargs*) then it will simply make that subplot current and
1161- return it. This behavior is deprecated. Meanwhile, if you do
1162- not want this behavior (i.e., you want to force the creation of a
1163- new subplot), you must use a unique set of args and kwargs. The axes
1164- *label* attribute has been exposed for this purpose: if you want
1165- two subplots that are otherwise identical to be added to the figure,
1166- make sure you give them unique labels.
1159+ If no *kwargs* are passed and there exists an Axes in the location
1160+ specified by *args* then that Axes will be returned rather than a new
1161+ Axes being created.
11671162
1168- In rare circumstances, `.Figure.add_subplot` may be called with a single
1169- argument, a subplot axes instance already created in the
1170- present figure but not in the figure's list of axes.
1163+ If *kwargs* are passed and there exists an Axes in the location
1164+ specified by *args*, the projection type is the same, and the
1165+ *kwargs* match with the existing Axes, then the existing Axes is
1166+ returned. Otherwise a new Axes is created with the specified
1167+ parameters. We save a reference to the *kwargs* which we us
1168+ for this comparison. If any of the values in *kwargs* are
1169+ mutable we will not detect the case where they are mutated.
1170+ In these cases we suggest using `.Figure.add_subplot` and the
1171+ explicit Axes API rather than the implicit pyplot API.
11711172
11721173 See Also
11731174 --------
@@ -1183,10 +1184,10 @@ def subplot(*args, **kwargs):
11831184 plt.subplot(221)
11841185
11851186 # equivalent but more general
1186- ax1= plt.subplot(2, 2, 1)
1187+ ax1 = plt.subplot(2, 2, 1)
11871188
11881189 # add a subplot with no frame
1189- ax2= plt.subplot(222, frameon=False)
1190+ ax2 = plt.subplot(222, frameon=False)
11901191
11911192 # add a polar subplot
11921193 plt.subplot(223, projection='polar')
@@ -1199,7 +1200,27 @@ def subplot(*args, **kwargs):
11991200
12001201 # add ax2 to the figure again
12011202 plt.subplot(ax2)
1203+
1204+ # make the first axes "current" again
1205+ plt.subplot(221)
1206+
12021207 """
1208+ unset = object ()
1209+ # sort out if the user passed us either polar or projection
1210+ # in principle we need to handle if *axes_class* is passed, but
1211+ # we will leave that validation to down stream code. Here we will
1212+ # only normalize `polar=True` vs `projection='polar'` so we can decide
1213+ # if we should create a new Axes or return the existing one
1214+ projection = kwargs .get ('projection' , unset )
1215+ polar = kwargs .pop ('polar' , unset )
1216+ if polar is not unset and polar :
1217+ # if we got mixed messages from the user, raise
1218+ if projection is not unset and projection != 'polar' :
1219+ raise ValueError (
1220+ f"polar={ polar } , yet projection={ projection !r} . "
1221+ "Only one of these arguments should be supplied."
1222+ )
1223+ kwargs ['projection' ] = projection = 'polar'
12031224
12041225 # if subplot called without arguments, create subplot(1, 1, 1)
12051226 if len (args ) == 0 :
@@ -1224,14 +1245,32 @@ def subplot(*args, **kwargs):
12241245
12251246 # First, search for an existing subplot with a matching spec.
12261247 key = SubplotSpec ._from_subplot_args (fig , args )
1227- ax = next (
1228- (ax for ax in fig .axes
1229- if hasattr (ax , 'get_subplotspec' ) and ax .get_subplotspec () == key ),
1230- None )
12311248
1232- # If no existing axes match, then create a new one.
1233- if ax is None :
1249+ for ax in fig .axes :
1250+ if hasattr (ax , 'get_subplotspec' ) and ax .get_subplotspec () == key :
1251+ # if we found an axes at the right position sort out if we
1252+ # should re-use it
1253+
1254+ # sort out what projection class and kwargs would be
1255+ # created so we can tell if we should re-use an existing
1256+ # one
1257+ p_class , pkw = fig ._process_projection_requirements (
1258+ * args , ** kwargs
1259+ )
1260+ # if no projection or projection kwargs were passed,
1261+ # return the axes we found with out checking anything
1262+ # else.
1263+ if projection is unset and pkw == {}:
1264+ break
1265+ # otherwise, only reuse if the axes class and kwargs are
1266+ # identical
1267+ elif getattr (ax , '_projection_init' , ()) == (p_class , pkw ):
1268+ break
1269+ else :
1270+ # in the case where we have exhausted the know Axes, make a
1271+ # new one!
12341272 ax = fig .add_subplot (* args , ** kwargs )
1273+
12351274 fig .sca (ax )
12361275
12371276 bbox = ax .bbox
0 commit comments