gridspec.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. r"""
  2. :mod:`~matplotlib.gridspec` contains classes that help to layout multiple
  3. `~.axes.Axes` in a grid-like pattern within a figure.
  4. The `GridSpec` specifies the overall grid structure. Individual cells within
  5. the grid are referenced by `SubplotSpec`\s.
  6. Often, users need not access this module directly, and can use higher-level
  7. methods like `~.pyplot.subplots`, `~.pyplot.subplot_mosaic` and
  8. `~.Figure.subfigures`. See the tutorial :ref:`arranging_axes` for a guide.
  9. """
  10. import copy
  11. import logging
  12. from numbers import Integral
  13. import numpy as np
  14. import matplotlib as mpl
  15. from matplotlib import _api, _pylab_helpers, _tight_layout
  16. from matplotlib.transforms import Bbox
  17. _log = logging.getLogger(__name__)
  18. class GridSpecBase:
  19. """
  20. A base class of GridSpec that specifies the geometry of the grid
  21. that a subplot will be placed.
  22. """
  23. def __init__(self, nrows, ncols, height_ratios=None, width_ratios=None):
  24. """
  25. Parameters
  26. ----------
  27. nrows, ncols : int
  28. The number of rows and columns of the grid.
  29. width_ratios : array-like of length *ncols*, optional
  30. Defines the relative widths of the columns. Each column gets a
  31. relative width of ``width_ratios[i] / sum(width_ratios)``.
  32. If not given, all columns will have the same width.
  33. height_ratios : array-like of length *nrows*, optional
  34. Defines the relative heights of the rows. Each row gets a
  35. relative height of ``height_ratios[i] / sum(height_ratios)``.
  36. If not given, all rows will have the same height.
  37. """
  38. if not isinstance(nrows, Integral) or nrows <= 0:
  39. raise ValueError(
  40. f"Number of rows must be a positive integer, not {nrows!r}")
  41. if not isinstance(ncols, Integral) or ncols <= 0:
  42. raise ValueError(
  43. f"Number of columns must be a positive integer, not {ncols!r}")
  44. self._nrows, self._ncols = nrows, ncols
  45. self.set_height_ratios(height_ratios)
  46. self.set_width_ratios(width_ratios)
  47. def __repr__(self):
  48. height_arg = (f', height_ratios={self._row_height_ratios!r}'
  49. if len(set(self._row_height_ratios)) != 1 else '')
  50. width_arg = (f', width_ratios={self._col_width_ratios!r}'
  51. if len(set(self._col_width_ratios)) != 1 else '')
  52. return '{clsname}({nrows}, {ncols}{optionals})'.format(
  53. clsname=self.__class__.__name__,
  54. nrows=self._nrows,
  55. ncols=self._ncols,
  56. optionals=height_arg + width_arg,
  57. )
  58. nrows = property(lambda self: self._nrows,
  59. doc="The number of rows in the grid.")
  60. ncols = property(lambda self: self._ncols,
  61. doc="The number of columns in the grid.")
  62. def get_geometry(self):
  63. """
  64. Return a tuple containing the number of rows and columns in the grid.
  65. """
  66. return self._nrows, self._ncols
  67. def get_subplot_params(self, figure=None):
  68. # Must be implemented in subclasses
  69. pass
  70. def new_subplotspec(self, loc, rowspan=1, colspan=1):
  71. """
  72. Create and return a `.SubplotSpec` instance.
  73. Parameters
  74. ----------
  75. loc : (int, int)
  76. The position of the subplot in the grid as
  77. ``(row_index, column_index)``.
  78. rowspan, colspan : int, default: 1
  79. The number of rows and columns the subplot should span in the grid.
  80. """
  81. loc1, loc2 = loc
  82. subplotspec = self[loc1:loc1+rowspan, loc2:loc2+colspan]
  83. return subplotspec
  84. def set_width_ratios(self, width_ratios):
  85. """
  86. Set the relative widths of the columns.
  87. *width_ratios* must be of length *ncols*. Each column gets a relative
  88. width of ``width_ratios[i] / sum(width_ratios)``.
  89. """
  90. if width_ratios is None:
  91. width_ratios = [1] * self._ncols
  92. elif len(width_ratios) != self._ncols:
  93. raise ValueError('Expected the given number of width ratios to '
  94. 'match the number of columns of the grid')
  95. self._col_width_ratios = width_ratios
  96. def get_width_ratios(self):
  97. """
  98. Return the width ratios.
  99. This is *None* if no width ratios have been set explicitly.
  100. """
  101. return self._col_width_ratios
  102. def set_height_ratios(self, height_ratios):
  103. """
  104. Set the relative heights of the rows.
  105. *height_ratios* must be of length *nrows*. Each row gets a relative
  106. height of ``height_ratios[i] / sum(height_ratios)``.
  107. """
  108. if height_ratios is None:
  109. height_ratios = [1] * self._nrows
  110. elif len(height_ratios) != self._nrows:
  111. raise ValueError('Expected the given number of height ratios to '
  112. 'match the number of rows of the grid')
  113. self._row_height_ratios = height_ratios
  114. def get_height_ratios(self):
  115. """
  116. Return the height ratios.
  117. This is *None* if no height ratios have been set explicitly.
  118. """
  119. return self._row_height_ratios
  120. def get_grid_positions(self, fig):
  121. """
  122. Return the positions of the grid cells in figure coordinates.
  123. Parameters
  124. ----------
  125. fig : `~matplotlib.figure.Figure`
  126. The figure the grid should be applied to. The subplot parameters
  127. (margins and spacing between subplots) are taken from *fig*.
  128. Returns
  129. -------
  130. bottoms, tops, lefts, rights : array
  131. The bottom, top, left, right positions of the grid cells in
  132. figure coordinates.
  133. """
  134. nrows, ncols = self.get_geometry()
  135. subplot_params = self.get_subplot_params(fig)
  136. left = subplot_params.left
  137. right = subplot_params.right
  138. bottom = subplot_params.bottom
  139. top = subplot_params.top
  140. wspace = subplot_params.wspace
  141. hspace = subplot_params.hspace
  142. tot_width = right - left
  143. tot_height = top - bottom
  144. # calculate accumulated heights of columns
  145. cell_h = tot_height / (nrows + hspace*(nrows-1))
  146. sep_h = hspace * cell_h
  147. norm = cell_h * nrows / sum(self._row_height_ratios)
  148. cell_heights = [r * norm for r in self._row_height_ratios]
  149. sep_heights = [0] + ([sep_h] * (nrows-1))
  150. cell_hs = np.cumsum(np.column_stack([sep_heights, cell_heights]).flat)
  151. # calculate accumulated widths of rows
  152. cell_w = tot_width / (ncols + wspace*(ncols-1))
  153. sep_w = wspace * cell_w
  154. norm = cell_w * ncols / sum(self._col_width_ratios)
  155. cell_widths = [r * norm for r in self._col_width_ratios]
  156. sep_widths = [0] + ([sep_w] * (ncols-1))
  157. cell_ws = np.cumsum(np.column_stack([sep_widths, cell_widths]).flat)
  158. fig_tops, fig_bottoms = (top - cell_hs).reshape((-1, 2)).T
  159. fig_lefts, fig_rights = (left + cell_ws).reshape((-1, 2)).T
  160. return fig_bottoms, fig_tops, fig_lefts, fig_rights
  161. @staticmethod
  162. def _check_gridspec_exists(figure, nrows, ncols):
  163. """
  164. Check if the figure already has a gridspec with these dimensions,
  165. or create a new one
  166. """
  167. for ax in figure.get_axes():
  168. gs = ax.get_gridspec()
  169. if gs is not None:
  170. if hasattr(gs, 'get_topmost_subplotspec'):
  171. # This is needed for colorbar gridspec layouts.
  172. # This is probably OK because this whole logic tree
  173. # is for when the user is doing simple things with the
  174. # add_subplot command. For complicated layouts
  175. # like subgridspecs the proper gridspec is passed in...
  176. gs = gs.get_topmost_subplotspec().get_gridspec()
  177. if gs.get_geometry() == (nrows, ncols):
  178. return gs
  179. # else gridspec not found:
  180. return GridSpec(nrows, ncols, figure=figure)
  181. def __getitem__(self, key):
  182. """Create and return a `.SubplotSpec` instance."""
  183. nrows, ncols = self.get_geometry()
  184. def _normalize(key, size, axis): # Includes last index.
  185. orig_key = key
  186. if isinstance(key, slice):
  187. start, stop, _ = key.indices(size)
  188. if stop > start:
  189. return start, stop - 1
  190. raise IndexError("GridSpec slice would result in no space "
  191. "allocated for subplot")
  192. else:
  193. if key < 0:
  194. key = key + size
  195. if 0 <= key < size:
  196. return key, key
  197. elif axis is not None:
  198. raise IndexError(f"index {orig_key} is out of bounds for "
  199. f"axis {axis} with size {size}")
  200. else: # flat index
  201. raise IndexError(f"index {orig_key} is out of bounds for "
  202. f"GridSpec with size {size}")
  203. if isinstance(key, tuple):
  204. try:
  205. k1, k2 = key
  206. except ValueError as err:
  207. raise ValueError("Unrecognized subplot spec") from err
  208. num1, num2 = np.ravel_multi_index(
  209. [_normalize(k1, nrows, 0), _normalize(k2, ncols, 1)],
  210. (nrows, ncols))
  211. else: # Single key
  212. num1, num2 = _normalize(key, nrows * ncols, None)
  213. return SubplotSpec(self, num1, num2)
  214. def subplots(self, *, sharex=False, sharey=False, squeeze=True,
  215. subplot_kw=None):
  216. """
  217. Add all subplots specified by this `GridSpec` to its parent figure.
  218. See `.Figure.subplots` for detailed documentation.
  219. """
  220. figure = self.figure
  221. if figure is None:
  222. raise ValueError("GridSpec.subplots() only works for GridSpecs "
  223. "created with a parent figure")
  224. if not isinstance(sharex, str):
  225. sharex = "all" if sharex else "none"
  226. if not isinstance(sharey, str):
  227. sharey = "all" if sharey else "none"
  228. _api.check_in_list(["all", "row", "col", "none", False, True],
  229. sharex=sharex, sharey=sharey)
  230. if subplot_kw is None:
  231. subplot_kw = {}
  232. # don't mutate kwargs passed by user...
  233. subplot_kw = subplot_kw.copy()
  234. # Create array to hold all Axes.
  235. axarr = np.empty((self._nrows, self._ncols), dtype=object)
  236. for row in range(self._nrows):
  237. for col in range(self._ncols):
  238. shared_with = {"none": None, "all": axarr[0, 0],
  239. "row": axarr[row, 0], "col": axarr[0, col]}
  240. subplot_kw["sharex"] = shared_with[sharex]
  241. subplot_kw["sharey"] = shared_with[sharey]
  242. axarr[row, col] = figure.add_subplot(
  243. self[row, col], **subplot_kw)
  244. # turn off redundant tick labeling
  245. if sharex in ["col", "all"]:
  246. for ax in axarr.flat:
  247. ax._label_outer_xaxis(skip_non_rectangular_axes=True)
  248. if sharey in ["row", "all"]:
  249. for ax in axarr.flat:
  250. ax._label_outer_yaxis(skip_non_rectangular_axes=True)
  251. if squeeze:
  252. # Discarding unneeded dimensions that equal 1. If we only have one
  253. # subplot, just return it instead of a 1-element array.
  254. return axarr.item() if axarr.size == 1 else axarr.squeeze()
  255. else:
  256. # Returned axis array will be always 2-d, even if nrows=ncols=1.
  257. return axarr
  258. class GridSpec(GridSpecBase):
  259. """
  260. A grid layout to place subplots within a figure.
  261. The location of the grid cells is determined in a similar way to
  262. `.SubplotParams` using *left*, *right*, *top*, *bottom*, *wspace*
  263. and *hspace*.
  264. Indexing a GridSpec instance returns a `.SubplotSpec`.
  265. """
  266. def __init__(self, nrows, ncols, figure=None,
  267. left=None, bottom=None, right=None, top=None,
  268. wspace=None, hspace=None,
  269. width_ratios=None, height_ratios=None):
  270. """
  271. Parameters
  272. ----------
  273. nrows, ncols : int
  274. The number of rows and columns of the grid.
  275. figure : `.Figure`, optional
  276. Only used for constrained layout to create a proper layoutgrid.
  277. left, right, top, bottom : float, optional
  278. Extent of the subplots as a fraction of figure width or height.
  279. Left cannot be larger than right, and bottom cannot be larger than
  280. top. If not given, the values will be inferred from a figure or
  281. rcParams at draw time. See also `GridSpec.get_subplot_params`.
  282. wspace : float, optional
  283. The amount of width reserved for space between subplots,
  284. expressed as a fraction of the average axis width.
  285. If not given, the values will be inferred from a figure or
  286. rcParams when necessary. See also `GridSpec.get_subplot_params`.
  287. hspace : float, optional
  288. The amount of height reserved for space between subplots,
  289. expressed as a fraction of the average axis height.
  290. If not given, the values will be inferred from a figure or
  291. rcParams when necessary. See also `GridSpec.get_subplot_params`.
  292. width_ratios : array-like of length *ncols*, optional
  293. Defines the relative widths of the columns. Each column gets a
  294. relative width of ``width_ratios[i] / sum(width_ratios)``.
  295. If not given, all columns will have the same width.
  296. height_ratios : array-like of length *nrows*, optional
  297. Defines the relative heights of the rows. Each row gets a
  298. relative height of ``height_ratios[i] / sum(height_ratios)``.
  299. If not given, all rows will have the same height.
  300. """
  301. self.left = left
  302. self.bottom = bottom
  303. self.right = right
  304. self.top = top
  305. self.wspace = wspace
  306. self.hspace = hspace
  307. self.figure = figure
  308. super().__init__(nrows, ncols,
  309. width_ratios=width_ratios,
  310. height_ratios=height_ratios)
  311. _AllowedKeys = ["left", "bottom", "right", "top", "wspace", "hspace"]
  312. def update(self, **kwargs):
  313. """
  314. Update the subplot parameters of the grid.
  315. Parameters that are not explicitly given are not changed. Setting a
  316. parameter to *None* resets it to :rc:`figure.subplot.*`.
  317. Parameters
  318. ----------
  319. left, right, top, bottom : float or None, optional
  320. Extent of the subplots as a fraction of figure width or height.
  321. wspace, hspace : float, optional
  322. Spacing between the subplots as a fraction of the average subplot
  323. width / height.
  324. """
  325. for k, v in kwargs.items():
  326. if k in self._AllowedKeys:
  327. setattr(self, k, v)
  328. else:
  329. raise AttributeError(f"{k} is an unknown keyword")
  330. for figmanager in _pylab_helpers.Gcf.figs.values():
  331. for ax in figmanager.canvas.figure.axes:
  332. if ax.get_subplotspec() is not None:
  333. ss = ax.get_subplotspec().get_topmost_subplotspec()
  334. if ss.get_gridspec() == self:
  335. fig = ax.get_figure(root=False)
  336. ax._set_position(ax.get_subplotspec().get_position(fig))
  337. def get_subplot_params(self, figure=None):
  338. """
  339. Return the `.SubplotParams` for the GridSpec.
  340. In order of precedence the values are taken from
  341. - non-*None* attributes of the GridSpec
  342. - the provided *figure*
  343. - :rc:`figure.subplot.*`
  344. Note that the ``figure`` attribute of the GridSpec is always ignored.
  345. """
  346. if figure is None:
  347. kw = {k: mpl.rcParams["figure.subplot."+k]
  348. for k in self._AllowedKeys}
  349. subplotpars = SubplotParams(**kw)
  350. else:
  351. subplotpars = copy.copy(figure.subplotpars)
  352. subplotpars.update(**{k: getattr(self, k) for k in self._AllowedKeys})
  353. return subplotpars
  354. def locally_modified_subplot_params(self):
  355. """
  356. Return a list of the names of the subplot parameters explicitly set
  357. in the GridSpec.
  358. This is a subset of the attributes of `.SubplotParams`.
  359. """
  360. return [k for k in self._AllowedKeys if getattr(self, k)]
  361. def tight_layout(self, figure, renderer=None,
  362. pad=1.08, h_pad=None, w_pad=None, rect=None):
  363. """
  364. Adjust subplot parameters to give specified padding.
  365. Parameters
  366. ----------
  367. figure : `.Figure`
  368. The figure.
  369. renderer : `.RendererBase` subclass, optional
  370. The renderer to be used.
  371. pad : float
  372. Padding between the figure edge and the edges of subplots, as a
  373. fraction of the font-size.
  374. h_pad, w_pad : float, optional
  375. Padding (height/width) between edges of adjacent subplots.
  376. Defaults to *pad*.
  377. rect : tuple (left, bottom, right, top), default: None
  378. (left, bottom, right, top) rectangle in normalized figure
  379. coordinates that the whole subplots area (including labels) will
  380. fit into. Default (None) is the whole figure.
  381. """
  382. if renderer is None:
  383. renderer = figure._get_renderer()
  384. kwargs = _tight_layout.get_tight_layout_figure(
  385. figure, figure.axes,
  386. _tight_layout.get_subplotspec_list(figure.axes, grid_spec=self),
  387. renderer, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
  388. if kwargs:
  389. self.update(**kwargs)
  390. class GridSpecFromSubplotSpec(GridSpecBase):
  391. """
  392. GridSpec whose subplot layout parameters are inherited from the
  393. location specified by a given SubplotSpec.
  394. """
  395. def __init__(self, nrows, ncols,
  396. subplot_spec,
  397. wspace=None, hspace=None,
  398. height_ratios=None, width_ratios=None):
  399. """
  400. Parameters
  401. ----------
  402. nrows, ncols : int
  403. Number of rows and number of columns of the grid.
  404. subplot_spec : SubplotSpec
  405. Spec from which the layout parameters are inherited.
  406. wspace, hspace : float, optional
  407. See `GridSpec` for more details. If not specified default values
  408. (from the figure or rcParams) are used.
  409. height_ratios : array-like of length *nrows*, optional
  410. See `GridSpecBase` for details.
  411. width_ratios : array-like of length *ncols*, optional
  412. See `GridSpecBase` for details.
  413. """
  414. self._wspace = wspace
  415. self._hspace = hspace
  416. if isinstance(subplot_spec, SubplotSpec):
  417. self._subplot_spec = subplot_spec
  418. else:
  419. raise TypeError(
  420. "subplot_spec must be type SubplotSpec, "
  421. "usually from GridSpec, or axes.get_subplotspec.")
  422. self.figure = self._subplot_spec.get_gridspec().figure
  423. super().__init__(nrows, ncols,
  424. width_ratios=width_ratios,
  425. height_ratios=height_ratios)
  426. def get_subplot_params(self, figure=None):
  427. """Return a dictionary of subplot layout parameters."""
  428. hspace = (self._hspace if self._hspace is not None
  429. else figure.subplotpars.hspace if figure is not None
  430. else mpl.rcParams["figure.subplot.hspace"])
  431. wspace = (self._wspace if self._wspace is not None
  432. else figure.subplotpars.wspace if figure is not None
  433. else mpl.rcParams["figure.subplot.wspace"])
  434. figbox = self._subplot_spec.get_position(figure)
  435. left, bottom, right, top = figbox.extents
  436. return SubplotParams(left=left, right=right,
  437. bottom=bottom, top=top,
  438. wspace=wspace, hspace=hspace)
  439. def get_topmost_subplotspec(self):
  440. """
  441. Return the topmost `.SubplotSpec` instance associated with the subplot.
  442. """
  443. return self._subplot_spec.get_topmost_subplotspec()
  444. class SubplotSpec:
  445. """
  446. The location of a subplot in a `GridSpec`.
  447. .. note::
  448. Likely, you will never instantiate a `SubplotSpec` yourself. Instead,
  449. you will typically obtain one from a `GridSpec` using item-access.
  450. Parameters
  451. ----------
  452. gridspec : `~matplotlib.gridspec.GridSpec`
  453. The GridSpec, which the subplot is referencing.
  454. num1, num2 : int
  455. The subplot will occupy the *num1*-th cell of the given
  456. *gridspec*. If *num2* is provided, the subplot will span between
  457. *num1*-th cell and *num2*-th cell **inclusive**.
  458. The index starts from 0.
  459. """
  460. def __init__(self, gridspec, num1, num2=None):
  461. self._gridspec = gridspec
  462. self.num1 = num1
  463. self.num2 = num2
  464. def __repr__(self):
  465. return (f"{self.get_gridspec()}["
  466. f"{self.rowspan.start}:{self.rowspan.stop}, "
  467. f"{self.colspan.start}:{self.colspan.stop}]")
  468. @staticmethod
  469. def _from_subplot_args(figure, args):
  470. """
  471. Construct a `.SubplotSpec` from a parent `.Figure` and either
  472. - a `.SubplotSpec` -- returned as is;
  473. - one or three numbers -- a MATLAB-style subplot specifier.
  474. """
  475. if len(args) == 1:
  476. arg, = args
  477. if isinstance(arg, SubplotSpec):
  478. return arg
  479. elif not isinstance(arg, Integral):
  480. raise ValueError(
  481. f"Single argument to subplot must be a three-digit "
  482. f"integer, not {arg!r}")
  483. try:
  484. rows, cols, num = map(int, str(arg))
  485. except ValueError:
  486. raise ValueError(
  487. f"Single argument to subplot must be a three-digit "
  488. f"integer, not {arg!r}") from None
  489. elif len(args) == 3:
  490. rows, cols, num = args
  491. else:
  492. raise _api.nargs_error("subplot", takes="1 or 3", given=len(args))
  493. gs = GridSpec._check_gridspec_exists(figure, rows, cols)
  494. if gs is None:
  495. gs = GridSpec(rows, cols, figure=figure)
  496. if isinstance(num, tuple) and len(num) == 2:
  497. if not all(isinstance(n, Integral) for n in num):
  498. raise ValueError(
  499. f"Subplot specifier tuple must contain integers, not {num}"
  500. )
  501. i, j = num
  502. else:
  503. if not isinstance(num, Integral) or num < 1 or num > rows*cols:
  504. raise ValueError(
  505. f"num must be an integer with 1 <= num <= {rows*cols}, "
  506. f"not {num!r}"
  507. )
  508. i = j = num
  509. return gs[i-1:j]
  510. # num2 is a property only to handle the case where it is None and someone
  511. # mutates num1.
  512. @property
  513. def num2(self):
  514. return self.num1 if self._num2 is None else self._num2
  515. @num2.setter
  516. def num2(self, value):
  517. self._num2 = value
  518. def get_gridspec(self):
  519. return self._gridspec
  520. def get_geometry(self):
  521. """
  522. Return the subplot geometry as tuple ``(n_rows, n_cols, start, stop)``.
  523. The indices *start* and *stop* define the range of the subplot within
  524. the `GridSpec`. *stop* is inclusive (i.e. for a single cell
  525. ``start == stop``).
  526. """
  527. rows, cols = self.get_gridspec().get_geometry()
  528. return rows, cols, self.num1, self.num2
  529. @property
  530. def rowspan(self):
  531. """The rows spanned by this subplot, as a `range` object."""
  532. ncols = self.get_gridspec().ncols
  533. return range(self.num1 // ncols, self.num2 // ncols + 1)
  534. @property
  535. def colspan(self):
  536. """The columns spanned by this subplot, as a `range` object."""
  537. ncols = self.get_gridspec().ncols
  538. # We explicitly support num2 referring to a column on num1's *left*, so
  539. # we must sort the column indices here so that the range makes sense.
  540. c1, c2 = sorted([self.num1 % ncols, self.num2 % ncols])
  541. return range(c1, c2 + 1)
  542. def is_first_row(self):
  543. return self.rowspan.start == 0
  544. def is_last_row(self):
  545. return self.rowspan.stop == self.get_gridspec().nrows
  546. def is_first_col(self):
  547. return self.colspan.start == 0
  548. def is_last_col(self):
  549. return self.colspan.stop == self.get_gridspec().ncols
  550. def get_position(self, figure):
  551. """
  552. Update the subplot position from ``figure.subplotpars``.
  553. """
  554. gridspec = self.get_gridspec()
  555. nrows, ncols = gridspec.get_geometry()
  556. rows, cols = np.unravel_index([self.num1, self.num2], (nrows, ncols))
  557. fig_bottoms, fig_tops, fig_lefts, fig_rights = \
  558. gridspec.get_grid_positions(figure)
  559. fig_bottom = fig_bottoms[rows].min()
  560. fig_top = fig_tops[rows].max()
  561. fig_left = fig_lefts[cols].min()
  562. fig_right = fig_rights[cols].max()
  563. return Bbox.from_extents(fig_left, fig_bottom, fig_right, fig_top)
  564. def get_topmost_subplotspec(self):
  565. """
  566. Return the topmost `SubplotSpec` instance associated with the subplot.
  567. """
  568. gridspec = self.get_gridspec()
  569. if hasattr(gridspec, "get_topmost_subplotspec"):
  570. return gridspec.get_topmost_subplotspec()
  571. else:
  572. return self
  573. def __eq__(self, other):
  574. """
  575. Two SubplotSpecs are considered equal if they refer to the same
  576. position(s) in the same `GridSpec`.
  577. """
  578. # other may not even have the attributes we are checking.
  579. return ((self._gridspec, self.num1, self.num2)
  580. == (getattr(other, "_gridspec", object()),
  581. getattr(other, "num1", object()),
  582. getattr(other, "num2", object())))
  583. def __hash__(self):
  584. return hash((self._gridspec, self.num1, self.num2))
  585. def subgridspec(self, nrows, ncols, **kwargs):
  586. """
  587. Create a GridSpec within this subplot.
  588. The created `.GridSpecFromSubplotSpec` will have this `SubplotSpec` as
  589. a parent.
  590. Parameters
  591. ----------
  592. nrows : int
  593. Number of rows in grid.
  594. ncols : int
  595. Number of columns in grid.
  596. Returns
  597. -------
  598. `.GridSpecFromSubplotSpec`
  599. Other Parameters
  600. ----------------
  601. **kwargs
  602. All other parameters are passed to `.GridSpecFromSubplotSpec`.
  603. See Also
  604. --------
  605. matplotlib.pyplot.subplots
  606. Examples
  607. --------
  608. Adding three subplots in the space occupied by a single subplot::
  609. fig = plt.figure()
  610. gs0 = fig.add_gridspec(3, 1)
  611. ax1 = fig.add_subplot(gs0[0])
  612. ax2 = fig.add_subplot(gs0[1])
  613. gssub = gs0[2].subgridspec(1, 3)
  614. for i in range(3):
  615. fig.add_subplot(gssub[0, i])
  616. """
  617. return GridSpecFromSubplotSpec(nrows, ncols, self, **kwargs)
  618. class SubplotParams:
  619. """
  620. Parameters defining the positioning of a subplots grid in a figure.
  621. """
  622. def __init__(self, left=None, bottom=None, right=None, top=None,
  623. wspace=None, hspace=None):
  624. """
  625. Defaults are given by :rc:`figure.subplot.[name]`.
  626. Parameters
  627. ----------
  628. left : float
  629. The position of the left edge of the subplots,
  630. as a fraction of the figure width.
  631. right : float
  632. The position of the right edge of the subplots,
  633. as a fraction of the figure width.
  634. bottom : float
  635. The position of the bottom edge of the subplots,
  636. as a fraction of the figure height.
  637. top : float
  638. The position of the top edge of the subplots,
  639. as a fraction of the figure height.
  640. wspace : float
  641. The width of the padding between subplots,
  642. as a fraction of the average Axes width.
  643. hspace : float
  644. The height of the padding between subplots,
  645. as a fraction of the average Axes height.
  646. """
  647. for key in ["left", "bottom", "right", "top", "wspace", "hspace"]:
  648. setattr(self, key, mpl.rcParams[f"figure.subplot.{key}"])
  649. self.update(left, bottom, right, top, wspace, hspace)
  650. def update(self, left=None, bottom=None, right=None, top=None,
  651. wspace=None, hspace=None):
  652. """
  653. Update the dimensions of the passed parameters. *None* means unchanged.
  654. """
  655. if ((left if left is not None else self.left)
  656. >= (right if right is not None else self.right)):
  657. raise ValueError('left cannot be >= right')
  658. if ((bottom if bottom is not None else self.bottom)
  659. >= (top if top is not None else self.top)):
  660. raise ValueError('bottom cannot be >= top')
  661. if left is not None:
  662. self.left = left
  663. if right is not None:
  664. self.right = right
  665. if bottom is not None:
  666. self.bottom = bottom
  667. if top is not None:
  668. self.top = top
  669. if wspace is not None:
  670. self.wspace = wspace
  671. if hspace is not None:
  672. self.hspace = hspace