You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2663 lines
93 KiB

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