figure.py 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888
  1. """
  2. `matplotlib.figure` implements the following classes:
  3. `Figure`
  4. Top level `~matplotlib.artist.Artist`, which holds all plot elements.
  5. `SubplotParams`
  6. Control the default spacing between subplots.
  7. """
  8. import inspect
  9. import logging
  10. from numbers import Integral
  11. import numpy as np
  12. import matplotlib as mpl
  13. from matplotlib import docstring, projections
  14. from matplotlib import __version__ as _mpl_version
  15. import matplotlib.artist as martist
  16. from matplotlib.artist import Artist, allow_rasterization
  17. from matplotlib.backend_bases import (
  18. FigureCanvasBase, NonGuiException, MouseButton)
  19. import matplotlib.cbook as cbook
  20. import matplotlib.colorbar as cbar
  21. import matplotlib.image as mimage
  22. from matplotlib.axes import Axes, SubplotBase, subplot_class_factory
  23. from matplotlib.blocking_input import BlockingMouseInput, BlockingKeyMouseInput
  24. from matplotlib.gridspec import GridSpec, SubplotSpec # noqa: F401
  25. import matplotlib.legend as mlegend
  26. from matplotlib.patches import Rectangle
  27. from matplotlib.text import Text
  28. from matplotlib.transforms import (Affine2D, Bbox, BboxTransformTo,
  29. TransformedBbox)
  30. import matplotlib._layoutbox as layoutbox
  31. _log = logging.getLogger(__name__)
  32. def _stale_figure_callback(self, val):
  33. if self.figure:
  34. self.figure.stale = val
  35. class _AxesStack(cbook.Stack):
  36. """
  37. Specialization of `.Stack`, to handle all tracking of `~.axes.Axes` in a
  38. `.Figure`.
  39. This stack stores ``key, (ind, axes)`` pairs, where:
  40. * **key** is a hash of the args and kwargs used in generating the Axes.
  41. * **ind** is a serial index tracking the order in which axes were added.
  42. AxesStack is a callable; calling it returns the current axes.
  43. The `current_key_axes` method returns the current key and associated axes.
  44. """
  45. def __init__(self):
  46. super().__init__()
  47. self._ind = 0
  48. def as_list(self):
  49. """
  50. Return a list of the Axes instances that have been added to the figure.
  51. """
  52. ia_list = [a for k, a in self._elements]
  53. ia_list.sort()
  54. return [a for i, a in ia_list]
  55. def get(self, key):
  56. """
  57. Return the Axes instance that was added with *key*.
  58. If it is not present, return *None*.
  59. """
  60. item = dict(self._elements).get(key)
  61. if item is None:
  62. return None
  63. cbook.warn_deprecated(
  64. "2.1",
  65. message="Adding an axes using the same arguments as a previous "
  66. "axes currently reuses the earlier instance. In a future "
  67. "version, a new instance will always be created and returned. "
  68. "Meanwhile, this warning can be suppressed, and the future "
  69. "behavior ensured, by passing a unique label to each axes "
  70. "instance.")
  71. return item[1]
  72. def _entry_from_axes(self, e):
  73. ind, k = {a: (ind, k) for k, (ind, a) in self._elements}[e]
  74. return (k, (ind, e))
  75. def remove(self, a):
  76. """Remove the axes from the stack."""
  77. super().remove(self._entry_from_axes(a))
  78. def bubble(self, a):
  79. """
  80. Move the given axes, which must already exist in the
  81. stack, to the top.
  82. """
  83. return super().bubble(self._entry_from_axes(a))
  84. def add(self, key, a):
  85. """
  86. Add Axes *a*, with key *key*, to the stack, and return the stack.
  87. If *key* is unhashable, replace it by a unique, arbitrary object.
  88. If *a* is already on the stack, don't add it again, but
  89. return *None*.
  90. """
  91. # All the error checking may be unnecessary; but this method
  92. # is called so seldom that the overhead is negligible.
  93. cbook._check_isinstance(Axes, a=a)
  94. try:
  95. hash(key)
  96. except TypeError:
  97. key = object()
  98. a_existing = self.get(key)
  99. if a_existing is not None:
  100. super().remove((key, a_existing))
  101. cbook._warn_external(
  102. "key {!r} already existed; Axes is being replaced".format(key))
  103. # I don't think the above should ever happen.
  104. if a in self:
  105. return None
  106. self._ind += 1
  107. return super().push((key, (self._ind, a)))
  108. def current_key_axes(self):
  109. """
  110. Return a tuple of ``(key, axes)`` for the active axes.
  111. If no axes exists on the stack, then returns ``(None, None)``.
  112. """
  113. if not len(self._elements):
  114. return self._default, self._default
  115. else:
  116. key, (index, axes) = self._elements[self._pos]
  117. return key, axes
  118. def __call__(self):
  119. return self.current_key_axes()[1]
  120. def __contains__(self, a):
  121. return a in self.as_list()
  122. @cbook.deprecated("3.2")
  123. class AxesStack(_AxesStack):
  124. pass
  125. class SubplotParams:
  126. """
  127. A class to hold the parameters for a subplot.
  128. """
  129. def __init__(self, left=None, bottom=None, right=None, top=None,
  130. wspace=None, hspace=None):
  131. """
  132. Defaults are given by :rc:`figure.subplot.[name]`.
  133. Parameters
  134. ----------
  135. left : float
  136. The position of the left edge of the subplots,
  137. as a fraction of the figure width.
  138. right : float
  139. The position of the right edge of the subplots,
  140. as a fraction of the figure width.
  141. bottom : float
  142. The position of the bottom edge of the subplots,
  143. as a fraction of the figure height.
  144. top : float
  145. The position of the top edge of the subplots,
  146. as a fraction of the figure height.
  147. wspace : float
  148. The width of the padding between subplots,
  149. as a fraction of the average axes width.
  150. hspace : float
  151. The height of the padding between subplots,
  152. as a fraction of the average axes height.
  153. """
  154. self.validate = True
  155. for key in ["left", "bottom", "right", "top", "wspace", "hspace"]:
  156. setattr(self, key, mpl.rcParams[f"figure.subplot.{key}"])
  157. self.update(left, bottom, right, top, wspace, hspace)
  158. def update(self, left=None, bottom=None, right=None, top=None,
  159. wspace=None, hspace=None):
  160. """
  161. Update the dimensions of the passed parameters. *None* means unchanged.
  162. """
  163. if self.validate:
  164. if ((left if left is not None else self.left)
  165. >= (right if right is not None else self.right)):
  166. raise ValueError('left cannot be >= right')
  167. if ((bottom if bottom is not None else self.bottom)
  168. >= (top if top is not None else self.top)):
  169. raise ValueError('bottom cannot be >= top')
  170. if left is not None:
  171. self.left = left
  172. if right is not None:
  173. self.right = right
  174. if bottom is not None:
  175. self.bottom = bottom
  176. if top is not None:
  177. self.top = top
  178. if wspace is not None:
  179. self.wspace = wspace
  180. if hspace is not None:
  181. self.hspace = hspace
  182. class Figure(Artist):
  183. """
  184. The top level container for all the plot elements.
  185. The Figure instance supports callbacks through a *callbacks* attribute
  186. which is a `.CallbackRegistry` instance. The events you can connect to
  187. are 'dpi_changed', and the callback will be called with ``func(fig)`` where
  188. fig is the `Figure` instance.
  189. Attributes
  190. ----------
  191. patch
  192. The `.Rectangle` instance representing the figure background patch.
  193. suppressComposite
  194. For multiple figure images, the figure will make composite images
  195. depending on the renderer option_image_nocomposite function. If
  196. *suppressComposite* is a boolean, this will override the renderer.
  197. """
  198. def __str__(self):
  199. return "Figure(%gx%g)" % tuple(self.bbox.size)
  200. def __repr__(self):
  201. return "<{clsname} size {h:g}x{w:g} with {naxes} Axes>".format(
  202. clsname=self.__class__.__name__,
  203. h=self.bbox.size[0], w=self.bbox.size[1],
  204. naxes=len(self.axes),
  205. )
  206. def __init__(self,
  207. figsize=None,
  208. dpi=None,
  209. facecolor=None,
  210. edgecolor=None,
  211. linewidth=0.0,
  212. frameon=None,
  213. subplotpars=None, # rc figure.subplot.*
  214. tight_layout=None, # rc figure.autolayout
  215. constrained_layout=None, # rc figure.constrained_layout.use
  216. ):
  217. """
  218. Parameters
  219. ----------
  220. figsize : 2-tuple of floats, default: :rc:`figure.figsize`
  221. Figure dimension ``(width, height)`` in inches.
  222. dpi : float, default: :rc:`figure.dpi`
  223. Dots per inch.
  224. facecolor : default: :rc:`figure.facecolor`
  225. The figure patch facecolor.
  226. edgecolor : default: :rc:`figure.edgecolor`
  227. The figure patch edge color.
  228. linewidth : float
  229. The linewidth of the frame (i.e. the edge linewidth of the figure
  230. patch).
  231. frameon : bool, default: :rc:`figure.frameon`
  232. If ``False``, suppress drawing the figure background patch.
  233. subplotpars : `SubplotParams`
  234. Subplot parameters. If not given, the default subplot
  235. parameters :rc:`figure.subplot.*` are used.
  236. tight_layout : bool or dict, default: :rc:`figure.autolayout`
  237. If ``False`` use *subplotpars*. If ``True`` adjust subplot
  238. parameters using `.tight_layout` with default padding.
  239. When providing a dict containing the keys ``pad``, ``w_pad``,
  240. ``h_pad``, and ``rect``, the default `.tight_layout` paddings
  241. will be overridden.
  242. constrained_layout : bool, default: :rc:`figure.constrained_layout.use`
  243. If ``True`` use constrained layout to adjust positioning of plot
  244. elements. Like ``tight_layout``, but designed to be more
  245. flexible. See
  246. :doc:`/tutorials/intermediate/constrainedlayout_guide`
  247. for examples. (Note: does not work with `add_subplot` or
  248. `~.pyplot.subplot2grid`.)
  249. """
  250. super().__init__()
  251. # remove the non-figure artist _axes property
  252. # as it makes no sense for a figure to be _in_ an axes
  253. # this is used by the property methods in the artist base class
  254. # which are over-ridden in this class
  255. del self._axes
  256. self.callbacks = cbook.CallbackRegistry()
  257. if figsize is None:
  258. figsize = mpl.rcParams['figure.figsize']
  259. if dpi is None:
  260. dpi = mpl.rcParams['figure.dpi']
  261. if facecolor is None:
  262. facecolor = mpl.rcParams['figure.facecolor']
  263. if edgecolor is None:
  264. edgecolor = mpl.rcParams['figure.edgecolor']
  265. if frameon is None:
  266. frameon = mpl.rcParams['figure.frameon']
  267. if not np.isfinite(figsize).all() or (np.array(figsize) < 0).any():
  268. raise ValueError('figure size must be positive finite not '
  269. f'{figsize}')
  270. self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
  271. self.dpi_scale_trans = Affine2D().scale(dpi)
  272. # do not use property as it will trigger
  273. self._dpi = dpi
  274. self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)
  275. self.transFigure = BboxTransformTo(self.bbox)
  276. self.patch = Rectangle(
  277. xy=(0, 0), width=1, height=1, visible=frameon,
  278. facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth,
  279. # Don't let the figure patch influence bbox calculation.
  280. in_layout=False)
  281. self._set_artist_props(self.patch)
  282. self.patch.set_antialiased(False)
  283. FigureCanvasBase(self) # Set self.canvas.
  284. self._suptitle = None
  285. if subplotpars is None:
  286. subplotpars = SubplotParams()
  287. self.subplotpars = subplotpars
  288. # constrained_layout:
  289. self._layoutbox = None
  290. # set in set_constrained_layout_pads()
  291. self.set_constrained_layout(constrained_layout)
  292. self.set_tight_layout(tight_layout)
  293. self._axstack = _AxesStack() # track all figure axes and current axes
  294. self.clf()
  295. self._cachedRenderer = None
  296. # groupers to keep track of x and y labels we want to align.
  297. # see self.align_xlabels and self.align_ylabels and
  298. # axis._get_tick_boxes_siblings
  299. self._align_xlabel_grp = cbook.Grouper()
  300. self._align_ylabel_grp = cbook.Grouper()
  301. # list of child gridspecs for this figure
  302. self._gridspecs = []
  303. # TODO: I'd like to dynamically add the _repr_html_ method
  304. # to the figure in the right context, but then IPython doesn't
  305. # use it, for some reason.
  306. def _repr_html_(self):
  307. # We can't use "isinstance" here, because then we'd end up importing
  308. # webagg unconditionally.
  309. if 'WebAgg' in type(self.canvas).__name__:
  310. from matplotlib.backends import backend_webagg
  311. return backend_webagg.ipython_inline_display(self)
  312. def show(self, warn=True):
  313. """
  314. If using a GUI backend with pyplot, display the figure window.
  315. If the figure was not created using `~.pyplot.figure`, it will lack
  316. a `~.backend_bases.FigureManagerBase`, and this method will raise an
  317. AttributeError.
  318. .. warning::
  319. This does not manage an GUI event loop. Consequently, the figure
  320. may only be shown briefly or not shown at all if you or your
  321. environment are not managing an event loop.
  322. Proper use cases for `.Figure.show` include running this from a
  323. GUI application or an IPython shell.
  324. If you're running a pure python shell or executing a non-GUI
  325. python script, you should use `matplotlib.pyplot.show` instead,
  326. which takes care of managing the event loop for you.
  327. Parameters
  328. ----------
  329. warn : bool, default: True
  330. If ``True`` and we are not running headless (i.e. on Linux with an
  331. unset DISPLAY), issue warning when called on a non-GUI backend.
  332. """
  333. if self.canvas.manager is None:
  334. raise AttributeError(
  335. "Figure.show works only for figures managed by pyplot, "
  336. "normally created by pyplot.figure()")
  337. try:
  338. self.canvas.manager.show()
  339. except NonGuiException as exc:
  340. cbook._warn_external(str(exc))
  341. def get_axes(self):
  342. """
  343. Return a list of axes in the Figure. You can access and modify the
  344. axes in the Figure through this list.
  345. Do not modify the list itself. Instead, use `~Figure.add_axes`,
  346. `~.Figure.add_subplot` or `~.Figure.delaxes` to add or remove an axes.
  347. Note: This is equivalent to the property `~.Figure.axes`.
  348. """
  349. return self._axstack.as_list()
  350. axes = property(get_axes, doc="""
  351. List of axes in the Figure. You can access and modify the axes in the
  352. Figure through this list.
  353. Do not modify the list itself. Instead, use "`~Figure.add_axes`,
  354. `~.Figure.add_subplot` or `~.Figure.delaxes` to add or remove an axes.
  355. """)
  356. def _get_dpi(self):
  357. return self._dpi
  358. def _set_dpi(self, dpi, forward=True):
  359. """
  360. Parameters
  361. ----------
  362. dpi : float
  363. forward : bool
  364. Passed on to `~.Figure.set_size_inches`
  365. """
  366. if dpi == self._dpi:
  367. # We don't want to cause undue events in backends.
  368. return
  369. self._dpi = dpi
  370. self.dpi_scale_trans.clear().scale(dpi)
  371. w, h = self.get_size_inches()
  372. self.set_size_inches(w, h, forward=forward)
  373. self.callbacks.process('dpi_changed', self)
  374. dpi = property(_get_dpi, _set_dpi, doc="The resolution in dots per inch.")
  375. def get_tight_layout(self):
  376. """Return whether `.tight_layout` is called when drawing."""
  377. return self._tight
  378. def set_tight_layout(self, tight):
  379. """
  380. Set whether and how `.tight_layout` is called when drawing.
  381. Parameters
  382. ----------
  383. tight : bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None
  384. If a bool, sets whether to call `.tight_layout` upon drawing.
  385. If ``None``, use the ``figure.autolayout`` rcparam instead.
  386. If a dict, pass it as kwargs to `.tight_layout`, overriding the
  387. default paddings.
  388. """
  389. if tight is None:
  390. tight = mpl.rcParams['figure.autolayout']
  391. self._tight = bool(tight)
  392. self._tight_parameters = tight if isinstance(tight, dict) else {}
  393. self.stale = True
  394. def get_constrained_layout(self):
  395. """
  396. Return whether constrained layout is being used.
  397. See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
  398. """
  399. return self._constrained
  400. def set_constrained_layout(self, constrained):
  401. """
  402. Set whether ``constrained_layout`` is used upon drawing. If None,
  403. :rc:`figure.constrained_layout.use` value will be used.
  404. When providing a dict containing the keys `w_pad`, `h_pad`
  405. the default ``constrained_layout`` paddings will be
  406. overridden. These pads are in inches and default to 3.0/72.0.
  407. ``w_pad`` is the width padding and ``h_pad`` is the height padding.
  408. See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
  409. Parameters
  410. ----------
  411. constrained : bool or dict or None
  412. """
  413. self._constrained_layout_pads = dict()
  414. self._constrained_layout_pads['w_pad'] = None
  415. self._constrained_layout_pads['h_pad'] = None
  416. self._constrained_layout_pads['wspace'] = None
  417. self._constrained_layout_pads['hspace'] = None
  418. if constrained is None:
  419. constrained = mpl.rcParams['figure.constrained_layout.use']
  420. self._constrained = bool(constrained)
  421. if isinstance(constrained, dict):
  422. self.set_constrained_layout_pads(**constrained)
  423. else:
  424. self.set_constrained_layout_pads()
  425. self.stale = True
  426. def set_constrained_layout_pads(self, **kwargs):
  427. """
  428. Set padding for ``constrained_layout``. Note the kwargs can be passed
  429. as a dictionary ``fig.set_constrained_layout(**paddict)``.
  430. See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
  431. Parameters
  432. ----------
  433. w_pad : float
  434. Width padding in inches. This is the pad around axes
  435. and is meant to make sure there is enough room for fonts to
  436. look good. Defaults to 3 pts = 0.04167 inches
  437. h_pad : float
  438. Height padding in inches. Defaults to 3 pts.
  439. wspace : float
  440. Width padding between subplots, expressed as a fraction of the
  441. subplot width. The total padding ends up being w_pad + wspace.
  442. hspace : float
  443. Height padding between subplots, expressed as a fraction of the
  444. subplot width. The total padding ends up being h_pad + hspace.
  445. """
  446. todo = ['w_pad', 'h_pad', 'wspace', 'hspace']
  447. for td in todo:
  448. if td in kwargs and kwargs[td] is not None:
  449. self._constrained_layout_pads[td] = kwargs[td]
  450. else:
  451. self._constrained_layout_pads[td] = (
  452. mpl.rcParams['figure.constrained_layout.' + td])
  453. def get_constrained_layout_pads(self, relative=False):
  454. """
  455. Get padding for ``constrained_layout``.
  456. Returns a list of ``w_pad, h_pad`` in inches and
  457. ``wspace`` and ``hspace`` as fractions of the subplot.
  458. See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
  459. Parameters
  460. ----------
  461. relative : bool
  462. If `True`, then convert from inches to figure relative.
  463. """
  464. w_pad = self._constrained_layout_pads['w_pad']
  465. h_pad = self._constrained_layout_pads['h_pad']
  466. wspace = self._constrained_layout_pads['wspace']
  467. hspace = self._constrained_layout_pads['hspace']
  468. if relative and (w_pad is not None or h_pad is not None):
  469. renderer0 = layoutbox.get_renderer(self)
  470. dpi = renderer0.dpi
  471. w_pad = w_pad * dpi / renderer0.width
  472. h_pad = h_pad * dpi / renderer0.height
  473. return w_pad, h_pad, wspace, hspace
  474. def autofmt_xdate(
  475. self, bottom=0.2, rotation=30, ha='right', which='major'):
  476. """
  477. Date ticklabels often overlap, so it is useful to rotate them
  478. and right align them. Also, a common use case is a number of
  479. subplots with shared xaxes where the x-axis is date data. The
  480. ticklabels are often long, and it helps to rotate them on the
  481. bottom subplot and turn them off on other subplots, as well as
  482. turn off xlabels.
  483. Parameters
  484. ----------
  485. bottom : float, default: 0.2
  486. The bottom of the subplots for `subplots_adjust`.
  487. rotation : float, default: 30 degrees
  488. The rotation angle of the xtick labels in degrees.
  489. ha : {'left', 'center', 'right'}, default: 'right'
  490. The horizontal alignment of the xticklabels.
  491. which : {'major', 'minor', 'both'}, default: 'major'
  492. Selects which ticklabels to rotate.
  493. """
  494. if which is None:
  495. cbook.warn_deprecated(
  496. "3.3", message="Support for passing which=None to mean "
  497. "which='major' is deprecated since %(since)s and will be "
  498. "removed %(removal)s.")
  499. allsubplots = all(hasattr(ax, 'is_last_row') for ax in self.axes)
  500. if len(self.axes) == 1:
  501. for label in self.axes[0].get_xticklabels(which=which):
  502. label.set_ha(ha)
  503. label.set_rotation(rotation)
  504. else:
  505. if allsubplots:
  506. for ax in self.get_axes():
  507. if ax.is_last_row():
  508. for label in ax.get_xticklabels(which=which):
  509. label.set_ha(ha)
  510. label.set_rotation(rotation)
  511. else:
  512. for label in ax.get_xticklabels(which=which):
  513. label.set_visible(False)
  514. ax.set_xlabel('')
  515. if allsubplots:
  516. self.subplots_adjust(bottom=bottom)
  517. self.stale = True
  518. def get_children(self):
  519. """Get a list of artists contained in the figure."""
  520. return [self.patch,
  521. *self.artists,
  522. *self.axes,
  523. *self.lines,
  524. *self.patches,
  525. *self.texts,
  526. *self.images,
  527. *self.legends]
  528. def contains(self, mouseevent):
  529. """
  530. Test whether the mouse event occurred on the figure.
  531. Returns
  532. -------
  533. bool, {}
  534. """
  535. inside, info = self._default_contains(mouseevent, figure=self)
  536. if inside is not None:
  537. return inside, info
  538. inside = self.bbox.contains(mouseevent.x, mouseevent.y)
  539. return inside, {}
  540. def get_window_extent(self, *args, **kwargs):
  541. """
  542. Return the figure bounding box in display space. Arguments are ignored.
  543. """
  544. return self.bbox
  545. def suptitle(self, t, **kwargs):
  546. """
  547. Add a centered title to the figure.
  548. Parameters
  549. ----------
  550. t : str
  551. The title text.
  552. x : float, default 0.5
  553. The x location of the text in figure coordinates.
  554. y : float, default 0.98
  555. The y location of the text in figure coordinates.
  556. horizontalalignment, ha : {'center', 'left', right'}, default: 'center'
  557. The horizontal alignment of the text relative to (*x*, *y*).
  558. verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, \
  559. default: 'top'
  560. The vertical alignment of the text relative to (*x*, *y*).
  561. fontsize, size : default: :rc:`figure.titlesize`
  562. The font size of the text. See `.Text.set_size` for possible
  563. values.
  564. fontweight, weight : default: :rc:`figure.titleweight`
  565. The font weight of the text. See `.Text.set_weight` for possible
  566. values.
  567. Returns
  568. -------
  569. text
  570. The `.Text` instance of the title.
  571. Other Parameters
  572. ----------------
  573. fontproperties : None or dict, optional
  574. A dict of font properties. If *fontproperties* is given the
  575. default values for font size and weight are taken from the
  576. `.FontProperties` defaults. :rc:`figure.titlesize` and
  577. :rc:`figure.titleweight` are ignored in this case.
  578. **kwargs
  579. Additional kwargs are `matplotlib.text.Text` properties.
  580. Examples
  581. --------
  582. >>> fig.suptitle('This is the figure title', fontsize=12)
  583. """
  584. manual_position = ('x' in kwargs or 'y' in kwargs)
  585. x = kwargs.pop('x', 0.5)
  586. y = kwargs.pop('y', 0.98)
  587. if 'horizontalalignment' not in kwargs and 'ha' not in kwargs:
  588. kwargs['horizontalalignment'] = 'center'
  589. if 'verticalalignment' not in kwargs and 'va' not in kwargs:
  590. kwargs['verticalalignment'] = 'top'
  591. if 'fontproperties' not in kwargs:
  592. if 'fontsize' not in kwargs and 'size' not in kwargs:
  593. kwargs['size'] = mpl.rcParams['figure.titlesize']
  594. if 'fontweight' not in kwargs and 'weight' not in kwargs:
  595. kwargs['weight'] = mpl.rcParams['figure.titleweight']
  596. sup = self.text(x, y, t, **kwargs)
  597. if self._suptitle is not None:
  598. self._suptitle.set_text(t)
  599. self._suptitle.set_position((x, y))
  600. self._suptitle.update_from(sup)
  601. sup.remove()
  602. else:
  603. self._suptitle = sup
  604. self._suptitle._layoutbox = None
  605. if self._layoutbox is not None and not manual_position:
  606. w_pad, h_pad, wspace, hspace = \
  607. self.get_constrained_layout_pads(relative=True)
  608. figlb = self._layoutbox
  609. self._suptitle._layoutbox = layoutbox.LayoutBox(
  610. parent=figlb, artist=self._suptitle,
  611. name=figlb.name+'.suptitle')
  612. # stack the suptitle on top of all the children.
  613. # Some day this should be on top of all the children in the
  614. # gridspec only.
  615. for child in figlb.children:
  616. if child is not self._suptitle._layoutbox:
  617. layoutbox.vstack([self._suptitle._layoutbox,
  618. child],
  619. padding=h_pad*2., strength='required')
  620. self.stale = True
  621. return self._suptitle
  622. def set_canvas(self, canvas):
  623. """
  624. Set the canvas that contains the figure
  625. Parameters
  626. ----------
  627. canvas : FigureCanvas
  628. """
  629. self.canvas = canvas
  630. def figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None,
  631. vmin=None, vmax=None, origin=None, resize=False, **kwargs):
  632. """
  633. Add a non-resampled image to the figure.
  634. The image is attached to the lower or upper left corner depending on
  635. *origin*.
  636. Parameters
  637. ----------
  638. X
  639. The image data. This is an array of one of the following shapes:
  640. - MxN: luminance (grayscale) values
  641. - MxNx3: RGB values
  642. - MxNx4: RGBA values
  643. xo, yo : int
  644. The *x*/*y* image offset in pixels.
  645. alpha : None or float
  646. The alpha blending value.
  647. norm : `matplotlib.colors.Normalize`
  648. A `.Normalize` instance to map the luminance to the
  649. interval [0, 1].
  650. cmap : str or `matplotlib.colors.Colormap`, default: :rc:`image.cmap`
  651. The colormap to use.
  652. vmin, vmax : float
  653. If *norm* is not given, these values set the data limits for the
  654. colormap.
  655. origin : {'upper', 'lower'}, default: :rc:`image.origin`
  656. Indicates where the [0, 0] index of the array is in the upper left
  657. or lower left corner of the axes.
  658. resize : bool
  659. If *True*, resize the figure to match the given image size.
  660. Returns
  661. -------
  662. `matplotlib.image.FigureImage`
  663. Other Parameters
  664. ----------------
  665. **kwargs
  666. Additional kwargs are `.Artist` kwargs passed on to `.FigureImage`.
  667. Notes
  668. -----
  669. figimage complements the axes image (`~matplotlib.axes.Axes.imshow`)
  670. which will be resampled to fit the current axes. If you want
  671. a resampled image to fill the entire figure, you can define an
  672. `~matplotlib.axes.Axes` with extent [0, 0, 1, 1].
  673. Examples
  674. --------
  675. ::
  676. f = plt.figure()
  677. nx = int(f.get_figwidth() * f.dpi)
  678. ny = int(f.get_figheight() * f.dpi)
  679. data = np.random.random((ny, nx))
  680. f.figimage(data)
  681. plt.show()
  682. """
  683. if resize:
  684. dpi = self.get_dpi()
  685. figsize = [x / dpi for x in (X.shape[1], X.shape[0])]
  686. self.set_size_inches(figsize, forward=True)
  687. im = mimage.FigureImage(self, cmap, norm, xo, yo, origin, **kwargs)
  688. im.stale_callback = _stale_figure_callback
  689. im.set_array(X)
  690. im.set_alpha(alpha)
  691. if norm is None:
  692. im.set_clim(vmin, vmax)
  693. self.images.append(im)
  694. im._remove_method = self.images.remove
  695. self.stale = True
  696. return im
  697. def set_size_inches(self, w, h=None, forward=True):
  698. """
  699. Set the figure size in inches.
  700. Call signatures::
  701. fig.set_size_inches(w, h) # OR
  702. fig.set_size_inches((w, h))
  703. Parameters
  704. ----------
  705. w : (float, float) or float
  706. Width and height in inches (if height not specified as a separate
  707. argument) or width.
  708. h : float
  709. Height in inches.
  710. forward : bool, default: True
  711. If ``True``, the canvas size is automatically updated, e.g.,
  712. you can resize the figure window from the shell.
  713. See Also
  714. --------
  715. matplotlib.figure.Figure.get_size_inches
  716. matplotlib.figure.Figure.set_figwidth
  717. matplotlib.figure.Figure.set_figheight
  718. Notes
  719. -----
  720. To transform from pixels to inches divide by `Figure.dpi`.
  721. """
  722. if h is None: # Got called with a single pair as argument.
  723. w, h = w
  724. size = np.array([w, h])
  725. if not np.isfinite(size).all() or (size < 0).any():
  726. raise ValueError(f'figure size must be positive finite not {size}')
  727. self.bbox_inches.p1 = size
  728. if forward:
  729. canvas = getattr(self, 'canvas')
  730. if canvas is not None:
  731. dpi_ratio = getattr(canvas, '_dpi_ratio', 1)
  732. manager = getattr(canvas, 'manager', None)
  733. if manager is not None:
  734. manager.resize(*(size * self.dpi / dpi_ratio).astype(int))
  735. self.stale = True
  736. def get_size_inches(self):
  737. """
  738. Return the current size of the figure in inches.
  739. Returns
  740. -------
  741. ndarray
  742. The size (width, height) of the figure in inches.
  743. See Also
  744. --------
  745. matplotlib.figure.Figure.set_size_inches
  746. matplotlib.figure.Figure.get_figwidth
  747. matplotlib.figure.Figure.get_figheight
  748. Notes
  749. -----
  750. The size in pixels can be obtained by multiplying with `Figure.dpi`.
  751. """
  752. return np.array(self.bbox_inches.p1)
  753. def get_edgecolor(self):
  754. """Get the edge color of the Figure rectangle."""
  755. return self.patch.get_edgecolor()
  756. def get_facecolor(self):
  757. """Get the face color of the Figure rectangle."""
  758. return self.patch.get_facecolor()
  759. def get_figwidth(self):
  760. """Return the figure width in inches."""
  761. return self.bbox_inches.width
  762. def get_figheight(self):
  763. """Return the figure height in inches."""
  764. return self.bbox_inches.height
  765. def get_dpi(self):
  766. """Return the resolution in dots per inch as a float."""
  767. return self.dpi
  768. def get_frameon(self):
  769. """
  770. Return the figure's background patch visibility, i.e.
  771. whether the figure background will be drawn. Equivalent to
  772. ``Figure.patch.get_visible()``.
  773. """
  774. return self.patch.get_visible()
  775. def set_edgecolor(self, color):
  776. """
  777. Set the edge color of the Figure rectangle.
  778. Parameters
  779. ----------
  780. color : color
  781. """
  782. self.patch.set_edgecolor(color)
  783. def set_facecolor(self, color):
  784. """
  785. Set the face color of the Figure rectangle.
  786. Parameters
  787. ----------
  788. color : color
  789. """
  790. self.patch.set_facecolor(color)
  791. def set_dpi(self, val):
  792. """
  793. Set the resolution of the figure in dots-per-inch.
  794. Parameters
  795. ----------
  796. val : float
  797. """
  798. self.dpi = val
  799. self.stale = True
  800. def set_figwidth(self, val, forward=True):
  801. """
  802. Set the width of the figure in inches.
  803. Parameters
  804. ----------
  805. val : float
  806. forward : bool
  807. See `set_size_inches`.
  808. See Also
  809. --------
  810. matplotlib.figure.Figure.set_figheight
  811. matplotlib.figure.Figure.set_size_inches
  812. """
  813. self.set_size_inches(val, self.get_figheight(), forward=forward)
  814. def set_figheight(self, val, forward=True):
  815. """
  816. Set the height of the figure in inches.
  817. Parameters
  818. ----------
  819. val : float
  820. forward : bool
  821. See `set_size_inches`.
  822. See Also
  823. --------
  824. matplotlib.figure.Figure.set_figwidth
  825. matplotlib.figure.Figure.set_size_inches
  826. """
  827. self.set_size_inches(self.get_figwidth(), val, forward=forward)
  828. def set_frameon(self, b):
  829. """
  830. Set the figure's background patch visibility, i.e.
  831. whether the figure background will be drawn. Equivalent to
  832. ``Figure.patch.set_visible()``.
  833. Parameters
  834. ----------
  835. b : bool
  836. """
  837. self.patch.set_visible(b)
  838. self.stale = True
  839. frameon = property(get_frameon, set_frameon)
  840. def add_artist(self, artist, clip=False):
  841. """
  842. Add an `.Artist` to the figure.
  843. Usually artists are added to axes objects using `.Axes.add_artist`;
  844. this method can be used in the rare cases where one needs to add
  845. artists directly to the figure instead.
  846. Parameters
  847. ----------
  848. artist : `~matplotlib.artist.Artist`
  849. The artist to add to the figure. If the added artist has no
  850. transform previously set, its transform will be set to
  851. ``figure.transFigure``.
  852. clip : bool, default: False
  853. Whether the added artist should be clipped by the figure patch.
  854. Returns
  855. -------
  856. `~matplotlib.artist.Artist`
  857. The added artist.
  858. """
  859. artist.set_figure(self)
  860. self.artists.append(artist)
  861. artist._remove_method = self.artists.remove
  862. if not artist.is_transform_set():
  863. artist.set_transform(self.transFigure)
  864. if clip:
  865. artist.set_clip_path(self.patch)
  866. self.stale = True
  867. return artist
  868. def _make_key(self, *args, **kwargs):
  869. """Make a hashable key out of args and kwargs."""
  870. def fixitems(items):
  871. # items may have arrays and lists in them, so convert them
  872. # to tuples for the key
  873. ret = []
  874. for k, v in items:
  875. # some objects can define __getitem__ without being
  876. # iterable and in those cases the conversion to tuples
  877. # will fail. So instead of using the np.iterable(v) function
  878. # we simply try and convert to a tuple, and proceed if not.
  879. try:
  880. v = tuple(v)
  881. except Exception:
  882. pass
  883. ret.append((k, v))
  884. return tuple(ret)
  885. def fixlist(args):
  886. ret = []
  887. for a in args:
  888. if np.iterable(a):
  889. a = tuple(a)
  890. ret.append(a)
  891. return tuple(ret)
  892. key = fixlist(args), fixitems(kwargs.items())
  893. return key
  894. def _process_projection_requirements(
  895. self, *args, polar=False, projection=None, **kwargs):
  896. """
  897. Handle the args/kwargs to add_axes/add_subplot/gca, returning::
  898. (axes_proj_class, proj_class_kwargs, proj_stack_key)
  899. which can be used for new axes initialization/identification.
  900. """
  901. if polar:
  902. if projection is not None and projection != 'polar':
  903. raise ValueError(
  904. "polar=True, yet projection=%r. "
  905. "Only one of these arguments should be supplied." %
  906. projection)
  907. projection = 'polar'
  908. if isinstance(projection, str) or projection is None:
  909. projection_class = projections.get_projection_class(projection)
  910. elif hasattr(projection, '_as_mpl_axes'):
  911. projection_class, extra_kwargs = projection._as_mpl_axes()
  912. kwargs.update(**extra_kwargs)
  913. else:
  914. raise TypeError('projection must be a string, None or implement a '
  915. '_as_mpl_axes method. Got %r' % projection)
  916. # Make the key without projection kwargs, this is used as a unique
  917. # lookup for axes instances
  918. key = self._make_key(*args, **kwargs)
  919. return projection_class, kwargs, key
  920. @docstring.dedent_interpd
  921. def add_axes(self, *args, **kwargs):
  922. """
  923. Add an axes to the figure.
  924. Call signatures::
  925. add_axes(rect, projection=None, polar=False, **kwargs)
  926. add_axes(ax)
  927. Parameters
  928. ----------
  929. rect : sequence of float
  930. The dimensions [left, bottom, width, height] of the new axes. All
  931. quantities are in fractions of figure width and height.
  932. projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
  933. 'polar', 'rectilinear', str}, optional
  934. The projection type of the `~.axes.Axes`. *str* is the name of
  935. a custom projection, see `~matplotlib.projections`. The default
  936. None results in a 'rectilinear' projection.
  937. polar : bool, default: False
  938. If True, equivalent to projection='polar'.
  939. sharex, sharey : `~.axes.Axes`, optional
  940. Share the x or y `~matplotlib.axis` with sharex and/or sharey.
  941. The axis will have the same limits, ticks, and scale as the axis
  942. of the shared axes.
  943. label : str
  944. A label for the returned axes.
  945. Returns
  946. -------
  947. `~.axes.Axes`, or a subclass of `~.axes.Axes`
  948. The returned axes class depends on the projection used. It is
  949. `~.axes.Axes` if rectilinear projection is used and
  950. `.projections.polar.PolarAxes` if polar projection is used.
  951. Other Parameters
  952. ----------------
  953. **kwargs
  954. This method also takes the keyword arguments for
  955. the returned axes class. The keyword arguments for the
  956. rectilinear axes class `~.axes.Axes` can be found in
  957. the following table but there might also be other keyword
  958. arguments if another projection is used, see the actual axes
  959. class.
  960. %(Axes)s
  961. Notes
  962. -----
  963. If the figure already has an axes with key (*args*,
  964. *kwargs*) then it will simply make that axes current and
  965. return it. This behavior is deprecated. Meanwhile, if you do
  966. not want this behavior (i.e., you want to force the creation of a
  967. new axes), you must use a unique set of args and kwargs. The axes
  968. *label* attribute has been exposed for this purpose: if you want
  969. two axes that are otherwise identical to be added to the figure,
  970. make sure you give them unique labels.
  971. In rare circumstances, `.add_axes` may be called with a single
  972. argument, a axes instance already created in the present figure but
  973. not in the figure's list of axes.
  974. See Also
  975. --------
  976. .Figure.add_subplot
  977. .pyplot.subplot
  978. .pyplot.axes
  979. .Figure.subplots
  980. .pyplot.subplots
  981. Examples
  982. --------
  983. Some simple examples::
  984. rect = l, b, w, h
  985. fig = plt.figure()
  986. fig.add_axes(rect, label=label1)
  987. fig.add_axes(rect, label=label2)
  988. fig.add_axes(rect, frameon=False, facecolor='g')
  989. fig.add_axes(rect, polar=True)
  990. ax = fig.add_axes(rect, projection='polar')
  991. fig.delaxes(ax)
  992. fig.add_axes(ax)
  993. """
  994. if not len(args) and 'rect' not in kwargs:
  995. cbook.warn_deprecated(
  996. "3.3",
  997. message="Calling add_axes() without argument is "
  998. "deprecated since %(since)s and will be removed %(removal)s. "
  999. "You may want to use add_subplot() instead.")
  1000. return
  1001. elif 'rect' in kwargs:
  1002. if len(args):
  1003. raise TypeError(
  1004. "add_axes() got multiple values for argument 'rect'")
  1005. args = (kwargs.pop('rect'), )
  1006. # shortcut the projection "key" modifications later on, if an axes
  1007. # with the exact args/kwargs exists, return it immediately.
  1008. key = self._make_key(*args, **kwargs)
  1009. ax = self._axstack.get(key)
  1010. if ax is not None:
  1011. self.sca(ax)
  1012. return ax
  1013. if isinstance(args[0], Axes):
  1014. a = args[0]
  1015. if a.get_figure() is not self:
  1016. raise ValueError(
  1017. "The Axes must have been created in the present figure")
  1018. else:
  1019. rect = args[0]
  1020. if not np.isfinite(rect).all():
  1021. raise ValueError('all entries in rect must be finite '
  1022. 'not {}'.format(rect))
  1023. projection_class, kwargs, key = \
  1024. self._process_projection_requirements(*args, **kwargs)
  1025. # check that an axes of this type doesn't already exist, if it
  1026. # does, set it as active and return it
  1027. ax = self._axstack.get(key)
  1028. if isinstance(ax, projection_class):
  1029. self.sca(ax)
  1030. return ax
  1031. # create the new axes using the axes class given
  1032. a = projection_class(self, rect, **kwargs)
  1033. return self._add_axes_internal(key, a)
  1034. @docstring.dedent_interpd
  1035. def add_subplot(self, *args, **kwargs):
  1036. """
  1037. Add an `~.axes.Axes` to the figure as part of a subplot arrangement.
  1038. Call signatures::
  1039. add_subplot(nrows, ncols, index, **kwargs)
  1040. add_subplot(pos, **kwargs)
  1041. add_subplot(ax)
  1042. add_subplot()
  1043. Parameters
  1044. ----------
  1045. *args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
  1046. The position of the subplot described by one of
  1047. - Three integers (*nrows*, *ncols*, *index*). The subplot will
  1048. take the *index* position on a grid with *nrows* rows and
  1049. *ncols* columns. *index* starts at 1 in the upper left corner
  1050. and increases to the right. *index* can also be a two-tuple
  1051. specifying the (*first*, *last*) indices (1-based, and including
  1052. *last*) of the subplot, e.g., ``fig.add_subplot(3, 1, (1, 2))``
  1053. makes a subplot that spans the upper 2/3 of the figure.
  1054. - A 3-digit integer. The digits are interpreted as if given
  1055. separately as three single-digit integers, i.e.
  1056. ``fig.add_subplot(235)`` is the same as
  1057. ``fig.add_subplot(2, 3, 5)``. Note that this can only be used
  1058. if there are no more than 9 subplots.
  1059. - A `.SubplotSpec`.
  1060. In rare circumstances, `.add_subplot` may be called with a single
  1061. argument, a subplot axes instance already created in the
  1062. present figure but not in the figure's list of axes.
  1063. projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
  1064. 'polar', 'rectilinear', str}, optional
  1065. The projection type of the subplot (`~.axes.Axes`). *str* is the
  1066. name of a custom projection, see `~matplotlib.projections`. The
  1067. default None results in a 'rectilinear' projection.
  1068. polar : bool, default: False
  1069. If True, equivalent to projection='polar'.
  1070. sharex, sharey : `~.axes.Axes`, optional
  1071. Share the x or y `~matplotlib.axis` with sharex and/or sharey.
  1072. The axis will have the same limits, ticks, and scale as the axis
  1073. of the shared axes.
  1074. label : str
  1075. A label for the returned axes.
  1076. Returns
  1077. -------
  1078. `.axes.SubplotBase`, or another subclass of `~.axes.Axes`
  1079. The axes of the subplot. The returned axes base class depends on
  1080. the projection used. It is `~.axes.Axes` if rectilinear projection
  1081. is used and `.projections.polar.PolarAxes` if polar projection
  1082. is used. The returned axes is then a subplot subclass of the
  1083. base class.
  1084. Other Parameters
  1085. ----------------
  1086. **kwargs
  1087. This method also takes the keyword arguments for the returned axes
  1088. base class; except for the *figure* argument. The keyword arguments
  1089. for the rectilinear base class `~.axes.Axes` can be found in
  1090. the following table but there might also be other keyword
  1091. arguments if another projection is used.
  1092. %(Axes)s
  1093. Notes
  1094. -----
  1095. If the figure already has a subplot with key (*args*,
  1096. *kwargs*) then it will simply make that subplot current and
  1097. return it. This behavior is deprecated. Meanwhile, if you do
  1098. not want this behavior (i.e., you want to force the creation of a
  1099. new subplot), you must use a unique set of args and kwargs. The axes
  1100. *label* attribute has been exposed for this purpose: if you want
  1101. two subplots that are otherwise identical to be added to the figure,
  1102. make sure you give them unique labels.
  1103. See Also
  1104. --------
  1105. .Figure.add_axes
  1106. .pyplot.subplot
  1107. .pyplot.axes
  1108. .Figure.subplots
  1109. .pyplot.subplots
  1110. Examples
  1111. --------
  1112. ::
  1113. fig = plt.figure()
  1114. fig.add_subplot(231)
  1115. ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general
  1116. fig.add_subplot(232, frameon=False) # subplot with no frame
  1117. fig.add_subplot(233, projection='polar') # polar subplot
  1118. fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1
  1119. fig.add_subplot(235, facecolor="red") # red subplot
  1120. ax1.remove() # delete ax1 from the figure
  1121. fig.add_subplot(ax1) # add ax1 back to the figure
  1122. """
  1123. if 'figure' in kwargs:
  1124. # Axes itself allows for a 'figure' kwarg, but since we want to
  1125. # bind the created Axes to self, it is not allowed here.
  1126. raise TypeError(
  1127. "add_subplot() got an unexpected keyword argument 'figure'")
  1128. if len(args) == 1 and isinstance(args[0], SubplotBase):
  1129. ax = args[0]
  1130. if ax.get_figure() is not self:
  1131. raise ValueError("The Subplot must have been created in "
  1132. "the present figure")
  1133. # make a key for the subplot (which includes the axes object id
  1134. # in the hash)
  1135. key = self._make_key(*args, **kwargs)
  1136. else:
  1137. if not args:
  1138. args = (1, 1, 1)
  1139. # Normalize correct ijk values to (i, j, k) here so that
  1140. # add_subplot(111) == add_subplot(1, 1, 1). Invalid values will
  1141. # trigger errors later (via SubplotSpec._from_subplot_args).
  1142. if (len(args) == 1 and isinstance(args[0], Integral)
  1143. and 100 <= args[0] <= 999):
  1144. args = tuple(map(int, str(args[0])))
  1145. projection_class, kwargs, key = \
  1146. self._process_projection_requirements(*args, **kwargs)
  1147. ax = self._axstack.get(key) # search axes with this key in stack
  1148. if ax is not None:
  1149. if isinstance(ax, projection_class):
  1150. # the axes already existed, so set it as active & return
  1151. self.sca(ax)
  1152. return ax
  1153. else:
  1154. # Undocumented convenience behavior:
  1155. # subplot(111); subplot(111, projection='polar')
  1156. # will replace the first with the second.
  1157. # Without this, add_subplot would be simpler and
  1158. # more similar to add_axes.
  1159. self._axstack.remove(ax)
  1160. ax = subplot_class_factory(projection_class)(self, *args, **kwargs)
  1161. return self._add_axes_internal(key, ax)
  1162. def _add_axes_internal(self, key, ax):
  1163. """Private helper for `add_axes` and `add_subplot`."""
  1164. self._axstack.add(key, ax)
  1165. self.sca(ax)
  1166. ax._remove_method = self.delaxes
  1167. self.stale = True
  1168. ax.stale_callback = _stale_figure_callback
  1169. return ax
  1170. @cbook._make_keyword_only("3.3", "sharex")
  1171. def subplots(self, nrows=1, ncols=1, sharex=False, sharey=False,
  1172. squeeze=True, subplot_kw=None, gridspec_kw=None):
  1173. """
  1174. Add a set of subplots to this figure.
  1175. This utility wrapper makes it convenient to create common layouts of
  1176. subplots in a single call.
  1177. Parameters
  1178. ----------
  1179. nrows, ncols : int, default: 1
  1180. Number of rows/columns of the subplot grid.
  1181. sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
  1182. Controls sharing of properties among x (*sharex*) or y (*sharey*)
  1183. axes:
  1184. - True or 'all': x- or y-axis will be shared among all subplots.
  1185. - False or 'none': each subplot x- or y-axis will be independent.
  1186. - 'row': each subplot row will share an x- or y-axis.
  1187. - 'col': each subplot column will share an x- or y-axis.
  1188. When subplots have a shared x-axis along a column, only the x tick
  1189. labels of the bottom subplot are created. Similarly, when subplots
  1190. have a shared y-axis along a row, only the y tick labels of the
  1191. first column subplot are created. To later turn other subplots'
  1192. ticklabels on, use `~matplotlib.axes.Axes.tick_params`.
  1193. squeeze : bool, default: True
  1194. - If True, extra dimensions are squeezed out from the returned
  1195. array of Axes:
  1196. - if only one subplot is constructed (nrows=ncols=1), the
  1197. resulting single Axes object is returned as a scalar.
  1198. - for Nx1 or 1xM subplots, the returned object is a 1D numpy
  1199. object array of Axes objects.
  1200. - for NxM, subplots with N>1 and M>1 are returned as a 2D array.
  1201. - If False, no squeezing at all is done: the returned Axes object
  1202. is always a 2D array containing Axes instances, even if it ends
  1203. up being 1x1.
  1204. subplot_kw : dict, optional
  1205. Dict with keywords passed to the `.Figure.add_subplot` call used to
  1206. create each subplot.
  1207. gridspec_kw : dict, optional
  1208. Dict with keywords passed to the
  1209. `~matplotlib.gridspec.GridSpec` constructor used to create
  1210. the grid the subplots are placed on.
  1211. Returns
  1212. -------
  1213. `~.axes.Axes` or array of Axes
  1214. Either a single `~matplotlib.axes.Axes` object or an array of Axes
  1215. objects if more than one subplot was created. The dimensions of the
  1216. resulting array can be controlled with the *squeeze* keyword, see
  1217. above.
  1218. See Also
  1219. --------
  1220. .pyplot.subplots
  1221. .Figure.add_subplot
  1222. .pyplot.subplot
  1223. Examples
  1224. --------
  1225. ::
  1226. # First create some toy data:
  1227. x = np.linspace(0, 2*np.pi, 400)
  1228. y = np.sin(x**2)
  1229. # Create a figure
  1230. plt.figure()
  1231. # Create a subplot
  1232. ax = fig.subplots()
  1233. ax.plot(x, y)
  1234. ax.set_title('Simple plot')
  1235. # Create two subplots and unpack the output array immediately
  1236. ax1, ax2 = fig.subplots(1, 2, sharey=True)
  1237. ax1.plot(x, y)
  1238. ax1.set_title('Sharing Y axis')
  1239. ax2.scatter(x, y)
  1240. # Create four polar axes and access them through the returned array
  1241. axes = fig.subplots(2, 2, subplot_kw=dict(polar=True))
  1242. axes[0, 0].plot(x, y)
  1243. axes[1, 1].scatter(x, y)
  1244. # Share a X axis with each column of subplots
  1245. fig.subplots(2, 2, sharex='col')
  1246. # Share a Y axis with each row of subplots
  1247. fig.subplots(2, 2, sharey='row')
  1248. # Share both X and Y axes with all subplots
  1249. fig.subplots(2, 2, sharex='all', sharey='all')
  1250. # Note that this is the same as
  1251. fig.subplots(2, 2, sharex=True, sharey=True)
  1252. """
  1253. if gridspec_kw is None:
  1254. gridspec_kw = {}
  1255. return (self.add_gridspec(nrows, ncols, figure=self, **gridspec_kw)
  1256. .subplots(sharex=sharex, sharey=sharey, squeeze=squeeze,
  1257. subplot_kw=subplot_kw))
  1258. @staticmethod
  1259. def _normalize_grid_string(layout):
  1260. layout = inspect.cleandoc(layout)
  1261. return [list(ln) for ln in layout.strip('\n').split('\n')]
  1262. def subplot_mosaic(self, layout, *, subplot_kw=None, gridspec_kw=None,
  1263. empty_sentinel='.'):
  1264. """
  1265. Build a layout of Axes based on ASCII art or nested lists.
  1266. This is a helper function to build complex GridSpec layouts visually.
  1267. .. note ::
  1268. This API is provisional and may be revised in the future based on
  1269. early user feedback.
  1270. Parameters
  1271. ----------
  1272. layout : list of list of {hashable or nested} or str
  1273. A visual layout of how you want your Axes to be arranged
  1274. labeled as strings. For example ::
  1275. x = [['A panel', 'A panel', 'edge'],
  1276. ['C panel', '.', 'edge']]
  1277. Produces 4 axes:
  1278. - 'A panel' which is 1 row high and spans the first two columns
  1279. - 'edge' which is 2 rows high and is on the right edge
  1280. - 'C panel' which in 1 row and 1 column wide in the bottom left
  1281. - a blank space 1 row and 1 column wide in the bottom center
  1282. Any of the entries in the layout can be a list of lists
  1283. of the same form to create nested layouts.
  1284. If input is a str, then it must be of the form ::
  1285. '''
  1286. AAE
  1287. C.E
  1288. '''
  1289. where each character is a column and each line is a row.
  1290. This only allows only single character Axes labels and does
  1291. not allow nesting but is very terse.
  1292. subplot_kw : dict, optional
  1293. Dictionary with keywords passed to the `.Figure.add_subplot` call
  1294. used to create each subplot.
  1295. gridspec_kw : dict, optional
  1296. Dictionary with keywords passed to the `.GridSpec` constructor used
  1297. to create the grid the subplots are placed on.
  1298. empty_sentinel : object, optional
  1299. Entry in the layout to mean "leave this space empty". Defaults
  1300. to ``'.'``. Note, if *layout* is a string, it is processed via
  1301. `inspect.cleandoc` to remove leading white space, which may
  1302. interfere with using white-space as the empty sentinel.
  1303. Returns
  1304. -------
  1305. dict[label, Axes]
  1306. A dictionary mapping the labels to the Axes objects.
  1307. """
  1308. subplot_kw = subplot_kw or {}
  1309. gridspec_kw = gridspec_kw or {}
  1310. # special-case string input
  1311. if isinstance(layout, str):
  1312. layout = self._normalize_grid_string(layout)
  1313. def _make_array(inp):
  1314. """
  1315. Convert input into 2D array
  1316. We need to have this internal function rather than
  1317. ``np.asarray(..., dtype=object)`` so that a list of lists
  1318. of lists does not get converted to an array of dimension >
  1319. 2
  1320. Returns
  1321. -------
  1322. 2D object array
  1323. """
  1324. r0, *rest = inp
  1325. for j, r in enumerate(rest, start=1):
  1326. if isinstance(r, str):
  1327. raise ValueError('List layout specification must be 2D')
  1328. if len(r0) != len(r):
  1329. raise ValueError(
  1330. "All of the rows must be the same length, however "
  1331. f"the first row ({r0!r}) has length {len(r0)} "
  1332. f"and row {j} ({r!r}) has length {len(r)}."
  1333. )
  1334. out = np.zeros((len(inp), len(r0)), dtype=object)
  1335. for j, r in enumerate(inp):
  1336. for k, v in enumerate(r):
  1337. out[j, k] = v
  1338. return out
  1339. def _identify_keys_and_nested(layout):
  1340. """
  1341. Given a 2D object array, identify unique IDs and nested layouts
  1342. Parameters
  1343. ----------
  1344. layout : 2D numpy object array
  1345. Returns
  1346. -------
  1347. unique_ids : Set[object]
  1348. The unique non-sub layout entries in this layout
  1349. nested : Dict[Tuple[int, int]], 2D object array
  1350. """
  1351. unique_ids = set()
  1352. nested = {}
  1353. for j, row in enumerate(layout):
  1354. for k, v in enumerate(row):
  1355. if v == empty_sentinel:
  1356. continue
  1357. elif not cbook.is_scalar_or_string(v):
  1358. nested[(j, k)] = _make_array(v)
  1359. else:
  1360. unique_ids.add(v)
  1361. return unique_ids, nested
  1362. def _do_layout(gs, layout, unique_ids, nested):
  1363. """
  1364. Recursively do the layout.
  1365. Parameters
  1366. ----------
  1367. gs : GridSpec
  1368. layout : 2D object array
  1369. The input converted to a 2D numpy array for this level.
  1370. unique_ids : Set[object]
  1371. The identified scalar labels at this level of nesting.
  1372. nested : Dict[Tuple[int, int]], 2D object array
  1373. The identified nested layouts if any.
  1374. Returns
  1375. -------
  1376. Dict[label, Axes]
  1377. A flat dict of all of the Axes created.
  1378. """
  1379. rows, cols = layout.shape
  1380. output = dict()
  1381. # create the Axes at this level of nesting
  1382. for name in unique_ids:
  1383. indx = np.argwhere(layout == name)
  1384. start_row, start_col = np.min(indx, axis=0)
  1385. end_row, end_col = np.max(indx, axis=0) + 1
  1386. slc = (slice(start_row, end_row), slice(start_col, end_col))
  1387. if (layout[slc] != name).any():
  1388. raise ValueError(
  1389. f"While trying to layout\n{layout!r}\n"
  1390. f"we found that the label {name!r} specifies a "
  1391. "non-rectangular or non-contiguous area.")
  1392. ax = self.add_subplot(
  1393. gs[slc], **{'label': str(name), **subplot_kw}
  1394. )
  1395. output[name] = ax
  1396. # do any sub-layouts
  1397. for (j, k), nested_layout in nested.items():
  1398. rows, cols = nested_layout.shape
  1399. nested_output = _do_layout(
  1400. gs[j, k].subgridspec(rows, cols, **gridspec_kw),
  1401. nested_layout,
  1402. *_identify_keys_and_nested(nested_layout)
  1403. )
  1404. overlap = set(output) & set(nested_output)
  1405. if overlap:
  1406. raise ValueError(f"There are duplicate keys {overlap} "
  1407. f"between the outer layout\n{layout!r}\n"
  1408. f"and the nested layout\n{nested_layout}")
  1409. output.update(nested_output)
  1410. return output
  1411. layout = _make_array(layout)
  1412. rows, cols = layout.shape
  1413. gs = self.add_gridspec(rows, cols, **gridspec_kw)
  1414. ret = _do_layout(gs, layout, *_identify_keys_and_nested(layout))
  1415. for k, ax in ret.items():
  1416. if isinstance(k, str):
  1417. ax.set_label(k)
  1418. return ret
  1419. def delaxes(self, ax):
  1420. """
  1421. Remove the `~.axes.Axes` *ax* from the figure; update the current axes.
  1422. """
  1423. def _reset_locators_and_formatters(axis):
  1424. # Set the formatters and locators to be associated with axis
  1425. # (where previously they may have been associated with another
  1426. # Axis instance)
  1427. #
  1428. # Because set_major_formatter() etc. force isDefault_* to be False,
  1429. # we have to manually check if the original formatter was a
  1430. # default and manually set isDefault_* if that was the case.
  1431. majfmt = axis.get_major_formatter()
  1432. isDefault = majfmt.axis.isDefault_majfmt
  1433. axis.set_major_formatter(majfmt)
  1434. if isDefault:
  1435. majfmt.axis.isDefault_majfmt = True
  1436. majloc = axis.get_major_locator()
  1437. isDefault = majloc.axis.isDefault_majloc
  1438. axis.set_major_locator(majloc)
  1439. if isDefault:
  1440. majloc.axis.isDefault_majloc = True
  1441. minfmt = axis.get_minor_formatter()
  1442. isDefault = majloc.axis.isDefault_minfmt
  1443. axis.set_minor_formatter(minfmt)
  1444. if isDefault:
  1445. minfmt.axis.isDefault_minfmt = True
  1446. minloc = axis.get_minor_locator()
  1447. isDefault = majloc.axis.isDefault_minloc
  1448. axis.set_minor_locator(minloc)
  1449. if isDefault:
  1450. minloc.axis.isDefault_minloc = True
  1451. def _break_share_link(ax, grouper):
  1452. siblings = grouper.get_siblings(ax)
  1453. if len(siblings) > 1:
  1454. grouper.remove(ax)
  1455. for last_ax in siblings:
  1456. if ax is not last_ax:
  1457. return last_ax
  1458. return None
  1459. self._axstack.remove(ax)
  1460. self._axobservers.process("_axes_change_event", self)
  1461. self.stale = True
  1462. last_ax = _break_share_link(ax, ax._shared_y_axes)
  1463. if last_ax is not None:
  1464. _reset_locators_and_formatters(last_ax.yaxis)
  1465. last_ax = _break_share_link(ax, ax._shared_x_axes)
  1466. if last_ax is not None:
  1467. _reset_locators_and_formatters(last_ax.xaxis)
  1468. def clf(self, keep_observers=False):
  1469. """
  1470. Clear the figure.
  1471. Set *keep_observers* to True if, for example,
  1472. a gui widget is tracking the axes in the figure.
  1473. """
  1474. self.suppressComposite = None
  1475. self.callbacks = cbook.CallbackRegistry()
  1476. for ax in tuple(self.axes): # Iterate over the copy.
  1477. ax.cla()
  1478. self.delaxes(ax) # removes ax from self._axstack
  1479. toolbar = getattr(self.canvas, 'toolbar', None)
  1480. if toolbar is not None:
  1481. toolbar.update()
  1482. self._axstack.clear()
  1483. self.artists = []
  1484. self.lines = []
  1485. self.patches = []
  1486. self.texts = []
  1487. self.images = []
  1488. self.legends = []
  1489. if not keep_observers:
  1490. self._axobservers = cbook.CallbackRegistry()
  1491. self._suptitle = None
  1492. if self.get_constrained_layout():
  1493. layoutbox.nonetree(self._layoutbox)
  1494. self.stale = True
  1495. def clear(self, keep_observers=False):
  1496. """Clear the figure -- synonym for `clf`."""
  1497. self.clf(keep_observers=keep_observers)
  1498. @allow_rasterization
  1499. def draw(self, renderer):
  1500. # docstring inherited
  1501. self._cachedRenderer = renderer
  1502. # draw the figure bounding box, perhaps none for white figure
  1503. if not self.get_visible():
  1504. return
  1505. artists = self.get_children()
  1506. artists.remove(self.patch)
  1507. artists = sorted(
  1508. (artist for artist in artists if not artist.get_animated()),
  1509. key=lambda artist: artist.get_zorder())
  1510. for ax in self.axes:
  1511. locator = ax.get_axes_locator()
  1512. if locator:
  1513. pos = locator(ax, renderer)
  1514. ax.apply_aspect(pos)
  1515. else:
  1516. ax.apply_aspect()
  1517. for child in ax.get_children():
  1518. if hasattr(child, 'apply_aspect'):
  1519. locator = child.get_axes_locator()
  1520. if locator:
  1521. pos = locator(child, renderer)
  1522. child.apply_aspect(pos)
  1523. else:
  1524. child.apply_aspect()
  1525. try:
  1526. renderer.open_group('figure', gid=self.get_gid())
  1527. if self.get_constrained_layout() and self.axes:
  1528. self.execute_constrained_layout(renderer)
  1529. if self.get_tight_layout() and self.axes:
  1530. try:
  1531. self.tight_layout(**self._tight_parameters)
  1532. except ValueError:
  1533. pass
  1534. # ValueError can occur when resizing a window.
  1535. self.patch.draw(renderer)
  1536. mimage._draw_list_compositing_images(
  1537. renderer, self, artists, self.suppressComposite)
  1538. renderer.close_group('figure')
  1539. finally:
  1540. self.stale = False
  1541. self.canvas.draw_event(renderer)
  1542. def draw_artist(self, a):
  1543. """
  1544. Draw `.Artist` instance *a* only.
  1545. This can only be called after the figure has been drawn.
  1546. """
  1547. if self._cachedRenderer is None:
  1548. raise AttributeError("draw_artist can only be used after an "
  1549. "initial draw which caches the renderer")
  1550. a.draw(self._cachedRenderer)
  1551. # Note: in the docstring below, the newlines in the examples after the
  1552. # calls to legend() allow replacing it with figlegend() to generate the
  1553. # docstring of pyplot.figlegend.
  1554. @docstring.dedent_interpd
  1555. def legend(self, *args, **kwargs):
  1556. """
  1557. Place a legend on the figure.
  1558. To make a legend from existing artists on every axes::
  1559. legend()
  1560. To make a legend for a list of lines and labels::
  1561. legend(
  1562. (line1, line2, line3),
  1563. ('label1', 'label2', 'label3'),
  1564. loc='upper right')
  1565. These can also be specified by keyword::
  1566. legend(
  1567. handles=(line1, line2, line3),
  1568. labels=('label1', 'label2', 'label3'),
  1569. loc='upper right')
  1570. Parameters
  1571. ----------
  1572. handles : list of `.Artist`, optional
  1573. A list of Artists (lines, patches) to be added to the legend.
  1574. Use this together with *labels*, if you need full control on what
  1575. is shown in the legend and the automatic mechanism described above
  1576. is not sufficient.
  1577. The length of handles and labels should be the same in this
  1578. case. If they are not, they are truncated to the smaller length.
  1579. labels : list of str, optional
  1580. A list of labels to show next to the artists.
  1581. Use this together with *handles*, if you need full control on what
  1582. is shown in the legend and the automatic mechanism described above
  1583. is not sufficient.
  1584. Returns
  1585. -------
  1586. `~matplotlib.legend.Legend`
  1587. Other Parameters
  1588. ----------------
  1589. %(_legend_kw_doc)s
  1590. Notes
  1591. -----
  1592. Some artists are not supported by this function. See
  1593. :doc:`/tutorials/intermediate/legend_guide` for details.
  1594. """
  1595. handles, labels, extra_args, kwargs = mlegend._parse_legend_args(
  1596. self.axes,
  1597. *args,
  1598. **kwargs)
  1599. # check for third arg
  1600. if len(extra_args):
  1601. # cbook.warn_deprecated(
  1602. # "2.1",
  1603. # message="Figure.legend will accept no more than two "
  1604. # "positional arguments in the future. Use "
  1605. # "'fig.legend(handles, labels, loc=location)' "
  1606. # "instead.")
  1607. # kwargs['loc'] = extra_args[0]
  1608. # extra_args = extra_args[1:]
  1609. pass
  1610. transform = kwargs.pop('bbox_transform', self.transFigure)
  1611. # explicitly set the bbox transform if the user hasn't.
  1612. l = mlegend.Legend(self, handles, labels, *extra_args,
  1613. bbox_transform=transform, **kwargs)
  1614. self.legends.append(l)
  1615. l._remove_method = self.legends.remove
  1616. self.stale = True
  1617. return l
  1618. @docstring.dedent_interpd
  1619. def text(self, x, y, s, fontdict=None, **kwargs):
  1620. """
  1621. Add text to figure.
  1622. Parameters
  1623. ----------
  1624. x, y : float
  1625. The position to place the text. By default, this is in figure
  1626. coordinates, floats in [0, 1]. The coordinate system can be changed
  1627. using the *transform* keyword.
  1628. s : str
  1629. The text string.
  1630. fontdict : dict, optional
  1631. A dictionary to override the default text properties. If not given,
  1632. the defaults are determined by :rc:`font.*`. Properties passed as
  1633. *kwargs* override the corresponding ones given in *fontdict*.
  1634. Returns
  1635. -------
  1636. `~.text.Text`
  1637. Other Parameters
  1638. ----------------
  1639. **kwargs : `~matplotlib.text.Text` properties
  1640. Other miscellaneous text parameters.
  1641. %(Text)s
  1642. See Also
  1643. --------
  1644. .Axes.text
  1645. .pyplot.text
  1646. """
  1647. effective_kwargs = {
  1648. 'transform': self.transFigure,
  1649. **(fontdict if fontdict is not None else {}),
  1650. **kwargs,
  1651. }
  1652. text = Text(x=x, y=y, text=s, **effective_kwargs)
  1653. text.set_figure(self)
  1654. text.stale_callback = _stale_figure_callback
  1655. self.texts.append(text)
  1656. text._remove_method = self.texts.remove
  1657. self.stale = True
  1658. return text
  1659. def _set_artist_props(self, a):
  1660. if a != self:
  1661. a.set_figure(self)
  1662. a.stale_callback = _stale_figure_callback
  1663. a.set_transform(self.transFigure)
  1664. @docstring.dedent_interpd
  1665. def gca(self, **kwargs):
  1666. """
  1667. Get the current axes, creating one if necessary.
  1668. The following kwargs are supported for ensuring the returned axes
  1669. adheres to the given projection etc., and for axes creation if
  1670. the active axes does not exist:
  1671. %(Axes)s
  1672. """
  1673. ckey, cax = self._axstack.current_key_axes()
  1674. # if there exists an axes on the stack see if it matches
  1675. # the desired axes configuration
  1676. if cax is not None:
  1677. # if no kwargs are given just return the current axes
  1678. # this is a convenience for gca() on axes such as polar etc.
  1679. if not kwargs:
  1680. return cax
  1681. # if the user has specified particular projection detail
  1682. # then build up a key which can represent this
  1683. else:
  1684. projection_class, _, key = \
  1685. self._process_projection_requirements(**kwargs)
  1686. # let the returned axes have any gridspec by removing it from
  1687. # the key
  1688. ckey = ckey[1:]
  1689. key = key[1:]
  1690. # if the cax matches this key then return the axes, otherwise
  1691. # continue and a new axes will be created
  1692. if key == ckey and isinstance(cax, projection_class):
  1693. return cax
  1694. else:
  1695. cbook._warn_external('Requested projection is different '
  1696. 'from current axis projection, '
  1697. 'creating new axis with requested '
  1698. 'projection.')
  1699. # no axes found, so create one which spans the figure
  1700. return self.add_subplot(1, 1, 1, **kwargs)
  1701. def sca(self, a):
  1702. """Set the current axes to be *a* and return *a*."""
  1703. self._axstack.bubble(a)
  1704. self._axobservers.process("_axes_change_event", self)
  1705. return a
  1706. def _gci(self):
  1707. # Helper for `~matplotlib.pyplot.gci`. Do not use elsewhere.
  1708. """
  1709. Get the current colorable artist.
  1710. Specifically, returns the current `.ScalarMappable` instance (`.Image`
  1711. created by `imshow` or `figimage`, `.Collection` created by `pcolor` or
  1712. `scatter`, etc.), or *None* if no such instance has been defined.
  1713. The current image is an attribute of the current axes, or the nearest
  1714. earlier axes in the current figure that contains an image.
  1715. Notes
  1716. -----
  1717. Historically, the only colorable artists were images; hence the name
  1718. ``gci`` (get current image).
  1719. """
  1720. # Look first for an image in the current Axes:
  1721. cax = self._axstack.current_key_axes()[1]
  1722. if cax is None:
  1723. return None
  1724. im = cax._gci()
  1725. if im is not None:
  1726. return im
  1727. # If there is no image in the current Axes, search for
  1728. # one in a previously created Axes. Whether this makes
  1729. # sense is debatable, but it is the documented behavior.
  1730. for ax in reversed(self.axes):
  1731. im = ax._gci()
  1732. if im is not None:
  1733. return im
  1734. return None
  1735. def __getstate__(self):
  1736. state = super().__getstate__()
  1737. # The canvas cannot currently be pickled, but this has the benefit
  1738. # of meaning that a figure can be detached from one canvas, and
  1739. # re-attached to another.
  1740. state.pop("canvas")
  1741. # Set cached renderer to None -- it can't be pickled.
  1742. state["_cachedRenderer"] = None
  1743. # add version information to the state
  1744. state['__mpl_version__'] = _mpl_version
  1745. # check whether the figure manager (if any) is registered with pyplot
  1746. from matplotlib import _pylab_helpers
  1747. if getattr(self.canvas, 'manager', None) \
  1748. in _pylab_helpers.Gcf.figs.values():
  1749. state['_restore_to_pylab'] = True
  1750. # set all the layoutbox information to None. kiwisolver objects can't
  1751. # be pickled, so we lose the layout options at this point.
  1752. state.pop('_layoutbox', None)
  1753. # suptitle:
  1754. if self._suptitle is not None:
  1755. self._suptitle._layoutbox = None
  1756. return state
  1757. def __setstate__(self, state):
  1758. version = state.pop('__mpl_version__')
  1759. restore_to_pylab = state.pop('_restore_to_pylab', False)
  1760. if version != _mpl_version:
  1761. cbook._warn_external(
  1762. f"This figure was saved with matplotlib version {version} and "
  1763. f"is unlikely to function correctly.")
  1764. self.__dict__ = state
  1765. # re-initialise some of the unstored state information
  1766. FigureCanvasBase(self) # Set self.canvas.
  1767. self._layoutbox = None
  1768. if restore_to_pylab:
  1769. # lazy import to avoid circularity
  1770. import matplotlib.pyplot as plt
  1771. import matplotlib._pylab_helpers as pylab_helpers
  1772. allnums = plt.get_fignums()
  1773. num = max(allnums) + 1 if allnums else 1
  1774. mgr = plt._backend_mod.new_figure_manager_given_figure(num, self)
  1775. pylab_helpers.Gcf._set_new_active_manager(mgr)
  1776. plt.draw_if_interactive()
  1777. self.stale = True
  1778. def add_axobserver(self, func):
  1779. """Whenever the axes state change, ``func(self)`` will be called."""
  1780. # Connect a wrapper lambda and not func itself, to avoid it being
  1781. # weakref-collected.
  1782. self._axobservers.connect("_axes_change_event", lambda arg: func(arg))
  1783. def savefig(self, fname, *, transparent=None, **kwargs):
  1784. """
  1785. Save the current figure.
  1786. Call signature::
  1787. savefig(fname, dpi=None, facecolor='w', edgecolor='w',
  1788. orientation='portrait', papertype=None, format=None,
  1789. transparent=False, bbox_inches=None, pad_inches=0.1,
  1790. frameon=None, metadata=None)
  1791. The available output formats depend on the backend being used.
  1792. Parameters
  1793. ----------
  1794. fname : str or path-like or file-like
  1795. A path, or a Python file-like object, or
  1796. possibly some backend-dependent object such as
  1797. `matplotlib.backends.backend_pdf.PdfPages`.
  1798. If *format* is set, it determines the output format, and the file
  1799. is saved as *fname*. Note that *fname* is used verbatim, and there
  1800. is no attempt to make the extension, if any, of *fname* match
  1801. *format*, and no extension is appended.
  1802. If *format* is not set, then the format is inferred from the
  1803. extension of *fname*, if there is one. If *format* is not
  1804. set and *fname* has no extension, then the file is saved with
  1805. :rc:`savefig.format` and the appropriate extension is appended to
  1806. *fname*.
  1807. Other Parameters
  1808. ----------------
  1809. dpi : float or 'figure', default: :rc:`savefig.dpi`
  1810. The resolution in dots per inch. If 'figure', use the figure's
  1811. dpi value.
  1812. quality : int, default: :rc:`savefig.jpeg_quality`
  1813. Applicable only if *format* is 'jpg' or 'jpeg', ignored otherwise.
  1814. The image quality, on a scale from 1 (worst) to 95 (best).
  1815. Values above 95 should be avoided; 100 disables portions of
  1816. the JPEG compression algorithm, and results in large files
  1817. with hardly any gain in image quality.
  1818. This parameter is deprecated.
  1819. optimize : bool, default: False
  1820. Applicable only if *format* is 'jpg' or 'jpeg', ignored otherwise.
  1821. Whether the encoder should make an extra pass over the image
  1822. in order to select optimal encoder settings.
  1823. This parameter is deprecated.
  1824. progressive : bool, default: False
  1825. Applicable only if *format* is 'jpg' or 'jpeg', ignored otherwise.
  1826. Whether the image should be stored as a progressive JPEG file.
  1827. This parameter is deprecated.
  1828. facecolor : color or 'auto', default: :rc:`savefig.facecolor`
  1829. The facecolor of the figure. If 'auto', use the current figure
  1830. facecolor.
  1831. edgecolor : color or 'auto', default: :rc:`savefig.edgecolor`
  1832. The edgecolor of the figure. If 'auto', use the current figure
  1833. edgecolor.
  1834. orientation : {'landscape', 'portrait'}
  1835. Currently only supported by the postscript backend.
  1836. papertype : str
  1837. One of 'letter', 'legal', 'executive', 'ledger', 'a0' through
  1838. 'a10', 'b0' through 'b10'. Only supported for postscript
  1839. output.
  1840. format : str
  1841. The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when
  1842. this is unset is documented under *fname*.
  1843. transparent : bool
  1844. If *True*, the axes patches will all be transparent; the
  1845. figure patch will also be transparent unless facecolor
  1846. and/or edgecolor are specified via kwargs.
  1847. This is useful, for example, for displaying
  1848. a plot on top of a colored background on a web page. The
  1849. transparency of these patches will be restored to their
  1850. original values upon exit of this function.
  1851. bbox_inches : str or `.Bbox`, default: :rc:`savefig.bbox`
  1852. Bounding box in inches: only the given portion of the figure is
  1853. saved. If 'tight', try to figure out the tight bbox of the figure.
  1854. pad_inches : float, default: :rc:`savefig.pad_inches`
  1855. Amount of padding around the figure when bbox_inches is 'tight'.
  1856. bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
  1857. A list of extra artists that will be considered when the
  1858. tight bbox is calculated.
  1859. backend : str, optional
  1860. Use a non-default backend to render the file, e.g. to render a
  1861. png file with the "cairo" backend rather than the default "agg",
  1862. or a pdf file with the "pgf" backend rather than the default
  1863. "pdf". Note that the default backend is normally sufficient. See
  1864. :ref:`the-builtin-backends` for a list of valid backends for each
  1865. file format. Custom backends can be referenced as "module://...".
  1866. metadata : dict, optional
  1867. Key/value pairs to store in the image metadata. The supported keys
  1868. and defaults depend on the image format and backend:
  1869. - 'png' with Agg backend: See the parameter ``metadata`` of
  1870. `~.FigureCanvasAgg.print_png`.
  1871. - 'pdf' with pdf backend: See the parameter ``metadata`` of
  1872. `~.backend_pdf.PdfPages`.
  1873. - 'svg' with svg backend: See the parameter ``metadata`` of
  1874. `~.FigureCanvasSVG.print_svg`.
  1875. - 'eps' and 'ps' with PS backend: Only 'Creator' is supported.
  1876. pil_kwargs : dict, optional
  1877. Additional keyword arguments that are passed to
  1878. `PIL.Image.Image.save` when saving the figure.
  1879. """
  1880. kwargs.setdefault('dpi', mpl.rcParams['savefig.dpi'])
  1881. if transparent is None:
  1882. transparent = mpl.rcParams['savefig.transparent']
  1883. if transparent:
  1884. kwargs.setdefault('facecolor', 'none')
  1885. kwargs.setdefault('edgecolor', 'none')
  1886. original_axes_colors = []
  1887. for ax in self.axes:
  1888. patch = ax.patch
  1889. original_axes_colors.append((patch.get_facecolor(),
  1890. patch.get_edgecolor()))
  1891. patch.set_facecolor('none')
  1892. patch.set_edgecolor('none')
  1893. self.canvas.print_figure(fname, **kwargs)
  1894. if transparent:
  1895. for ax, cc in zip(self.axes, original_axes_colors):
  1896. ax.patch.set_facecolor(cc[0])
  1897. ax.patch.set_edgecolor(cc[1])
  1898. @docstring.dedent_interpd
  1899. def colorbar(self, mappable, cax=None, ax=None, use_gridspec=True, **kw):
  1900. """
  1901. Create a colorbar for a ScalarMappable instance, *mappable*.
  1902. Documentation for the pyplot thin wrapper:
  1903. %(colorbar_doc)s
  1904. """
  1905. if ax is None:
  1906. ax = self.gca()
  1907. # Store the value of gca so that we can set it back later on.
  1908. current_ax = self.gca()
  1909. if cax is None:
  1910. if use_gridspec and isinstance(ax, SubplotBase) \
  1911. and (not self.get_constrained_layout()):
  1912. cax, kw = cbar.make_axes_gridspec(ax, **kw)
  1913. else:
  1914. cax, kw = cbar.make_axes(ax, **kw)
  1915. # need to remove kws that cannot be passed to Colorbar
  1916. NON_COLORBAR_KEYS = ['fraction', 'pad', 'shrink', 'aspect', 'anchor',
  1917. 'panchor']
  1918. cb_kw = {k: v for k, v in kw.items() if k not in NON_COLORBAR_KEYS}
  1919. cb = cbar.colorbar_factory(cax, mappable, **cb_kw)
  1920. self.sca(current_ax)
  1921. self.stale = True
  1922. return cb
  1923. def subplots_adjust(self, left=None, bottom=None, right=None, top=None,
  1924. wspace=None, hspace=None):
  1925. """
  1926. Adjust the subplot layout parameters.
  1927. Unset parameters are left unmodified; initial values are given by
  1928. :rc:`figure.subplot.[name]`.
  1929. Parameters
  1930. ----------
  1931. left : float, optional
  1932. The position of the left edge of the subplots,
  1933. as a fraction of the figure width.
  1934. right : float, optional
  1935. The position of the right edge of the subplots,
  1936. as a fraction of the figure width.
  1937. bottom : float, optional
  1938. The position of the bottom edge of the subplots,
  1939. as a fraction of the figure height.
  1940. top : float, optional
  1941. The position of the top edge of the subplots,
  1942. as a fraction of the figure height.
  1943. wspace : float, optional
  1944. The width of the padding between subplots,
  1945. as a fraction of the average axes width.
  1946. hspace : float, optional
  1947. The height of the padding between subplots,
  1948. as a fraction of the average axes height.
  1949. """
  1950. if self.get_constrained_layout():
  1951. self.set_constrained_layout(False)
  1952. cbook._warn_external("This figure was using "
  1953. "constrained_layout==True, but that is "
  1954. "incompatible with subplots_adjust and or "
  1955. "tight_layout: setting "
  1956. "constrained_layout==False. ")
  1957. self.subplotpars.update(left, bottom, right, top, wspace, hspace)
  1958. for ax in self.axes:
  1959. if not isinstance(ax, SubplotBase):
  1960. # Check if sharing a subplots axis
  1961. if isinstance(ax._sharex, SubplotBase):
  1962. ax._sharex.update_params()
  1963. ax.set_position(ax._sharex.figbox)
  1964. elif isinstance(ax._sharey, SubplotBase):
  1965. ax._sharey.update_params()
  1966. ax.set_position(ax._sharey.figbox)
  1967. else:
  1968. ax.update_params()
  1969. ax.set_position(ax.figbox)
  1970. self.stale = True
  1971. def ginput(self, n=1, timeout=30, show_clicks=True,
  1972. mouse_add=MouseButton.LEFT,
  1973. mouse_pop=MouseButton.RIGHT,
  1974. mouse_stop=MouseButton.MIDDLE):
  1975. """
  1976. Blocking call to interact with a figure.
  1977. Wait until the user clicks *n* times on the figure, and return the
  1978. coordinates of each click in a list.
  1979. There are three possible interactions:
  1980. - Add a point.
  1981. - Remove the most recently added point.
  1982. - Stop the interaction and return the points added so far.
  1983. The actions are assigned to mouse buttons via the arguments
  1984. *mouse_add*, *mouse_pop* and *mouse_stop*.
  1985. Parameters
  1986. ----------
  1987. n : int, default: 1
  1988. Number of mouse clicks to accumulate. If negative, accumulate
  1989. clicks until the input is terminated manually.
  1990. timeout : float, default: 30 seconds
  1991. Number of seconds to wait before timing out. If zero or negative
  1992. will never timeout.
  1993. show_clicks : bool, default: True
  1994. If True, show a red cross at the location of each click.
  1995. mouse_add : `.MouseButton` or None, default: `.MouseButton.LEFT`
  1996. Mouse button used to add points.
  1997. mouse_pop : `.MouseButton` or None, default: `.MouseButton.RIGHT`
  1998. Mouse button used to remove the most recently added point.
  1999. mouse_stop : `.MouseButton` or None, default: `.MouseButton.MIDDLE`
  2000. Mouse button used to stop input.
  2001. Returns
  2002. -------
  2003. list of tuples
  2004. A list of the clicked (x, y) coordinates.
  2005. Notes
  2006. -----
  2007. The keyboard can also be used to select points in case your mouse
  2008. does not have one or more of the buttons. The delete and backspace
  2009. keys act like right clicking (i.e., remove last point), the enter key
  2010. terminates input and any other key (not already used by the window
  2011. manager) selects a point.
  2012. """
  2013. blocking_mouse_input = BlockingMouseInput(self,
  2014. mouse_add=mouse_add,
  2015. mouse_pop=mouse_pop,
  2016. mouse_stop=mouse_stop)
  2017. return blocking_mouse_input(n=n, timeout=timeout,
  2018. show_clicks=show_clicks)
  2019. def waitforbuttonpress(self, timeout=-1):
  2020. """
  2021. Blocking call to interact with the figure.
  2022. Wait for user input and return True if a key was pressed, False if a
  2023. mouse button was pressed and None if no input was given within
  2024. *timeout* seconds. Negative values deactivate *timeout*.
  2025. """
  2026. blocking_input = BlockingKeyMouseInput(self)
  2027. return blocking_input(timeout=timeout)
  2028. def get_default_bbox_extra_artists(self):
  2029. bbox_artists = [artist for artist in self.get_children()
  2030. if (artist.get_visible() and artist.get_in_layout())]
  2031. for ax in self.axes:
  2032. if ax.get_visible():
  2033. bbox_artists.extend(ax.get_default_bbox_extra_artists())
  2034. return bbox_artists
  2035. def get_tightbbox(self, renderer, bbox_extra_artists=None):
  2036. """
  2037. Return a (tight) bounding box of the figure in inches.
  2038. Artists that have ``artist.set_in_layout(False)`` are not included
  2039. in the bbox.
  2040. Parameters
  2041. ----------
  2042. renderer : `.RendererBase` subclass
  2043. renderer that will be used to draw the figures (i.e.
  2044. ``fig.canvas.get_renderer()``)
  2045. bbox_extra_artists : list of `.Artist` or ``None``
  2046. List of artists to include in the tight bounding box. If
  2047. ``None`` (default), then all artist children of each axes are
  2048. included in the tight bounding box.
  2049. Returns
  2050. -------
  2051. `.BboxBase`
  2052. containing the bounding box (in figure inches).
  2053. """
  2054. bb = []
  2055. if bbox_extra_artists is None:
  2056. artists = self.get_default_bbox_extra_artists()
  2057. else:
  2058. artists = bbox_extra_artists
  2059. for a in artists:
  2060. bbox = a.get_tightbbox(renderer)
  2061. if bbox is not None and (bbox.width != 0 or bbox.height != 0):
  2062. bb.append(bbox)
  2063. for ax in self.axes:
  2064. if ax.get_visible():
  2065. # some axes don't take the bbox_extra_artists kwarg so we
  2066. # need this conditional....
  2067. try:
  2068. bbox = ax.get_tightbbox(
  2069. renderer, bbox_extra_artists=bbox_extra_artists)
  2070. except TypeError:
  2071. bbox = ax.get_tightbbox(renderer)
  2072. bb.append(bbox)
  2073. bb = [b for b in bb
  2074. if (np.isfinite(b.width) and np.isfinite(b.height)
  2075. and (b.width != 0 or b.height != 0))]
  2076. if len(bb) == 0:
  2077. return self.bbox_inches
  2078. _bbox = Bbox.union(bb)
  2079. bbox_inches = TransformedBbox(_bbox, Affine2D().scale(1 / self.dpi))
  2080. return bbox_inches
  2081. def init_layoutbox(self):
  2082. """Initialize the layoutbox for use in constrained_layout."""
  2083. if self._layoutbox is None:
  2084. self._layoutbox = layoutbox.LayoutBox(
  2085. parent=None, name='figlb', artist=self)
  2086. self._layoutbox.constrain_geometry(0., 0., 1., 1.)
  2087. def execute_constrained_layout(self, renderer=None):
  2088. """
  2089. Use ``layoutbox`` to determine pos positions within axes.
  2090. See also `.set_constrained_layout_pads`.
  2091. """
  2092. from matplotlib._constrained_layout import do_constrained_layout
  2093. _log.debug('Executing constrainedlayout')
  2094. if self._layoutbox is None:
  2095. cbook._warn_external("Calling figure.constrained_layout, but "
  2096. "figure not setup to do constrained layout. "
  2097. " You either called GridSpec without the "
  2098. "fig keyword, you are using plt.subplot, "
  2099. "or you need to call figure or subplots "
  2100. "with the constrained_layout=True kwarg.")
  2101. return
  2102. w_pad, h_pad, wspace, hspace = self.get_constrained_layout_pads()
  2103. # convert to unit-relative lengths
  2104. fig = self
  2105. width, height = fig.get_size_inches()
  2106. w_pad = w_pad / width
  2107. h_pad = h_pad / height
  2108. if renderer is None:
  2109. renderer = layoutbox.get_renderer(fig)
  2110. do_constrained_layout(fig, renderer, h_pad, w_pad, hspace, wspace)
  2111. @cbook._delete_parameter("3.2", "renderer")
  2112. def tight_layout(self, renderer=None, pad=1.08, h_pad=None, w_pad=None,
  2113. rect=None):
  2114. """
  2115. Adjust the padding between and around subplots.
  2116. To exclude an artist on the axes from the bounding box calculation
  2117. that determines the subplot parameters (i.e. legend, or annotation),
  2118. set ``a.set_in_layout(False)`` for that artist.
  2119. Parameters
  2120. ----------
  2121. renderer : subclass of `~.backend_bases.RendererBase`, optional
  2122. Defaults to the renderer for the figure. Deprecated.
  2123. pad : float, default: 1.08
  2124. Padding between the figure edge and the edges of subplots,
  2125. as a fraction of the font size.
  2126. h_pad, w_pad : float, default: *pad*
  2127. Padding (height/width) between edges of adjacent subplots,
  2128. as a fraction of the font size.
  2129. rect : tuple (left, bottom, right, top), default: (0, 0, 1, 1)
  2130. A rectangle in normalized figure coordinates into which the whole
  2131. subplots area (including labels) will fit.
  2132. See Also
  2133. --------
  2134. .Figure.set_tight_layout
  2135. .pyplot.tight_layout
  2136. """
  2137. from .tight_layout import (
  2138. get_renderer, get_subplotspec_list, get_tight_layout_figure)
  2139. from contextlib import suppress
  2140. subplotspec_list = get_subplotspec_list(self.axes)
  2141. if None in subplotspec_list:
  2142. cbook._warn_external("This figure includes Axes that are not "
  2143. "compatible with tight_layout, so results "
  2144. "might be incorrect.")
  2145. if renderer is None:
  2146. renderer = get_renderer(self)
  2147. ctx = (renderer._draw_disabled()
  2148. if hasattr(renderer, '_draw_disabled')
  2149. else suppress())
  2150. with ctx:
  2151. kwargs = get_tight_layout_figure(
  2152. self, self.axes, subplotspec_list, renderer,
  2153. pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
  2154. if kwargs:
  2155. self.subplots_adjust(**kwargs)
  2156. def align_xlabels(self, axs=None):
  2157. """
  2158. Align the xlabels of subplots in the same subplot column if label
  2159. alignment is being done automatically (i.e. the label position is
  2160. not manually set).
  2161. Alignment persists for draw events after this is called.
  2162. If a label is on the bottom, it is aligned with labels on axes that
  2163. also have their label on the bottom and that have the same
  2164. bottom-most subplot row. If the label is on the top,
  2165. it is aligned with labels on axes with the same top-most row.
  2166. Parameters
  2167. ----------
  2168. axs : list of `~matplotlib.axes.Axes`
  2169. Optional list of (or ndarray) `~matplotlib.axes.Axes`
  2170. to align the xlabels.
  2171. Default is to align all axes on the figure.
  2172. See Also
  2173. --------
  2174. matplotlib.figure.Figure.align_ylabels
  2175. matplotlib.figure.Figure.align_labels
  2176. Notes
  2177. -----
  2178. This assumes that ``axs`` are from the same `.GridSpec`, so that
  2179. their `.SubplotSpec` positions correspond to figure positions.
  2180. Examples
  2181. --------
  2182. Example with rotated xtick labels::
  2183. fig, axs = plt.subplots(1, 2)
  2184. for tick in axs[0].get_xticklabels():
  2185. tick.set_rotation(55)
  2186. axs[0].set_xlabel('XLabel 0')
  2187. axs[1].set_xlabel('XLabel 1')
  2188. fig.align_xlabels()
  2189. """
  2190. if axs is None:
  2191. axs = self.axes
  2192. axs = np.ravel(axs)
  2193. for ax in axs:
  2194. _log.debug(' Working on: %s', ax.get_xlabel())
  2195. rowspan = ax.get_subplotspec().rowspan
  2196. pos = ax.xaxis.get_label_position() # top or bottom
  2197. # Search through other axes for label positions that are same as
  2198. # this one and that share the appropriate row number.
  2199. # Add to a grouper associated with each axes of siblings.
  2200. # This list is inspected in `axis.draw` by
  2201. # `axis._update_label_position`.
  2202. for axc in axs:
  2203. if axc.xaxis.get_label_position() == pos:
  2204. rowspanc = axc.get_subplotspec().rowspan
  2205. if (pos == 'top' and rowspan.start == rowspanc.start or
  2206. pos == 'bottom' and rowspan.stop == rowspanc.stop):
  2207. # grouper for groups of xlabels to align
  2208. self._align_xlabel_grp.join(ax, axc)
  2209. def align_ylabels(self, axs=None):
  2210. """
  2211. Align the ylabels of subplots in the same subplot column if label
  2212. alignment is being done automatically (i.e. the label position is
  2213. not manually set).
  2214. Alignment persists for draw events after this is called.
  2215. If a label is on the left, it is aligned with labels on axes that
  2216. also have their label on the left and that have the same
  2217. left-most subplot column. If the label is on the right,
  2218. it is aligned with labels on axes with the same right-most column.
  2219. Parameters
  2220. ----------
  2221. axs : list of `~matplotlib.axes.Axes`
  2222. Optional list (or ndarray) of `~matplotlib.axes.Axes`
  2223. to align the ylabels.
  2224. Default is to align all axes on the figure.
  2225. See Also
  2226. --------
  2227. matplotlib.figure.Figure.align_xlabels
  2228. matplotlib.figure.Figure.align_labels
  2229. Notes
  2230. -----
  2231. This assumes that ``axs`` are from the same `.GridSpec`, so that
  2232. their `.SubplotSpec` positions correspond to figure positions.
  2233. Examples
  2234. --------
  2235. Example with large yticks labels::
  2236. fig, axs = plt.subplots(2, 1)
  2237. axs[0].plot(np.arange(0, 1000, 50))
  2238. axs[0].set_ylabel('YLabel 0')
  2239. axs[1].set_ylabel('YLabel 1')
  2240. fig.align_ylabels()
  2241. """
  2242. if axs is None:
  2243. axs = self.axes
  2244. axs = np.ravel(axs)
  2245. for ax in axs:
  2246. _log.debug(' Working on: %s', ax.get_ylabel())
  2247. colspan = ax.get_subplotspec().colspan
  2248. pos = ax.yaxis.get_label_position() # left or right
  2249. # Search through other axes for label positions that are same as
  2250. # this one and that share the appropriate column number.
  2251. # Add to a list associated with each axes of siblings.
  2252. # This list is inspected in `axis.draw` by
  2253. # `axis._update_label_position`.
  2254. for axc in axs:
  2255. if axc.yaxis.get_label_position() == pos:
  2256. colspanc = axc.get_subplotspec().colspan
  2257. if (pos == 'left' and colspan.start == colspanc.start or
  2258. pos == 'right' and colspan.stop == colspanc.stop):
  2259. # grouper for groups of ylabels to align
  2260. self._align_ylabel_grp.join(ax, axc)
  2261. def align_labels(self, axs=None):
  2262. """
  2263. Align the xlabels and ylabels of subplots with the same subplots
  2264. row or column (respectively) if label alignment is being
  2265. done automatically (i.e. the label position is not manually set).
  2266. Alignment persists for draw events after this is called.
  2267. Parameters
  2268. ----------
  2269. axs : list of `~matplotlib.axes.Axes`
  2270. Optional list (or ndarray) of `~matplotlib.axes.Axes`
  2271. to align the labels.
  2272. Default is to align all axes on the figure.
  2273. See Also
  2274. --------
  2275. matplotlib.figure.Figure.align_xlabels
  2276. matplotlib.figure.Figure.align_ylabels
  2277. """
  2278. self.align_xlabels(axs=axs)
  2279. self.align_ylabels(axs=axs)
  2280. def add_gridspec(self, nrows=1, ncols=1, **kwargs):
  2281. """
  2282. Return a `.GridSpec` that has this figure as a parent. This allows
  2283. complex layout of axes in the figure.
  2284. Parameters
  2285. ----------
  2286. nrows : int, default: 1
  2287. Number of rows in grid.
  2288. ncols : int, default: 1
  2289. Number or columns in grid.
  2290. Returns
  2291. -------
  2292. `.GridSpec`
  2293. Other Parameters
  2294. ----------------
  2295. **kwargs
  2296. Keyword arguments are passed to `.GridSpec`.
  2297. See Also
  2298. --------
  2299. matplotlib.pyplot.subplots
  2300. Examples
  2301. --------
  2302. Adding a subplot that spans two rows::
  2303. fig = plt.figure()
  2304. gs = fig.add_gridspec(2, 2)
  2305. ax1 = fig.add_subplot(gs[0, 0])
  2306. ax2 = fig.add_subplot(gs[1, 0])
  2307. # spans two rows:
  2308. ax3 = fig.add_subplot(gs[:, 1])
  2309. """
  2310. _ = kwargs.pop('figure', None) # pop in case user has added this...
  2311. gs = GridSpec(nrows=nrows, ncols=ncols, figure=self, **kwargs)
  2312. self._gridspecs.append(gs)
  2313. return gs
  2314. def figaspect(arg):
  2315. """
  2316. Calculate the width and height for a figure with a specified aspect ratio.
  2317. While the height is taken from :rc:`figure.figsize`, the width is
  2318. adjusted to match the desired aspect ratio. Additionally, it is ensured
  2319. that the width is in the range [4., 16.] and the height is in the range
  2320. [2., 16.]. If necessary, the default height is adjusted to ensure this.
  2321. Parameters
  2322. ----------
  2323. arg : float or 2d array
  2324. If a float, this defines the aspect ratio (i.e. the ratio height /
  2325. width).
  2326. In case of an array the aspect ratio is number of rows / number of
  2327. columns, so that the array could be fitted in the figure undistorted.
  2328. Returns
  2329. -------
  2330. width, height
  2331. The figure size in inches.
  2332. Notes
  2333. -----
  2334. If you want to create an axes within the figure, that still preserves the
  2335. aspect ratio, be sure to create it with equal width and height. See
  2336. examples below.
  2337. Thanks to Fernando Perez for this function.
  2338. Examples
  2339. --------
  2340. Make a figure twice as tall as it is wide::
  2341. w, h = figaspect(2.)
  2342. fig = Figure(figsize=(w, h))
  2343. ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
  2344. ax.imshow(A, **kwargs)
  2345. Make a figure with the proper aspect for an array::
  2346. A = rand(5, 3)
  2347. w, h = figaspect(A)
  2348. fig = Figure(figsize=(w, h))
  2349. ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
  2350. ax.imshow(A, **kwargs)
  2351. """
  2352. isarray = hasattr(arg, 'shape') and not np.isscalar(arg)
  2353. # min/max sizes to respect when autoscaling. If John likes the idea, they
  2354. # could become rc parameters, for now they're hardwired.
  2355. figsize_min = np.array((4.0, 2.0)) # min length for width/height
  2356. figsize_max = np.array((16.0, 16.0)) # max length for width/height
  2357. # Extract the aspect ratio of the array
  2358. if isarray:
  2359. nr, nc = arg.shape[:2]
  2360. arr_ratio = nr / nc
  2361. else:
  2362. arr_ratio = arg
  2363. # Height of user figure defaults
  2364. fig_height = mpl.rcParams['figure.figsize'][1]
  2365. # New size for the figure, keeping the aspect ratio of the caller
  2366. newsize = np.array((fig_height / arr_ratio, fig_height))
  2367. # Sanity checks, don't drop either dimension below figsize_min
  2368. newsize /= min(1.0, *(newsize / figsize_min))
  2369. # Avoid humongous windows as well
  2370. newsize /= max(1.0, *(newsize / figsize_max))
  2371. # Finally, if we have a really funky aspect ratio, break it but respect
  2372. # the min/max dimensions (we don't want figures 10 feet tall!)
  2373. newsize = np.clip(newsize, figsize_min, figsize_max)
  2374. return newsize
  2375. docstring.interpd.update(Figure=martist.kwdoc(Figure))