@@ -355,6 +355,74 @@ def legend(self, *args, **kwargs):
355355 def _remove_legend (self , legend ):
356356 self .legend_ = None
357357
358+ @_docstring .interpd
359+ def colorbar (self , mappable = None , * , use_gridspec = True , ** kwargs ):
360+ """
361+ Add a colorbar next to the Axes.
362+
363+ Parameters
364+ ----------
365+ mappable : `matplotlib.colorizer.ColorizingArtist`, optional
366+ The `.ColorizingArtist` (i.e., `.AxesImage`, `.ContourSet`, etc.) described
367+ by this colorbar.
368+
369+ If not given, the mappable is inferred from the Axes. If there is exactly
370+ one image or collection, this is used as mappable. Otherwise, an error is
371+ raised and you must specify the mappable explicitly.
372+
373+ Note that one can create a `.colorizer.ColorizingArtist` "on-the-fly"
374+ to generate colorbars not attached to a previously drawn artist, e.g.
375+
376+ ::
377+
378+ cr = colorizer.Colorizer(norm=norm, cmap=cmap)
379+ ax.colorbar(colorizer.ColorizingArtist(cr))
380+
381+ Returns
382+ -------
383+ colorbar : `~matplotlib.colorbar.Colorbar`
384+
385+ Other Parameters
386+ ----------------
387+ use_gridspec : bool, optional
388+ If *ax* is positioned with a subplotspec and *use_gridspec*
389+ is ``True``, then *cax* is also positioned with a subplotspec.
390+
391+ %(_make_axes_kw_doc)s
392+ %(_colormap_kw_doc)s
393+
394+ Notes
395+ -----
396+ This method is a convenience shortcut if you want to place a colorbar
397+ right next to an Axes. ``ax.colorbar(mappable)`` is equivalent to
398+ ``fig.colorbar(mappable, ax=ax)``. In particular, if you have exactly one
399+ mappable in the Axes, the general ::
400+
401+ im = ax.imshow(data)
402+ fig.colorbar(im, ax=ax)
403+
404+ can be written more concisely as ::
405+
406+ ax.imshow(data)
407+ ax.colorbar()
408+
409+ Use `.Figure.colorbar` if you need more control on placing the colorbar.
410+ """
411+ if mappable is None :
412+ # autodetect the mappable
413+ colormapped_artists = [* self .images , * self .collections ]
414+ if len (colormapped_artists ) != 1 :
415+ raise RuntimeError (
416+ "Axes.colormap() requires exactly one colormapped Artist in the "
417+ f"Axes, but found { len (colormapped_artists )} . In ambiguous cases, "
418+ "please specify the mappable for the colorbar explicitly."
419+ )
420+ mappable = colormapped_artists [0 ]
421+
422+ return self .figure .colorbar (
423+ mappable , ax = self , use_gridspec = use_gridspec , ** kwargs
424+ )
425+
358426 def inset_axes (self , bounds , * , transform = None , zorder = 5 , ** kwargs ):
359427 """
360428 Add a child inset Axes to this existing Axes.
0 commit comments