gridspec.py 27 KB

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