_layoutbox.py 23 KB

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