@@ -1221,13 +1221,13 @@ def colorbar(
12211221
12221222 The *shrink* kwarg provides a simple way to scale the colorbar with
12231223 respect to the axes. Note that if *cax* is specified, it determines the
1224- size of the colorbar and *shrink* and *aspect* kwargs are ignored.
1224+ size of the colorbar, and *shrink* and *aspect* are ignored.
12251225
12261226 For more precise control, you can manually specify the positions of the
12271227 axes objects in which the mappable and the colorbar are drawn. In this
12281228 case, do not use any of the axes properties kwargs.
12291229
1230- It is known that some vector graphics viewers (svg and pdf) renders
1230+ It is known that some vector graphics viewers (svg and pdf) render
12311231 white gaps between segments of the colorbar. This is due to bugs in
12321232 the viewers, not Matplotlib. As a workaround, the colorbar can be
12331233 rendered with overlapping segments::
@@ -1247,37 +1247,30 @@ def colorbar(
12471247 if (self .get_layout_engine () is not None and
12481248 not self .get_layout_engine ().colorbar_gridspec ):
12491249 use_gridspec = False
1250- # Store the value of gca so that we can set it back later on.
12511250 if cax is None :
1251+ current_ax = self .gca ()
12521252 if ax is None :
12531253 _api .warn_deprecated ("3.6" , message = (
12541254 'Unable to determine Axes to steal space for Colorbar. '
12551255 'Using gca(), but will raise in the future. '
12561256 'Either provide the *cax* argument to use as the Axes for '
12571257 'the Colorbar, provide the *ax* argument to steal space '
12581258 'from it, or add *mappable* to an Axes.' ))
1259- ax = self .gca ()
1260- current_ax = self .gca ()
1261- userax = False
1259+ ax = current_ax
12621260 if (use_gridspec
12631261 and isinstance (ax , mpl .axes ._base ._AxesBase )
12641262 and ax .get_subplotspec ()):
12651263 cax , kwargs = cbar .make_axes_gridspec (ax , ** kwargs )
12661264 else :
12671265 cax , kwargs = cbar .make_axes (ax , ** kwargs )
1266+ # make_axes calls add_{axes,subplot} which changes gca; undo that.
1267+ self .sca (current_ax )
12681268 cax .grid (visible = False , which = 'both' , axis = 'both' )
1269- else :
1270- userax = True
12711269
1272- # need to remove kws that cannot be passed to Colorbar
1273- NON_COLORBAR_KEYS = ['fraction' , 'pad' , 'shrink' , 'aspect' , 'anchor' ,
1274- 'panchor' ]
1275- cb_kw = {k : v for k , v in kwargs .items () if k not in NON_COLORBAR_KEYS }
1276-
1277- cb = cbar .Colorbar (cax , mappable , ** cb_kw )
1278-
1279- if not userax :
1280- self .sca (current_ax )
1270+ NON_COLORBAR_KEYS = [ # remove kws that cannot be passed to Colorbar
1271+ 'fraction' , 'pad' , 'shrink' , 'aspect' , 'anchor' , 'panchor' ]
1272+ cb = cbar .Colorbar (cax , mappable , ** {
1273+ k : v for k , v in kwargs .items () if k not in NON_COLORBAR_KEYS })
12811274 self .stale = True
12821275 return cb
12831276
0 commit comments