_layoutgrid.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. """
  2. A layoutgrid is a nrows by ncols set of boxes, meant to be used by
  3. `._constrained_layout`, each box is analogous to a subplotspec element of
  4. a gridspec.
  5. Each box is defined by left[ncols], right[ncols], bottom[nrows] and top[nrows],
  6. and by two editable margins for each side. The main margin gets its value
  7. set by the size of ticklabels, titles, etc on each axes that is in the figure.
  8. The outer margin is the padding around the axes, and space for any
  9. colorbars.
  10. The "inner" widths and heights of these boxes are then constrained to be the
  11. same (relative the values of `width_ratios[ncols]` and `height_ratios[nrows]`).
  12. The layoutgrid is then constrained to be contained within a parent layoutgrid,
  13. its column(s) and row(s) specified when it is created.
  14. """
  15. import itertools
  16. import kiwisolver as kiwi
  17. import logging
  18. import numpy as np
  19. import matplotlib as mpl
  20. import matplotlib.patches as mpatches
  21. from matplotlib.transforms import Bbox
  22. _log = logging.getLogger(__name__)
  23. class LayoutGrid:
  24. """
  25. Analogous to a gridspec, and contained in another LayoutGrid.
  26. """
  27. def __init__(self, parent=None, parent_pos=(0, 0),
  28. parent_inner=False, name='', ncols=1, nrows=1,
  29. h_pad=None, w_pad=None, width_ratios=None,
  30. height_ratios=None):
  31. Variable = kiwi.Variable
  32. self.parent_pos = parent_pos
  33. self.parent_inner = parent_inner
  34. self.name = name + seq_id()
  35. if isinstance(parent, LayoutGrid):
  36. self.name = f'{parent.name}.{self.name}'
  37. self.nrows = nrows
  38. self.ncols = ncols
  39. self.height_ratios = np.atleast_1d(height_ratios)
  40. if height_ratios is None:
  41. self.height_ratios = np.ones(nrows)
  42. self.width_ratios = np.atleast_1d(width_ratios)
  43. if width_ratios is None:
  44. self.width_ratios = np.ones(ncols)
  45. sn = self.name + '_'
  46. if not isinstance(parent, LayoutGrid):
  47. # parent can be a rect if not a LayoutGrid
  48. # allows specifying a rectangle to contain the layout.
  49. self.solver = kiwi.Solver()
  50. else:
  51. parent.add_child(self, *parent_pos)
  52. self.solver = parent.solver
  53. # keep track of artist associated w/ this layout. Can be none
  54. self.artists = np.empty((nrows, ncols), dtype=object)
  55. self.children = np.empty((nrows, ncols), dtype=object)
  56. self.margins = {}
  57. self.margin_vals = {}
  58. # all the boxes in each column share the same left/right margins:
  59. for todo in ['left', 'right', 'leftcb', 'rightcb']:
  60. # track the value so we can change only if a margin is larger
  61. # than the current value
  62. self.margin_vals[todo] = np.zeros(ncols)
  63. sol = self.solver
  64. self.lefts = [Variable(f'{sn}lefts[{i}]') for i in range(ncols)]
  65. self.rights = [Variable(f'{sn}rights[{i}]') for i in range(ncols)]
  66. for todo in ['left', 'right', 'leftcb', 'rightcb']:
  67. self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]')
  68. for i in range(ncols)]
  69. for i in range(ncols):
  70. sol.addEditVariable(self.margins[todo][i], 'strong')
  71. for todo in ['bottom', 'top', 'bottomcb', 'topcb']:
  72. self.margins[todo] = np.empty((nrows), dtype=object)
  73. self.margin_vals[todo] = np.zeros(nrows)
  74. self.bottoms = [Variable(f'{sn}bottoms[{i}]') for i in range(nrows)]
  75. self.tops = [Variable(f'{sn}tops[{i}]') for i in range(nrows)]
  76. for todo in ['bottom', 'top', 'bottomcb', 'topcb']:
  77. self.margins[todo] = [Variable(f'{sn}margins[{todo}][{i}]')
  78. for i in range(nrows)]
  79. for i in range(nrows):
  80. sol.addEditVariable(self.margins[todo][i], 'strong')
  81. # set these margins to zero by default. They will be edited as
  82. # children are filled.
  83. self.reset_margins()
  84. self.add_constraints(parent)
  85. self.h_pad = h_pad
  86. self.w_pad = w_pad
  87. def __repr__(self):
  88. str = f'LayoutBox: {self.name:25s} {self.nrows}x{self.ncols},\n'
  89. for i in range(self.nrows):
  90. for j in range(self.ncols):
  91. str += f'{i}, {j}: '\
  92. f'L{self.lefts[j].value():1.3f}, ' \
  93. f'B{self.bottoms[i].value():1.3f}, ' \
  94. f'R{self.rights[j].value():1.3f}, ' \
  95. f'T{self.tops[i].value():1.3f}, ' \
  96. f'ML{self.margins["left"][j].value():1.3f}, ' \
  97. f'MR{self.margins["right"][j].value():1.3f}, ' \
  98. f'MB{self.margins["bottom"][i].value():1.3f}, ' \
  99. f'MT{self.margins["top"][i].value():1.3f}, \n'
  100. return str
  101. def reset_margins(self):
  102. """
  103. Reset all the margins to zero. Must do this after changing
  104. figure size, for instance, because the relative size of the
  105. axes labels etc changes.
  106. """
  107. for todo in ['left', 'right', 'bottom', 'top',
  108. 'leftcb', 'rightcb', 'bottomcb', 'topcb']:
  109. self.edit_margins(todo, 0.0)
  110. def add_constraints(self, parent):
  111. # define self-consistent constraints
  112. self.hard_constraints()
  113. # define relationship with parent layoutgrid:
  114. self.parent_constraints(parent)
  115. # define relative widths of the grid cells to each other
  116. # and stack horizontally and vertically.
  117. self.grid_constraints()
  118. def hard_constraints(self):
  119. """
  120. These are the redundant constraints, plus ones that make the
  121. rest of the code easier.
  122. """
  123. for i in range(self.ncols):
  124. hc = [self.rights[i] >= self.lefts[i],
  125. (self.rights[i] - self.margins['right'][i] -
  126. self.margins['rightcb'][i] >=
  127. self.lefts[i] - self.margins['left'][i] -
  128. self.margins['leftcb'][i])
  129. ]
  130. for c in hc:
  131. self.solver.addConstraint(c | 'required')
  132. for i in range(self.nrows):
  133. hc = [self.tops[i] >= self.bottoms[i],
  134. (self.tops[i] - self.margins['top'][i] -
  135. self.margins['topcb'][i] >=
  136. self.bottoms[i] - self.margins['bottom'][i] -
  137. self.margins['bottomcb'][i])
  138. ]
  139. for c in hc:
  140. self.solver.addConstraint(c | 'required')
  141. def add_child(self, child, i=0, j=0):
  142. # np.ix_ returns the cross product of i and j indices
  143. self.children[np.ix_(np.atleast_1d(i), np.atleast_1d(j))] = child
  144. def parent_constraints(self, parent):
  145. # constraints that are due to the parent...
  146. # i.e. the first column's left is equal to the
  147. # parent's left, the last column right equal to the
  148. # parent's right...
  149. if not isinstance(parent, LayoutGrid):
  150. # specify a rectangle in figure coordinates
  151. hc = [self.lefts[0] == parent[0],
  152. self.rights[-1] == parent[0] + parent[2],
  153. # top and bottom reversed order...
  154. self.tops[0] == parent[1] + parent[3],
  155. self.bottoms[-1] == parent[1]]
  156. else:
  157. rows, cols = self.parent_pos
  158. rows = np.atleast_1d(rows)
  159. cols = np.atleast_1d(cols)
  160. left = parent.lefts[cols[0]]
  161. right = parent.rights[cols[-1]]
  162. top = parent.tops[rows[0]]
  163. bottom = parent.bottoms[rows[-1]]
  164. if self.parent_inner:
  165. # the layout grid is contained inside the inner
  166. # grid of the parent.
  167. left += parent.margins['left'][cols[0]]
  168. left += parent.margins['leftcb'][cols[0]]
  169. right -= parent.margins['right'][cols[-1]]
  170. right -= parent.margins['rightcb'][cols[-1]]
  171. top -= parent.margins['top'][rows[0]]
  172. top -= parent.margins['topcb'][rows[0]]
  173. bottom += parent.margins['bottom'][rows[-1]]
  174. bottom += parent.margins['bottomcb'][rows[-1]]
  175. hc = [self.lefts[0] == left,
  176. self.rights[-1] == right,
  177. # from top to bottom
  178. self.tops[0] == top,
  179. self.bottoms[-1] == bottom]
  180. for c in hc:
  181. self.solver.addConstraint(c | 'required')
  182. def grid_constraints(self):
  183. # constrain the ratio of the inner part of the grids
  184. # to be the same (relative to width_ratios)
  185. # constrain widths:
  186. w = (self.rights[0] - self.margins['right'][0] -
  187. self.margins['rightcb'][0])
  188. w = (w - self.lefts[0] - self.margins['left'][0] -
  189. self.margins['leftcb'][0])
  190. w0 = w / self.width_ratios[0]
  191. # from left to right
  192. for i in range(1, self.ncols):
  193. w = (self.rights[i] - self.margins['right'][i] -
  194. self.margins['rightcb'][i])
  195. w = (w - self.lefts[i] - self.margins['left'][i] -
  196. self.margins['leftcb'][i])
  197. c = (w == w0 * self.width_ratios[i])
  198. self.solver.addConstraint(c | 'strong')
  199. # constrain the grid cells to be directly next to each other.
  200. c = (self.rights[i - 1] == self.lefts[i])
  201. self.solver.addConstraint(c | 'strong')
  202. # constrain heights:
  203. h = self.tops[0] - self.margins['top'][0] - self.margins['topcb'][0]
  204. h = (h - self.bottoms[0] - self.margins['bottom'][0] -
  205. self.margins['bottomcb'][0])
  206. h0 = h / self.height_ratios[0]
  207. # from top to bottom:
  208. for i in range(1, self.nrows):
  209. h = (self.tops[i] - self.margins['top'][i] -
  210. self.margins['topcb'][i])
  211. h = (h - self.bottoms[i] - self.margins['bottom'][i] -
  212. self.margins['bottomcb'][i])
  213. c = (h == h0 * self.height_ratios[i])
  214. self.solver.addConstraint(c | 'strong')
  215. # constrain the grid cells to be directly above each other.
  216. c = (self.bottoms[i - 1] == self.tops[i])
  217. self.solver.addConstraint(c | 'strong')
  218. # Margin editing: The margins are variable and meant to
  219. # contain things of a fixed size like axes labels, tick labels, titles
  220. # etc
  221. def edit_margin(self, todo, size, cell):
  222. """
  223. Change the size of the margin for one cell.
  224. Parameters
  225. ----------
  226. todo : string (one of 'left', 'right', 'bottom', 'top')
  227. margin to alter.
  228. size : float
  229. Size of the margin. If it is larger than the existing minimum it
  230. updates the margin size. Fraction of figure size.
  231. cell : int
  232. Cell column or row to edit.
  233. """
  234. self.solver.suggestValue(self.margins[todo][cell], size)
  235. self.margin_vals[todo][cell] = size
  236. def edit_margin_min(self, todo, size, cell=0):
  237. """
  238. Change the minimum size of the margin for one cell.
  239. Parameters
  240. ----------
  241. todo : string (one of 'left', 'right', 'bottom', 'top')
  242. margin to alter.
  243. size : float
  244. Minimum size of the margin . If it is larger than the
  245. existing minimum it updates the margin size. Fraction of
  246. figure size.
  247. cell : int
  248. Cell column or row to edit.
  249. """
  250. if size > self.margin_vals[todo][cell]:
  251. self.edit_margin(todo, size, cell)
  252. def edit_margins(self, todo, size):
  253. """
  254. Change the size of all the margin of all the cells in the layout grid.
  255. Parameters
  256. ----------
  257. todo : string (one of 'left', 'right', 'bottom', 'top')
  258. margin to alter.
  259. size : float
  260. Size to set the margins. Fraction of figure size.
  261. """
  262. for i in range(len(self.margin_vals[todo])):
  263. self.edit_margin(todo, size, i)
  264. def edit_all_margins_min(self, todo, size):
  265. """
  266. Change the minimum size of all the margin of all
  267. the cells in the layout grid.
  268. Parameters
  269. ----------
  270. todo : {'left', 'right', 'bottom', 'top'}
  271. The margin to alter.
  272. size : float
  273. Minimum size of the margin. If it is larger than the
  274. existing minimum it updates the margin size. Fraction of
  275. figure size.
  276. """
  277. for i in range(len(self.margin_vals[todo])):
  278. self.edit_margin_min(todo, size, i)
  279. def edit_outer_margin_mins(self, margin, ss):
  280. """
  281. Edit all four margin minimums in one statement.
  282. Parameters
  283. ----------
  284. margin : dict
  285. size of margins in a dict with keys 'left', 'right', 'bottom',
  286. 'top'
  287. ss : SubplotSpec
  288. defines the subplotspec these margins should be applied to
  289. """
  290. self.edit_margin_min('left', margin['left'], ss.colspan.start)
  291. self.edit_margin_min('leftcb', margin['leftcb'], ss.colspan.start)
  292. self.edit_margin_min('right', margin['right'], ss.colspan.stop - 1)
  293. self.edit_margin_min('rightcb', margin['rightcb'], ss.colspan.stop - 1)
  294. # rows are from the top down:
  295. self.edit_margin_min('top', margin['top'], ss.rowspan.start)
  296. self.edit_margin_min('topcb', margin['topcb'], ss.rowspan.start)
  297. self.edit_margin_min('bottom', margin['bottom'], ss.rowspan.stop - 1)
  298. self.edit_margin_min('bottomcb', margin['bottomcb'],
  299. ss.rowspan.stop - 1)
  300. def get_margins(self, todo, col):
  301. """Return the margin at this position"""
  302. return self.margin_vals[todo][col]
  303. def get_outer_bbox(self, rows=0, cols=0):
  304. """
  305. Return the outer bounding box of the subplot specs
  306. given by rows and cols. rows and cols can be spans.
  307. """
  308. rows = np.atleast_1d(rows)
  309. cols = np.atleast_1d(cols)
  310. bbox = Bbox.from_extents(
  311. self.lefts[cols[0]].value(),
  312. self.bottoms[rows[-1]].value(),
  313. self.rights[cols[-1]].value(),
  314. self.tops[rows[0]].value())
  315. return bbox
  316. def get_inner_bbox(self, rows=0, cols=0):
  317. """
  318. Return the inner bounding box of the subplot specs
  319. given by rows and cols. rows and cols can be spans.
  320. """
  321. rows = np.atleast_1d(rows)
  322. cols = np.atleast_1d(cols)
  323. bbox = Bbox.from_extents(
  324. (self.lefts[cols[0]].value() +
  325. self.margins['left'][cols[0]].value() +
  326. self.margins['leftcb'][cols[0]].value()),
  327. (self.bottoms[rows[-1]].value() +
  328. self.margins['bottom'][rows[-1]].value() +
  329. self.margins['bottomcb'][rows[-1]].value()),
  330. (self.rights[cols[-1]].value() -
  331. self.margins['right'][cols[-1]].value() -
  332. self.margins['rightcb'][cols[-1]].value()),
  333. (self.tops[rows[0]].value() -
  334. self.margins['top'][rows[0]].value() -
  335. self.margins['topcb'][rows[0]].value())
  336. )
  337. return bbox
  338. def get_bbox_for_cb(self, rows=0, cols=0):
  339. """
  340. Return the bounding box that includes the
  341. decorations but, *not* the colorbar...
  342. """
  343. rows = np.atleast_1d(rows)
  344. cols = np.atleast_1d(cols)
  345. bbox = Bbox.from_extents(
  346. (self.lefts[cols[0]].value() +
  347. self.margins['leftcb'][cols[0]].value()),
  348. (self.bottoms[rows[-1]].value() +
  349. self.margins['bottomcb'][rows[-1]].value()),
  350. (self.rights[cols[-1]].value() -
  351. self.margins['rightcb'][cols[-1]].value()),
  352. (self.tops[rows[0]].value() -
  353. self.margins['topcb'][rows[0]].value())
  354. )
  355. return bbox
  356. def get_left_margin_bbox(self, rows=0, cols=0):
  357. """
  358. Return the left margin bounding box of the subplot specs
  359. given by rows and cols. rows and cols can be spans.
  360. """
  361. rows = np.atleast_1d(rows)
  362. cols = np.atleast_1d(cols)
  363. bbox = Bbox.from_extents(
  364. (self.lefts[cols[0]].value() +
  365. self.margins['leftcb'][cols[0]].value()),
  366. (self.bottoms[rows[-1]].value()),
  367. (self.lefts[cols[0]].value() +
  368. self.margins['leftcb'][cols[0]].value() +
  369. self.margins['left'][cols[0]].value()),
  370. (self.tops[rows[0]].value()))
  371. return bbox
  372. def get_bottom_margin_bbox(self, rows=0, cols=0):
  373. """
  374. Return the left margin bounding box of the subplot specs
  375. given by rows and cols. rows and cols can be spans.
  376. """
  377. rows = np.atleast_1d(rows)
  378. cols = np.atleast_1d(cols)
  379. bbox = Bbox.from_extents(
  380. (self.lefts[cols[0]].value()),
  381. (self.bottoms[rows[-1]].value() +
  382. self.margins['bottomcb'][rows[-1]].value()),
  383. (self.rights[cols[-1]].value()),
  384. (self.bottoms[rows[-1]].value() +
  385. self.margins['bottom'][rows[-1]].value() +
  386. self.margins['bottomcb'][rows[-1]].value()
  387. ))
  388. return bbox
  389. def get_right_margin_bbox(self, rows=0, cols=0):
  390. """
  391. Return the left margin bounding box of the subplot specs
  392. given by rows and cols. rows and cols can be spans.
  393. """
  394. rows = np.atleast_1d(rows)
  395. cols = np.atleast_1d(cols)
  396. bbox = Bbox.from_extents(
  397. (self.rights[cols[-1]].value() -
  398. self.margins['right'][cols[-1]].value() -
  399. self.margins['rightcb'][cols[-1]].value()),
  400. (self.bottoms[rows[-1]].value()),
  401. (self.rights[cols[-1]].value() -
  402. self.margins['rightcb'][cols[-1]].value()),
  403. (self.tops[rows[0]].value()))
  404. return bbox
  405. def get_top_margin_bbox(self, rows=0, cols=0):
  406. """
  407. Return the left margin bounding box of the subplot specs
  408. given by rows and cols. rows and cols can be spans.
  409. """
  410. rows = np.atleast_1d(rows)
  411. cols = np.atleast_1d(cols)
  412. bbox = Bbox.from_extents(
  413. (self.lefts[cols[0]].value()),
  414. (self.tops[rows[0]].value() -
  415. self.margins['topcb'][rows[0]].value()),
  416. (self.rights[cols[-1]].value()),
  417. (self.tops[rows[0]].value() -
  418. self.margins['topcb'][rows[0]].value() -
  419. self.margins['top'][rows[0]].value()))
  420. return bbox
  421. def update_variables(self):
  422. """
  423. Update the variables for the solver attached to this layoutgrid.
  424. """
  425. self.solver.updateVariables()
  426. _layoutboxobjnum = itertools.count()
  427. def seq_id():
  428. """Generate a short sequential id for layoutbox objects."""
  429. return '%06d' % next(_layoutboxobjnum)
  430. def plot_children(fig, lg=None, level=0):
  431. """Simple plotting to show where boxes are."""
  432. if lg is None:
  433. _layoutgrids = fig.get_layout_engine().execute(fig)
  434. lg = _layoutgrids[fig]
  435. colors = mpl.rcParams["axes.prop_cycle"].by_key()["color"]
  436. col = colors[level]
  437. for i in range(lg.nrows):
  438. for j in range(lg.ncols):
  439. bb = lg.get_outer_bbox(rows=i, cols=j)
  440. fig.add_artist(
  441. mpatches.Rectangle(bb.p0, bb.width, bb.height, linewidth=1,
  442. edgecolor='0.7', facecolor='0.7',
  443. alpha=0.2, transform=fig.transFigure,
  444. zorder=-3))
  445. bbi = lg.get_inner_bbox(rows=i, cols=j)
  446. fig.add_artist(
  447. mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=2,
  448. edgecolor=col, facecolor='none',
  449. transform=fig.transFigure, zorder=-2))
  450. bbi = lg.get_left_margin_bbox(rows=i, cols=j)
  451. fig.add_artist(
  452. mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
  453. edgecolor='none', alpha=0.2,
  454. facecolor=[0.5, 0.7, 0.5],
  455. transform=fig.transFigure, zorder=-2))
  456. bbi = lg.get_right_margin_bbox(rows=i, cols=j)
  457. fig.add_artist(
  458. mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
  459. edgecolor='none', alpha=0.2,
  460. facecolor=[0.7, 0.5, 0.5],
  461. transform=fig.transFigure, zorder=-2))
  462. bbi = lg.get_bottom_margin_bbox(rows=i, cols=j)
  463. fig.add_artist(
  464. mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
  465. edgecolor='none', alpha=0.2,
  466. facecolor=[0.5, 0.5, 0.7],
  467. transform=fig.transFigure, zorder=-2))
  468. bbi = lg.get_top_margin_bbox(rows=i, cols=j)
  469. fig.add_artist(
  470. mpatches.Rectangle(bbi.p0, bbi.width, bbi.height, linewidth=0,
  471. edgecolor='none', alpha=0.2,
  472. facecolor=[0.7, 0.2, 0.7],
  473. transform=fig.transFigure, zorder=-2))
  474. for ch in lg.children.flat:
  475. if ch is not None:
  476. plot_children(fig, ch, level=level+1)