_layoutbox.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. """
  2. Conventions:
  3. "constrain_x" means to constrain the variable with either
  4. another kiwisolver variable, or a float. i.e. `constrain_width(0.2)`
  5. will set a constraint that the width has to be 0.2 and this constraint is
  6. permanent - i.e. it will not be removed if it becomes obsolete.
  7. "edit_x" means to set x to a value (just a float), and that this value can
  8. change. So `edit_width(0.2)` will set width to be 0.2, but `edit_width(0.3)`
  9. will allow it to change to 0.3 later. Note that these values are still just
  10. "suggestions" in `kiwisolver` parlance, and could be over-ridden by
  11. other constrains.
  12. """
  13. import itertools
  14. import kiwisolver as kiwi
  15. import logging
  16. import numpy as np
  17. _log = logging.getLogger(__name__)
  18. # renderers can be complicated
  19. def get_renderer(fig):
  20. if fig._cachedRenderer:
  21. renderer = fig._cachedRenderer
  22. else:
  23. canvas = fig.canvas
  24. if canvas and hasattr(canvas, "get_renderer"):
  25. renderer = canvas.get_renderer()
  26. else:
  27. # not sure if this can happen
  28. # seems to with PDF...
  29. _log.info("constrained_layout : falling back to Agg renderer")
  30. from matplotlib.backends.backend_agg import FigureCanvasAgg
  31. canvas = FigureCanvasAgg(fig)
  32. renderer = canvas.get_renderer()
  33. return renderer
  34. class LayoutBox:
  35. """
  36. Basic rectangle representation using kiwi solver variables
  37. """
  38. def __init__(self, parent=None, name='', tightwidth=False,
  39. tightheight=False, artist=None,
  40. lower_left=(0, 0), upper_right=(1, 1), pos=False,
  41. subplot=False, h_pad=None, w_pad=None):
  42. Variable = kiwi.Variable
  43. self.parent = parent
  44. self.name = name
  45. sn = self.name + '_'
  46. if parent is None:
  47. self.solver = kiwi.Solver()
  48. self.constrained_layout_called = 0
  49. else:
  50. self.solver = parent.solver
  51. self.constrained_layout_called = None
  52. # parent wants to know about this child!
  53. parent.add_child(self)
  54. # keep track of artist associated w/ this layout. Can be none
  55. self.artist = artist
  56. # keep track if this box is supposed to be a pos that is constrained
  57. # by the parent.
  58. self.pos = pos
  59. # keep track of whether we need to match this subplot up with others.
  60. self.subplot = subplot
  61. self.top = Variable(sn + 'top')
  62. self.bottom = Variable(sn + 'bottom')
  63. self.left = Variable(sn + 'left')
  64. self.right = Variable(sn + 'right')
  65. self.width = Variable(sn + 'width')
  66. self.height = Variable(sn + 'height')
  67. self.h_center = Variable(sn + 'h_center')
  68. self.v_center = Variable(sn + 'v_center')
  69. self.min_width = Variable(sn + 'min_width')
  70. self.min_height = Variable(sn + 'min_height')
  71. self.pref_width = Variable(sn + 'pref_width')
  72. self.pref_height = Variable(sn + 'pref_height')
  73. # margins are only used for axes-position layout boxes. maybe should
  74. # be a separate subclass:
  75. self.left_margin = Variable(sn + 'left_margin')
  76. self.right_margin = Variable(sn + 'right_margin')
  77. self.bottom_margin = Variable(sn + 'bottom_margin')
  78. self.top_margin = Variable(sn + 'top_margin')
  79. # mins
  80. self.left_margin_min = Variable(sn + 'left_margin_min')
  81. self.right_margin_min = Variable(sn + 'right_margin_min')
  82. self.bottom_margin_min = Variable(sn + 'bottom_margin_min')
  83. self.top_margin_min = Variable(sn + 'top_margin_min')
  84. right, top = upper_right
  85. left, bottom = lower_left
  86. self.tightheight = tightheight
  87. self.tightwidth = tightwidth
  88. self.add_constraints()
  89. self.children = []
  90. self.subplotspec = None
  91. if self.pos:
  92. self.constrain_margins()
  93. self.h_pad = h_pad
  94. self.w_pad = w_pad
  95. def constrain_margins(self):
  96. """
  97. Only do this for pos. This sets a variable distance
  98. margin between the position of the axes and the outer edge of
  99. the axes.
  100. Margins are variable because they change with the figure size.
  101. Margin minimums are set to make room for axes decorations. However,
  102. the margins can be larger if we are mathicng the position size to
  103. other axes.
  104. """
  105. sol = self.solver
  106. # left
  107. if not sol.hasEditVariable(self.left_margin_min):
  108. sol.addEditVariable(self.left_margin_min, 'strong')
  109. sol.suggestValue(self.left_margin_min, 0.0001)
  110. c = (self.left_margin == self.left - self.parent.left)
  111. self.solver.addConstraint(c | 'required')
  112. c = (self.left_margin >= self.left_margin_min)
  113. self.solver.addConstraint(c | 'strong')
  114. # right
  115. if not sol.hasEditVariable(self.right_margin_min):
  116. sol.addEditVariable(self.right_margin_min, 'strong')
  117. sol.suggestValue(self.right_margin_min, 0.0001)
  118. c = (self.right_margin == self.parent.right - self.right)
  119. self.solver.addConstraint(c | 'required')
  120. c = (self.right_margin >= self.right_margin_min)
  121. self.solver.addConstraint(c | 'required')
  122. # bottom
  123. if not sol.hasEditVariable(self.bottom_margin_min):
  124. sol.addEditVariable(self.bottom_margin_min, 'strong')
  125. sol.suggestValue(self.bottom_margin_min, 0.0001)
  126. c = (self.bottom_margin == self.bottom - self.parent.bottom)
  127. self.solver.addConstraint(c | 'required')
  128. c = (self.bottom_margin >= self.bottom_margin_min)
  129. self.solver.addConstraint(c | 'required')
  130. # top
  131. if not sol.hasEditVariable(self.top_margin_min):
  132. sol.addEditVariable(self.top_margin_min, 'strong')
  133. sol.suggestValue(self.top_margin_min, 0.0001)
  134. c = (self.top_margin == self.parent.top - self.top)
  135. self.solver.addConstraint(c | 'required')
  136. c = (self.top_margin >= self.top_margin_min)
  137. self.solver.addConstraint(c | 'required')
  138. def add_child(self, child):
  139. self.children += [child]
  140. def remove_child(self, child):
  141. try:
  142. self.children.remove(child)
  143. except ValueError:
  144. _log.info("Tried to remove child that doesn't belong to parent")
  145. def add_constraints(self):
  146. sol = self.solver
  147. # never let width and height go negative.
  148. for i in [self.min_width, self.min_height]:
  149. sol.addEditVariable(i, 1e9)
  150. sol.suggestValue(i, 0.0)
  151. # define relation ships between things thing width and right and left
  152. self.hard_constraints()
  153. # self.soft_constraints()
  154. if self.parent:
  155. self.parent_constrain()
  156. # sol.updateVariables()
  157. def parent_constrain(self):
  158. parent = self.parent
  159. hc = [self.left >= parent.left,
  160. self.bottom >= parent.bottom,
  161. self.top <= parent.top,
  162. self.right <= parent.right]
  163. for c in hc:
  164. self.solver.addConstraint(c | 'required')
  165. def hard_constraints(self):
  166. hc = [self.width == self.right - self.left,
  167. self.height == self.top - self.bottom,
  168. self.h_center == (self.left + self.right) * 0.5,
  169. self.v_center == (self.top + self.bottom) * 0.5,
  170. self.width >= self.min_width,
  171. self.height >= self.min_height]
  172. for c in hc:
  173. self.solver.addConstraint(c | 'required')
  174. def soft_constraints(self):
  175. sol = self.solver
  176. if self.tightwidth:
  177. suggest = 0.
  178. else:
  179. suggest = 20.
  180. c = (self.pref_width == suggest)
  181. for i in c:
  182. sol.addConstraint(i | 'required')
  183. if self.tightheight:
  184. suggest = 0.
  185. else:
  186. suggest = 20.
  187. c = (self.pref_height == suggest)
  188. for i in c:
  189. sol.addConstraint(i | 'required')
  190. c = [(self.width >= suggest),
  191. (self.height >= suggest)]
  192. for i in c:
  193. sol.addConstraint(i | 150000)
  194. def set_parent(self, parent):
  195. """Replace the parent of this with the new parent."""
  196. self.parent = parent
  197. self.parent_constrain()
  198. def constrain_geometry(self, left, bottom, right, top, strength='strong'):
  199. hc = [self.left == left,
  200. self.right == right,
  201. self.bottom == bottom,
  202. self.top == top]
  203. for c in hc:
  204. self.solver.addConstraint(c | strength)
  205. # self.solver.updateVariables()
  206. def constrain_same(self, other, strength='strong'):
  207. """
  208. Make the layoutbox have same position as other layoutbox
  209. """
  210. hc = [self.left == other.left,
  211. self.right == other.right,
  212. self.bottom == other.bottom,
  213. self.top == other.top]
  214. for c in hc:
  215. self.solver.addConstraint(c | strength)
  216. def constrain_left_margin(self, margin, strength='strong'):
  217. c = (self.left == self.parent.left + margin)
  218. self.solver.addConstraint(c | strength)
  219. def edit_left_margin_min(self, margin):
  220. self.solver.suggestValue(self.left_margin_min, margin)
  221. def constrain_right_margin(self, margin, strength='strong'):
  222. c = (self.right == self.parent.right - margin)
  223. self.solver.addConstraint(c | strength)
  224. def edit_right_margin_min(self, margin):
  225. self.solver.suggestValue(self.right_margin_min, margin)
  226. def constrain_bottom_margin(self, margin, strength='strong'):
  227. c = (self.bottom == self.parent.bottom + margin)
  228. self.solver.addConstraint(c | strength)
  229. def edit_bottom_margin_min(self, margin):
  230. self.solver.suggestValue(self.bottom_margin_min, margin)
  231. def constrain_top_margin(self, margin, strength='strong'):
  232. c = (self.top == self.parent.top - margin)
  233. self.solver.addConstraint(c | strength)
  234. def edit_top_margin_min(self, margin):
  235. self.solver.suggestValue(self.top_margin_min, margin)
  236. def get_rect(self):
  237. return (self.left.value(), self.bottom.value(),
  238. self.width.value(), self.height.value())
  239. def update_variables(self):
  240. """
  241. Update *all* the variables that are part of the solver this LayoutBox
  242. is created with.
  243. """
  244. self.solver.updateVariables()
  245. def edit_height(self, height, strength='strong'):
  246. """
  247. Set the height of the layout box.
  248. This is done as an editable variable so that the value can change
  249. due to resizing.
  250. """
  251. sol = self.solver
  252. for i in [self.height]:
  253. if not sol.hasEditVariable(i):
  254. sol.addEditVariable(i, strength)
  255. sol.suggestValue(self.height, height)
  256. def constrain_height(self, height, strength='strong'):
  257. """
  258. Constrain the height of the layout box. height is
  259. either a float or a layoutbox.height.
  260. """
  261. c = (self.height == height)
  262. self.solver.addConstraint(c | strength)
  263. def constrain_height_min(self, height, strength='strong'):
  264. c = (self.height >= height)
  265. self.solver.addConstraint(c | strength)
  266. def edit_width(self, width, strength='strong'):
  267. sol = self.solver
  268. for i in [self.width]:
  269. if not sol.hasEditVariable(i):
  270. sol.addEditVariable(i, strength)
  271. sol.suggestValue(self.width, width)
  272. def constrain_width(self, width, strength='strong'):
  273. """
  274. Constrain the width of the layout box. *width* is
  275. either a float or a layoutbox.width.
  276. """
  277. c = (self.width == width)
  278. self.solver.addConstraint(c | strength)
  279. def constrain_width_min(self, width, strength='strong'):
  280. c = (self.width >= width)
  281. self.solver.addConstraint(c | strength)
  282. def constrain_left(self, left, strength='strong'):
  283. c = (self.left == left)
  284. self.solver.addConstraint(c | strength)
  285. def constrain_bottom(self, bottom, strength='strong'):
  286. c = (self.bottom == bottom)
  287. self.solver.addConstraint(c | strength)
  288. def constrain_right(self, right, strength='strong'):
  289. c = (self.right == right)
  290. self.solver.addConstraint(c | strength)
  291. def constrain_top(self, top, strength='strong'):
  292. c = (self.top == top)
  293. self.solver.addConstraint(c | strength)
  294. def _is_subplotspec_layoutbox(self):
  295. """
  296. Helper to check if this layoutbox is the layoutbox of a subplotspec.
  297. """
  298. name = self.name.split('.')[-1]
  299. return name[:2] == 'ss'
  300. def _is_gridspec_layoutbox(self):
  301. """
  302. Helper to check if this layoutbox is the layoutbox of a gridspec.
  303. """
  304. name = self.name.split('.')[-1]
  305. return name[:8] == 'gridspec'
  306. def find_child_subplots(self):
  307. """
  308. Find children of this layout box that are subplots. We want to line
  309. poss up, and this is an easy way to find them all.
  310. """
  311. if self.subplot:
  312. subplots = [self]
  313. else:
  314. subplots = []
  315. for child in self.children:
  316. subplots += child.find_child_subplots()
  317. return subplots
  318. def layout_from_subplotspec(self, subspec,
  319. name='', artist=None, pos=False):
  320. """
  321. Make a layout box from a subplotspec. The layout box is
  322. constrained to be a fraction of the width/height of the parent,
  323. and be a fraction of the parent width/height from the left/bottom
  324. of the parent. Therefore the parent can move around and the
  325. layout for the subplot spec should move with it.
  326. The parent is *usually* the gridspec that made the subplotspec.??
  327. """
  328. lb = LayoutBox(parent=self, name=name, artist=artist, pos=pos)
  329. gs = subspec.get_gridspec()
  330. nrows, ncols = gs.get_geometry()
  331. parent = self.parent
  332. # OK, now, we want to set the position of this subplotspec
  333. # based on its subplotspec parameters. The new gridspec will inherit
  334. # from gridspec. prob should be new method in gridspec
  335. left = 0.0
  336. right = 1.0
  337. bottom = 0.0
  338. top = 1.0
  339. totWidth = right-left
  340. totHeight = top-bottom
  341. hspace = 0.
  342. wspace = 0.
  343. # calculate accumulated heights of columns
  344. cellH = totHeight / (nrows + hspace * (nrows - 1))
  345. sepH = hspace * cellH
  346. if gs._row_height_ratios is not None:
  347. netHeight = cellH * nrows
  348. tr = sum(gs._row_height_ratios)
  349. cellHeights = [netHeight * r / tr for r in gs._row_height_ratios]
  350. else:
  351. cellHeights = [cellH] * nrows
  352. sepHeights = [0] + ([sepH] * (nrows - 1))
  353. cellHs = np.cumsum(np.column_stack([sepHeights, cellHeights]).flat)
  354. # calculate accumulated widths of rows
  355. cellW = totWidth / (ncols + wspace * (ncols - 1))
  356. sepW = wspace * cellW
  357. if gs._col_width_ratios is not None:
  358. netWidth = cellW * ncols
  359. tr = sum(gs._col_width_ratios)
  360. cellWidths = [netWidth * r / tr for r in gs._col_width_ratios]
  361. else:
  362. cellWidths = [cellW] * ncols
  363. sepWidths = [0] + ([sepW] * (ncols - 1))
  364. cellWs = np.cumsum(np.column_stack([sepWidths, cellWidths]).flat)
  365. figTops = [top - cellHs[2 * rowNum] for rowNum in range(nrows)]
  366. figBottoms = [top - cellHs[2 * rowNum + 1] for rowNum in range(nrows)]
  367. figLefts = [left + cellWs[2 * colNum] for colNum in range(ncols)]
  368. figRights = [left + cellWs[2 * colNum + 1] for colNum in range(ncols)]
  369. rowNum1, colNum1 = divmod(subspec.num1, ncols)
  370. rowNum2, colNum2 = divmod(subspec.num2, ncols)
  371. figBottom = min(figBottoms[rowNum1], figBottoms[rowNum2])
  372. figTop = max(figTops[rowNum1], figTops[rowNum2])
  373. figLeft = min(figLefts[colNum1], figLefts[colNum2])
  374. figRight = max(figRights[colNum1], figRights[colNum2])
  375. # These are numbers relative to (0, 0, 1, 1). Need to constrain
  376. # relative to parent.
  377. width = figRight - figLeft
  378. height = figTop - figBottom
  379. parent = self.parent
  380. cs = [self.left == parent.left + parent.width * figLeft,
  381. self.bottom == parent.bottom + parent.height * figBottom,
  382. self.width == parent.width * width,
  383. self.height == parent.height * height]
  384. for c in cs:
  385. self.solver.addConstraint(c | 'required')
  386. return lb
  387. def __repr__(self):
  388. return (f'LayoutBox: {self.name:25s}, '
  389. f'(left: {self.left.value():1.3f}) '
  390. f'(bot: {self.bottom.value():1.3f}) '
  391. f'(right: {self.right.value():1.3f}) '
  392. f'(top: {self.top.value():1.3f})')
  393. # Utility functions that act on layoutboxes...
  394. def hstack(boxes, padding=0, strength='strong'):
  395. """
  396. Stack LayoutBox instances from left to right.
  397. *padding* is in figure-relative units.
  398. """
  399. for i in range(1, len(boxes)):
  400. c = (boxes[i-1].right + padding <= boxes[i].left)
  401. boxes[i].solver.addConstraint(c | strength)
  402. def hpack(boxes, padding=0, strength='strong'):
  403. """Stack LayoutBox instances from left to right."""
  404. for i in range(1, len(boxes)):
  405. c = (boxes[i-1].right + padding == boxes[i].left)
  406. boxes[i].solver.addConstraint(c | strength)
  407. def vstack(boxes, padding=0, strength='strong'):
  408. """Stack LayoutBox instances from top to bottom."""
  409. for i in range(1, len(boxes)):
  410. c = (boxes[i-1].bottom - padding >= boxes[i].top)
  411. boxes[i].solver.addConstraint(c | strength)
  412. def vpack(boxes, padding=0, strength='strong'):
  413. """Stack LayoutBox instances from top to bottom."""
  414. for i in range(1, len(boxes)):
  415. c = (boxes[i-1].bottom - padding >= boxes[i].top)
  416. boxes[i].solver.addConstraint(c | strength)
  417. def match_heights(boxes, height_ratios=None, strength='medium'):
  418. """Stack LayoutBox instances from top to bottom."""
  419. if height_ratios is None:
  420. height_ratios = np.ones(len(boxes))
  421. for i in range(1, len(boxes)):
  422. c = (boxes[i-1].height ==
  423. boxes[i].height*height_ratios[i-1]/height_ratios[i])
  424. boxes[i].solver.addConstraint(c | strength)
  425. def match_widths(boxes, width_ratios=None, strength='medium'):
  426. """Stack LayoutBox instances from top to bottom."""
  427. if width_ratios is None:
  428. width_ratios = np.ones(len(boxes))
  429. for i in range(1, len(boxes)):
  430. c = (boxes[i-1].width ==
  431. boxes[i].width*width_ratios[i-1]/width_ratios[i])
  432. boxes[i].solver.addConstraint(c | strength)
  433. def vstackeq(boxes, padding=0, height_ratios=None):
  434. vstack(boxes, padding=padding)
  435. match_heights(boxes, height_ratios=height_ratios)
  436. def hstackeq(boxes, padding=0, width_ratios=None):
  437. hstack(boxes, padding=padding)
  438. match_widths(boxes, width_ratios=width_ratios)
  439. def align(boxes, attr, strength='strong'):
  440. cons = []
  441. for box in boxes[1:]:
  442. cons = (getattr(boxes[0], attr) == getattr(box, attr))
  443. boxes[0].solver.addConstraint(cons | strength)
  444. def match_top_margins(boxes, levels=1):
  445. box0 = boxes[0]
  446. top0 = box0
  447. for n in range(levels):
  448. top0 = top0.parent
  449. for box in boxes[1:]:
  450. topb = box
  451. for n in range(levels):
  452. topb = topb.parent
  453. c = (box0.top-top0.top == box.top-topb.top)
  454. box0.solver.addConstraint(c | 'strong')
  455. def match_bottom_margins(boxes, levels=1):
  456. box0 = boxes[0]
  457. top0 = box0
  458. for n in range(levels):
  459. top0 = top0.parent
  460. for box in boxes[1:]:
  461. topb = box
  462. for n in range(levels):
  463. topb = topb.parent
  464. c = (box0.bottom-top0.bottom == box.bottom-topb.bottom)
  465. box0.solver.addConstraint(c | 'strong')
  466. def match_left_margins(boxes, levels=1):
  467. box0 = boxes[0]
  468. top0 = box0
  469. for n in range(levels):
  470. top0 = top0.parent
  471. for box in boxes[1:]:
  472. topb = box
  473. for n in range(levels):
  474. topb = topb.parent
  475. c = (box0.left-top0.left == box.left-topb.left)
  476. box0.solver.addConstraint(c | 'strong')
  477. def match_right_margins(boxes, levels=1):
  478. box0 = boxes[0]
  479. top0 = box0
  480. for n in range(levels):
  481. top0 = top0.parent
  482. for box in boxes[1:]:
  483. topb = box
  484. for n in range(levels):
  485. topb = topb.parent
  486. c = (box0.right-top0.right == box.right-topb.right)
  487. box0.solver.addConstraint(c | 'strong')
  488. def match_width_margins(boxes, levels=1):
  489. match_left_margins(boxes, levels=levels)
  490. match_right_margins(boxes, levels=levels)
  491. def match_height_margins(boxes, levels=1):
  492. match_top_margins(boxes, levels=levels)
  493. match_bottom_margins(boxes, levels=levels)
  494. def match_margins(boxes, levels=1):
  495. match_width_margins(boxes, levels=levels)
  496. match_height_margins(boxes, levels=levels)
  497. _layoutboxobjnum = itertools.count()
  498. def seq_id():
  499. """Generate a short sequential id for layoutbox objects."""
  500. return '%06d' % next(_layoutboxobjnum)
  501. def print_children(lb):
  502. """Print the children of the layoutbox."""
  503. print(lb)
  504. for child in lb.children:
  505. print_children(child)
  506. def nonetree(lb):
  507. """
  508. Make all elements in this tree None, signalling not to do any more layout.
  509. """
  510. if lb is not None:
  511. if lb.parent is None:
  512. # Clear the solver. Hopefully this garbage collects.
  513. lb.solver.reset()
  514. nonechildren(lb)
  515. else:
  516. nonetree(lb.parent)
  517. def nonechildren(lb):
  518. for child in lb.children:
  519. nonechildren(child)
  520. lb.artist._layoutbox = None
  521. lb = None
  522. def print_tree(lb):
  523. """Print the tree of layoutboxes."""
  524. if lb.parent is None:
  525. print('LayoutBox Tree\n')
  526. print('==============\n')
  527. print_children(lb)
  528. print('\n')
  529. else:
  530. print_tree(lb.parent)
  531. def plot_children(fig, box, level=0, printit=True):
  532. """Simple plotting to show where boxes are."""
  533. import matplotlib
  534. import matplotlib.pyplot as plt
  535. if isinstance(fig, matplotlib.figure.Figure):
  536. ax = fig.add_axes([0., 0., 1., 1.])
  537. ax.set_facecolor([1., 1., 1., 0.7])
  538. ax.set_alpha(0.3)
  539. fig.draw(fig.canvas.get_renderer())
  540. else:
  541. ax = fig
  542. import matplotlib.patches as patches
  543. colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
  544. if printit:
  545. print("Level:", level)
  546. for child in box.children:
  547. if printit:
  548. print(child)
  549. ax.add_patch(
  550. patches.Rectangle(
  551. (child.left.value(), child.bottom.value()), # (x, y)
  552. child.width.value(), # width
  553. child.height.value(), # height
  554. fc='none',
  555. alpha=0.8,
  556. ec=colors[level]
  557. )
  558. )
  559. if level > 0:
  560. name = child.name.split('.')[-1]
  561. if level % 2 == 0:
  562. ax.text(child.left.value(), child.bottom.value(), name,
  563. size=12-level, color=colors[level])
  564. else:
  565. ax.text(child.right.value(), child.top.value(), name,
  566. ha='right', va='top', size=12-level,
  567. color=colors[level])
  568. plot_children(ax, child, level=level+1, printit=printit)