axes_divider.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. """
  2. Helper classes to adjust the positions of multiple axes at drawing time.
  3. """
  4. import functools
  5. import numpy as np
  6. import matplotlib as mpl
  7. from matplotlib import _api
  8. from matplotlib.gridspec import SubplotSpec
  9. import matplotlib.transforms as mtransforms
  10. from . import axes_size as Size
  11. class Divider:
  12. """
  13. An Axes positioning class.
  14. The divider is initialized with lists of horizontal and vertical sizes
  15. (:mod:`mpl_toolkits.axes_grid1.axes_size`) based on which a given
  16. rectangular area will be divided.
  17. The `new_locator` method then creates a callable object
  18. that can be used as the *axes_locator* of the axes.
  19. """
  20. def __init__(self, fig, pos, horizontal, vertical,
  21. aspect=None, anchor="C"):
  22. """
  23. Parameters
  24. ----------
  25. fig : Figure
  26. pos : tuple of 4 floats
  27. Position of the rectangle that will be divided.
  28. horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
  29. Sizes for horizontal division.
  30. vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
  31. Sizes for vertical division.
  32. aspect : bool, optional
  33. Whether overall rectangular area is reduced so that the relative
  34. part of the horizontal and vertical scales have the same scale.
  35. anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
  36. 'NW', 'W'}, default: 'C'
  37. Placement of the reduced rectangle, when *aspect* is True.
  38. """
  39. self._fig = fig
  40. self._pos = pos
  41. self._horizontal = horizontal
  42. self._vertical = vertical
  43. self._anchor = anchor
  44. self.set_anchor(anchor)
  45. self._aspect = aspect
  46. self._xrefindex = 0
  47. self._yrefindex = 0
  48. self._locator = None
  49. def get_horizontal_sizes(self, renderer):
  50. return np.array([s.get_size(renderer) for s in self.get_horizontal()])
  51. def get_vertical_sizes(self, renderer):
  52. return np.array([s.get_size(renderer) for s in self.get_vertical()])
  53. def set_position(self, pos):
  54. """
  55. Set the position of the rectangle.
  56. Parameters
  57. ----------
  58. pos : tuple of 4 floats
  59. position of the rectangle that will be divided
  60. """
  61. self._pos = pos
  62. def get_position(self):
  63. """Return the position of the rectangle."""
  64. return self._pos
  65. def set_anchor(self, anchor):
  66. """
  67. Parameters
  68. ----------
  69. anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
  70. 'NW', 'W'}
  71. Either an (*x*, *y*) pair of relative coordinates (0 is left or
  72. bottom, 1 is right or top), 'C' (center), or a cardinal direction
  73. ('SW', southwest, is bottom left, etc.).
  74. See Also
  75. --------
  76. .Axes.set_anchor
  77. """
  78. if isinstance(anchor, str):
  79. _api.check_in_list(mtransforms.Bbox.coefs, anchor=anchor)
  80. elif not isinstance(anchor, (tuple, list)) or len(anchor) != 2:
  81. raise TypeError("anchor must be str or 2-tuple")
  82. self._anchor = anchor
  83. def get_anchor(self):
  84. """Return the anchor."""
  85. return self._anchor
  86. def get_subplotspec(self):
  87. return None
  88. def set_horizontal(self, h):
  89. """
  90. Parameters
  91. ----------
  92. h : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
  93. sizes for horizontal division
  94. """
  95. self._horizontal = h
  96. def get_horizontal(self):
  97. """Return horizontal sizes."""
  98. return self._horizontal
  99. def set_vertical(self, v):
  100. """
  101. Parameters
  102. ----------
  103. v : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
  104. sizes for vertical division
  105. """
  106. self._vertical = v
  107. def get_vertical(self):
  108. """Return vertical sizes."""
  109. return self._vertical
  110. def set_aspect(self, aspect=False):
  111. """
  112. Parameters
  113. ----------
  114. aspect : bool
  115. """
  116. self._aspect = aspect
  117. def get_aspect(self):
  118. """Return aspect."""
  119. return self._aspect
  120. def set_locator(self, _locator):
  121. self._locator = _locator
  122. def get_locator(self):
  123. return self._locator
  124. def get_position_runtime(self, ax, renderer):
  125. if self._locator is None:
  126. return self.get_position()
  127. else:
  128. return self._locator(ax, renderer).bounds
  129. @staticmethod
  130. def _calc_k(sizes, total):
  131. # sizes is a (n, 2) array of (rel_size, abs_size); this method finds
  132. # the k factor such that sum(rel_size * k + abs_size) == total.
  133. rel_sum, abs_sum = sizes.sum(0)
  134. return (total - abs_sum) / rel_sum if rel_sum else 0
  135. @staticmethod
  136. def _calc_offsets(sizes, k):
  137. # Apply k factors to (n, 2) sizes array of (rel_size, abs_size); return
  138. # the resulting cumulative offset positions.
  139. return np.cumsum([0, *(sizes @ [k, 1])])
  140. def new_locator(self, nx, ny, nx1=None, ny1=None):
  141. """
  142. Return an axes locator callable for the specified cell.
  143. Parameters
  144. ----------
  145. nx, nx1 : int
  146. Integers specifying the column-position of the
  147. cell. When *nx1* is None, a single *nx*-th column is
  148. specified. Otherwise, location of columns spanning between *nx*
  149. to *nx1* (but excluding *nx1*-th column) is specified.
  150. ny, ny1 : int
  151. Same as *nx* and *nx1*, but for row positions.
  152. """
  153. if nx1 is None:
  154. nx1 = nx + 1
  155. if ny1 is None:
  156. ny1 = ny + 1
  157. # append_size("left") adds a new size at the beginning of the
  158. # horizontal size lists; this shift transforms e.g.
  159. # new_locator(nx=2, ...) into effectively new_locator(nx=3, ...). To
  160. # take that into account, instead of recording nx, we record
  161. # nx-self._xrefindex, where _xrefindex is shifted by 1 by each
  162. # append_size("left"), and re-add self._xrefindex back to nx in
  163. # _locate, when the actual axes position is computed. Ditto for y.
  164. xref = self._xrefindex
  165. yref = self._yrefindex
  166. locator = functools.partial(
  167. self._locate, nx - xref, ny - yref, nx1 - xref, ny1 - yref)
  168. locator.get_subplotspec = self.get_subplotspec
  169. return locator
  170. @_api.deprecated(
  171. "3.8", alternative="divider.new_locator(...)(ax, renderer)")
  172. def locate(self, nx, ny, nx1=None, ny1=None, axes=None, renderer=None):
  173. """
  174. Implementation of ``divider.new_locator().__call__``.
  175. Parameters
  176. ----------
  177. nx, nx1 : int
  178. Integers specifying the column-position of the cell. When *nx1* is
  179. None, a single *nx*-th column is specified. Otherwise, the
  180. location of columns spanning between *nx* to *nx1* (but excluding
  181. *nx1*-th column) is specified.
  182. ny, ny1 : int
  183. Same as *nx* and *nx1*, but for row positions.
  184. axes
  185. renderer
  186. """
  187. xref = self._xrefindex
  188. yref = self._yrefindex
  189. return self._locate(
  190. nx - xref, (nx + 1 if nx1 is None else nx1) - xref,
  191. ny - yref, (ny + 1 if ny1 is None else ny1) - yref,
  192. axes, renderer)
  193. def _locate(self, nx, ny, nx1, ny1, axes, renderer):
  194. """
  195. Implementation of ``divider.new_locator().__call__``.
  196. The axes locator callable returned by ``new_locator()`` is created as
  197. a `functools.partial` of this method with *nx*, *ny*, *nx1*, and *ny1*
  198. specifying the requested cell.
  199. """
  200. nx += self._xrefindex
  201. nx1 += self._xrefindex
  202. ny += self._yrefindex
  203. ny1 += self._yrefindex
  204. fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
  205. x, y, w, h = self.get_position_runtime(axes, renderer)
  206. hsizes = self.get_horizontal_sizes(renderer)
  207. vsizes = self.get_vertical_sizes(renderer)
  208. k_h = self._calc_k(hsizes, fig_w * w)
  209. k_v = self._calc_k(vsizes, fig_h * h)
  210. if self.get_aspect():
  211. k = min(k_h, k_v)
  212. ox = self._calc_offsets(hsizes, k)
  213. oy = self._calc_offsets(vsizes, k)
  214. ww = (ox[-1] - ox[0]) / fig_w
  215. hh = (oy[-1] - oy[0]) / fig_h
  216. pb = mtransforms.Bbox.from_bounds(x, y, w, h)
  217. pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)
  218. x0, y0 = pb1.anchored(self.get_anchor(), pb).p0
  219. else:
  220. ox = self._calc_offsets(hsizes, k_h)
  221. oy = self._calc_offsets(vsizes, k_v)
  222. x0, y0 = x, y
  223. if nx1 is None:
  224. nx1 = -1
  225. if ny1 is None:
  226. ny1 = -1
  227. x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w
  228. y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h
  229. return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
  230. def append_size(self, position, size):
  231. _api.check_in_list(["left", "right", "bottom", "top"],
  232. position=position)
  233. if position == "left":
  234. self._horizontal.insert(0, size)
  235. self._xrefindex += 1
  236. elif position == "right":
  237. self._horizontal.append(size)
  238. elif position == "bottom":
  239. self._vertical.insert(0, size)
  240. self._yrefindex += 1
  241. else: # 'top'
  242. self._vertical.append(size)
  243. def add_auto_adjustable_area(self, use_axes, pad=0.1, adjust_dirs=None):
  244. """
  245. Add auto-adjustable padding around *use_axes* to take their decorations
  246. (title, labels, ticks, ticklabels) into account during layout.
  247. Parameters
  248. ----------
  249. use_axes : `~matplotlib.axes.Axes` or list of `~matplotlib.axes.Axes`
  250. The Axes whose decorations are taken into account.
  251. pad : float, default: 0.1
  252. Additional padding in inches.
  253. adjust_dirs : list of {"left", "right", "bottom", "top"}, optional
  254. The sides where padding is added; defaults to all four sides.
  255. """
  256. if adjust_dirs is None:
  257. adjust_dirs = ["left", "right", "bottom", "top"]
  258. for d in adjust_dirs:
  259. self.append_size(d, Size._AxesDecorationsSize(use_axes, d) + pad)
  260. @_api.deprecated("3.8")
  261. class AxesLocator:
  262. """
  263. A callable object which returns the position and size of a given
  264. `.AxesDivider` cell.
  265. """
  266. def __init__(self, axes_divider, nx, ny, nx1=None, ny1=None):
  267. """
  268. Parameters
  269. ----------
  270. axes_divider : `~mpl_toolkits.axes_grid1.axes_divider.AxesDivider`
  271. nx, nx1 : int
  272. Integers specifying the column-position of the
  273. cell. When *nx1* is None, a single *nx*-th column is
  274. specified. Otherwise, location of columns spanning between *nx*
  275. to *nx1* (but excluding *nx1*-th column) is specified.
  276. ny, ny1 : int
  277. Same as *nx* and *nx1*, but for row positions.
  278. """
  279. self._axes_divider = axes_divider
  280. _xrefindex = axes_divider._xrefindex
  281. _yrefindex = axes_divider._yrefindex
  282. self._nx, self._ny = nx - _xrefindex, ny - _yrefindex
  283. if nx1 is None:
  284. nx1 = len(self._axes_divider)
  285. if ny1 is None:
  286. ny1 = len(self._axes_divider[0])
  287. self._nx1 = nx1 - _xrefindex
  288. self._ny1 = ny1 - _yrefindex
  289. def __call__(self, axes, renderer):
  290. _xrefindex = self._axes_divider._xrefindex
  291. _yrefindex = self._axes_divider._yrefindex
  292. return self._axes_divider.locate(self._nx + _xrefindex,
  293. self._ny + _yrefindex,
  294. self._nx1 + _xrefindex,
  295. self._ny1 + _yrefindex,
  296. axes,
  297. renderer)
  298. def get_subplotspec(self):
  299. return self._axes_divider.get_subplotspec()
  300. class SubplotDivider(Divider):
  301. """
  302. The Divider class whose rectangle area is specified as a subplot geometry.
  303. """
  304. def __init__(self, fig, *args, horizontal=None, vertical=None,
  305. aspect=None, anchor='C'):
  306. """
  307. Parameters
  308. ----------
  309. fig : `~matplotlib.figure.Figure`
  310. *args : tuple (*nrows*, *ncols*, *index*) or int
  311. The array of subplots in the figure has dimensions ``(nrows,
  312. ncols)``, and *index* is the index of the subplot being created.
  313. *index* starts at 1 in the upper left corner and increases to the
  314. right.
  315. If *nrows*, *ncols*, and *index* are all single digit numbers, then
  316. *args* can be passed as a single 3-digit number (e.g. 234 for
  317. (2, 3, 4)).
  318. horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional
  319. Sizes for horizontal division.
  320. vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional
  321. Sizes for vertical division.
  322. aspect : bool, optional
  323. Whether overall rectangular area is reduced so that the relative
  324. part of the horizontal and vertical scales have the same scale.
  325. anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
  326. 'NW', 'W'}, default: 'C'
  327. Placement of the reduced rectangle, when *aspect* is True.
  328. """
  329. self.figure = fig
  330. super().__init__(fig, [0, 0, 1, 1],
  331. horizontal=horizontal or [], vertical=vertical or [],
  332. aspect=aspect, anchor=anchor)
  333. self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args))
  334. def get_position(self):
  335. """Return the bounds of the subplot box."""
  336. return self.get_subplotspec().get_position(self.figure).bounds
  337. def get_subplotspec(self):
  338. """Get the SubplotSpec instance."""
  339. return self._subplotspec
  340. def set_subplotspec(self, subplotspec):
  341. """Set the SubplotSpec instance."""
  342. self._subplotspec = subplotspec
  343. self.set_position(subplotspec.get_position(self.figure))
  344. class AxesDivider(Divider):
  345. """
  346. Divider based on the preexisting axes.
  347. """
  348. def __init__(self, axes, xref=None, yref=None):
  349. """
  350. Parameters
  351. ----------
  352. axes : :class:`~matplotlib.axes.Axes`
  353. xref
  354. yref
  355. """
  356. self._axes = axes
  357. if xref is None:
  358. self._xref = Size.AxesX(axes)
  359. else:
  360. self._xref = xref
  361. if yref is None:
  362. self._yref = Size.AxesY(axes)
  363. else:
  364. self._yref = yref
  365. super().__init__(fig=axes.get_figure(), pos=None,
  366. horizontal=[self._xref], vertical=[self._yref],
  367. aspect=None, anchor="C")
  368. def _get_new_axes(self, *, axes_class=None, **kwargs):
  369. axes = self._axes
  370. if axes_class is None:
  371. axes_class = type(axes)
  372. return axes_class(axes.get_figure(), axes.get_position(original=True),
  373. **kwargs)
  374. def new_horizontal(self, size, pad=None, pack_start=False, **kwargs):
  375. """
  376. Helper method for ``append_axes("left")`` and ``append_axes("right")``.
  377. See the documentation of `append_axes` for more details.
  378. :meta private:
  379. """
  380. if pad is None:
  381. pad = mpl.rcParams["figure.subplot.wspace"] * self._xref
  382. pos = "left" if pack_start else "right"
  383. if pad:
  384. if not isinstance(pad, Size._Base):
  385. pad = Size.from_any(pad, fraction_ref=self._xref)
  386. self.append_size(pos, pad)
  387. if not isinstance(size, Size._Base):
  388. size = Size.from_any(size, fraction_ref=self._xref)
  389. self.append_size(pos, size)
  390. locator = self.new_locator(
  391. nx=0 if pack_start else len(self._horizontal) - 1,
  392. ny=self._yrefindex)
  393. ax = self._get_new_axes(**kwargs)
  394. ax.set_axes_locator(locator)
  395. return ax
  396. def new_vertical(self, size, pad=None, pack_start=False, **kwargs):
  397. """
  398. Helper method for ``append_axes("top")`` and ``append_axes("bottom")``.
  399. See the documentation of `append_axes` for more details.
  400. :meta private:
  401. """
  402. if pad is None:
  403. pad = mpl.rcParams["figure.subplot.hspace"] * self._yref
  404. pos = "bottom" if pack_start else "top"
  405. if pad:
  406. if not isinstance(pad, Size._Base):
  407. pad = Size.from_any(pad, fraction_ref=self._yref)
  408. self.append_size(pos, pad)
  409. if not isinstance(size, Size._Base):
  410. size = Size.from_any(size, fraction_ref=self._yref)
  411. self.append_size(pos, size)
  412. locator = self.new_locator(
  413. nx=self._xrefindex,
  414. ny=0 if pack_start else len(self._vertical) - 1)
  415. ax = self._get_new_axes(**kwargs)
  416. ax.set_axes_locator(locator)
  417. return ax
  418. def append_axes(self, position, size, pad=None, *, axes_class=None,
  419. **kwargs):
  420. """
  421. Add a new axes on a given side of the main axes.
  422. Parameters
  423. ----------
  424. position : {"left", "right", "bottom", "top"}
  425. Where the new axes is positioned relative to the main axes.
  426. size : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str
  427. The axes width or height. float or str arguments are interpreted
  428. as ``axes_size.from_any(size, AxesX(<main_axes>))`` for left or
  429. right axes, and likewise with ``AxesY`` for bottom or top axes.
  430. pad : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str
  431. Padding between the axes. float or str arguments are interpreted
  432. as for *size*. Defaults to :rc:`figure.subplot.wspace` times the
  433. main Axes width (left or right axes) or :rc:`figure.subplot.hspace`
  434. times the main Axes height (bottom or top axes).
  435. axes_class : subclass type of `~.axes.Axes`, optional
  436. The type of the new axes. Defaults to the type of the main axes.
  437. **kwargs
  438. All extra keywords arguments are passed to the created axes.
  439. """
  440. create_axes, pack_start = _api.check_getitem({
  441. "left": (self.new_horizontal, True),
  442. "right": (self.new_horizontal, False),
  443. "bottom": (self.new_vertical, True),
  444. "top": (self.new_vertical, False),
  445. }, position=position)
  446. ax = create_axes(
  447. size, pad, pack_start=pack_start, axes_class=axes_class, **kwargs)
  448. self._fig.add_axes(ax)
  449. return ax
  450. def get_aspect(self):
  451. if self._aspect is None:
  452. aspect = self._axes.get_aspect()
  453. if aspect == "auto":
  454. return False
  455. else:
  456. return True
  457. else:
  458. return self._aspect
  459. def get_position(self):
  460. if self._pos is None:
  461. bbox = self._axes.get_position(original=True)
  462. return bbox.bounds
  463. else:
  464. return self._pos
  465. def get_anchor(self):
  466. if self._anchor is None:
  467. return self._axes.get_anchor()
  468. else:
  469. return self._anchor
  470. def get_subplotspec(self):
  471. return self._axes.get_subplotspec()
  472. # Helper for HBoxDivider/VBoxDivider.
  473. # The variable names are written for a horizontal layout, but the calculations
  474. # work identically for vertical layouts.
  475. def _locate(x, y, w, h, summed_widths, equal_heights, fig_w, fig_h, anchor):
  476. total_width = fig_w * w
  477. max_height = fig_h * h
  478. # Determine the k factors.
  479. n = len(equal_heights)
  480. eq_rels, eq_abss = equal_heights.T
  481. sm_rels, sm_abss = summed_widths.T
  482. A = np.diag([*eq_rels, 0])
  483. A[:n, -1] = -1
  484. A[-1, :-1] = sm_rels
  485. B = [*(-eq_abss), total_width - sm_abss.sum()]
  486. # A @ K = B: This finds factors {k_0, ..., k_{N-1}, H} so that
  487. # eq_rel_i * k_i + eq_abs_i = H for all i: all axes have the same height
  488. # sum(sm_rel_i * k_i + sm_abs_i) = total_width: fixed total width
  489. # (foo_rel_i * k_i + foo_abs_i will end up being the size of foo.)
  490. *karray, height = np.linalg.solve(A, B)
  491. if height > max_height: # Additionally, upper-bound the height.
  492. karray = (max_height - eq_abss) / eq_rels
  493. # Compute the offsets corresponding to these factors.
  494. ox = np.cumsum([0, *(sm_rels * karray + sm_abss)])
  495. ww = (ox[-1] - ox[0]) / fig_w
  496. h0_rel, h0_abs = equal_heights[0]
  497. hh = (karray[0]*h0_rel + h0_abs) / fig_h
  498. pb = mtransforms.Bbox.from_bounds(x, y, w, h)
  499. pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)
  500. x0, y0 = pb1.anchored(anchor, pb).p0
  501. return x0, y0, ox, hh
  502. class HBoxDivider(SubplotDivider):
  503. """
  504. A `.SubplotDivider` for laying out axes horizontally, while ensuring that
  505. they have equal heights.
  506. Examples
  507. --------
  508. .. plot:: gallery/axes_grid1/demo_axes_hbox_divider.py
  509. """
  510. def new_locator(self, nx, nx1=None):
  511. """
  512. Create an axes locator callable for the specified cell.
  513. Parameters
  514. ----------
  515. nx, nx1 : int
  516. Integers specifying the column-position of the
  517. cell. When *nx1* is None, a single *nx*-th column is
  518. specified. Otherwise, location of columns spanning between *nx*
  519. to *nx1* (but excluding *nx1*-th column) is specified.
  520. """
  521. return super().new_locator(nx, 0, nx1, 0)
  522. def _locate(self, nx, ny, nx1, ny1, axes, renderer):
  523. # docstring inherited
  524. nx += self._xrefindex
  525. nx1 += self._xrefindex
  526. fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
  527. x, y, w, h = self.get_position_runtime(axes, renderer)
  528. summed_ws = self.get_horizontal_sizes(renderer)
  529. equal_hs = self.get_vertical_sizes(renderer)
  530. x0, y0, ox, hh = _locate(
  531. x, y, w, h, summed_ws, equal_hs, fig_w, fig_h, self.get_anchor())
  532. if nx1 is None:
  533. nx1 = -1
  534. x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w
  535. y1, h1 = y0, hh
  536. return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
  537. class VBoxDivider(SubplotDivider):
  538. """
  539. A `.SubplotDivider` for laying out axes vertically, while ensuring that
  540. they have equal widths.
  541. """
  542. def new_locator(self, ny, ny1=None):
  543. """
  544. Create an axes locator callable for the specified cell.
  545. Parameters
  546. ----------
  547. ny, ny1 : int
  548. Integers specifying the row-position of the
  549. cell. When *ny1* is None, a single *ny*-th row is
  550. specified. Otherwise, location of rows spanning between *ny*
  551. to *ny1* (but excluding *ny1*-th row) is specified.
  552. """
  553. return super().new_locator(0, ny, 0, ny1)
  554. def _locate(self, nx, ny, nx1, ny1, axes, renderer):
  555. # docstring inherited
  556. ny += self._yrefindex
  557. ny1 += self._yrefindex
  558. fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
  559. x, y, w, h = self.get_position_runtime(axes, renderer)
  560. summed_hs = self.get_vertical_sizes(renderer)
  561. equal_ws = self.get_horizontal_sizes(renderer)
  562. y0, x0, oy, ww = _locate(
  563. y, x, h, w, summed_hs, equal_ws, fig_h, fig_w, self.get_anchor())
  564. if ny1 is None:
  565. ny1 = -1
  566. x1, w1 = x0, ww
  567. y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h
  568. return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
  569. def make_axes_locatable(axes):
  570. divider = AxesDivider(axes)
  571. locator = divider.new_locator(nx=0, ny=0)
  572. axes.set_axes_locator(locator)
  573. return divider
  574. def make_axes_area_auto_adjustable(
  575. ax, use_axes=None, pad=0.1, adjust_dirs=None):
  576. """
  577. Add auto-adjustable padding around *ax* to take its decorations (title,
  578. labels, ticks, ticklabels) into account during layout, using
  579. `.Divider.add_auto_adjustable_area`.
  580. By default, padding is determined from the decorations of *ax*.
  581. Pass *use_axes* to consider the decorations of other Axes instead.
  582. """
  583. if adjust_dirs is None:
  584. adjust_dirs = ["left", "right", "bottom", "top"]
  585. divider = make_axes_locatable(ax)
  586. if use_axes is None:
  587. use_axes = ax
  588. divider.add_auto_adjustable_area(use_axes=use_axes, pad=pad,
  589. adjust_dirs=adjust_dirs)