figure.py 99 KB

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