You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

693 lines
21 KiB

4 years ago
  1. """
  2. Place a table below the x-axis at location loc.
  3. The table consists of a grid of cells.
  4. The grid need not be rectangular and can have holes.
  5. Cells are added by specifying their row and column.
  6. For the purposes of positioning the cell at (0, 0) is
  7. assumed to be at the top left and the cell at (max_row, max_col)
  8. is assumed to be at bottom right.
  9. You can add additional cells outside this range to have convenient
  10. ways of positioning more interesting grids.
  11. Author : John Gill <jng@europe.renre.com>
  12. Copyright : 2004 John Gill and John Hunter
  13. License : matplotlib license
  14. """
  15. import warnings
  16. from . import artist, cbook, docstring
  17. from .artist import Artist, allow_rasterization
  18. from .patches import Rectangle
  19. from .text import Text
  20. from .transforms import Bbox
  21. from .path import Path
  22. class Cell(Rectangle):
  23. """
  24. A cell is a `.Rectangle` with some associated text.
  25. """
  26. PAD = 0.1 # padding between text and rectangle
  27. def __init__(self, xy, width, height,
  28. edgecolor='k', facecolor='w',
  29. fill=True,
  30. text='',
  31. loc=None,
  32. fontproperties=None
  33. ):
  34. # Call base
  35. Rectangle.__init__(self, xy, width=width, height=height,
  36. edgecolor=edgecolor, facecolor=facecolor)
  37. self.set_clip_on(False)
  38. # Create text object
  39. if loc is None:
  40. loc = 'right'
  41. self._loc = loc
  42. self._text = Text(x=xy[0], y=xy[1], text=text,
  43. fontproperties=fontproperties)
  44. self._text.set_clip_on(False)
  45. def set_transform(self, trans):
  46. Rectangle.set_transform(self, trans)
  47. # the text does not get the transform!
  48. self.stale = True
  49. def set_figure(self, fig):
  50. Rectangle.set_figure(self, fig)
  51. self._text.set_figure(fig)
  52. def get_text(self):
  53. """Return the cell `.Text` instance."""
  54. return self._text
  55. def set_fontsize(self, size):
  56. self._text.set_fontsize(size)
  57. self.stale = True
  58. def get_fontsize(self):
  59. """Return the cell fontsize."""
  60. return self._text.get_fontsize()
  61. def auto_set_font_size(self, renderer):
  62. """ Shrink font size until text fits. """
  63. fontsize = self.get_fontsize()
  64. required = self.get_required_width(renderer)
  65. while fontsize > 1 and required > self.get_width():
  66. fontsize -= 1
  67. self.set_fontsize(fontsize)
  68. required = self.get_required_width(renderer)
  69. return fontsize
  70. @allow_rasterization
  71. def draw(self, renderer):
  72. if not self.get_visible():
  73. return
  74. # draw the rectangle
  75. Rectangle.draw(self, renderer)
  76. # position the text
  77. self._set_text_position(renderer)
  78. self._text.draw(renderer)
  79. self.stale = False
  80. def _set_text_position(self, renderer):
  81. """ Set text up so it draws in the right place.
  82. Currently support 'left', 'center' and 'right'
  83. """
  84. bbox = self.get_window_extent(renderer)
  85. l, b, w, h = bbox.bounds
  86. # draw in center vertically
  87. self._text.set_verticalalignment('center')
  88. y = b + (h / 2.0)
  89. # now position horizontally
  90. if self._loc == 'center':
  91. self._text.set_horizontalalignment('center')
  92. x = l + (w / 2.0)
  93. elif self._loc == 'left':
  94. self._text.set_horizontalalignment('left')
  95. x = l + (w * self.PAD)
  96. else:
  97. self._text.set_horizontalalignment('right')
  98. x = l + (w * (1.0 - self.PAD))
  99. self._text.set_position((x, y))
  100. def get_text_bounds(self, renderer):
  101. """ Get text bounds in axes co-ordinates. """
  102. bbox = self._text.get_window_extent(renderer)
  103. bboxa = bbox.inverse_transformed(self.get_data_transform())
  104. return bboxa.bounds
  105. def get_required_width(self, renderer):
  106. """ Get width required for this cell. """
  107. l, b, w, h = self.get_text_bounds(renderer)
  108. return w * (1.0 + (2.0 * self.PAD))
  109. def set_text_props(self, **kwargs):
  110. 'update the text properties with kwargs'
  111. self._text.update(kwargs)
  112. self.stale = True
  113. class CustomCell(Cell):
  114. """
  115. A subclass of Cell where the sides may be visibly toggled.
  116. """
  117. _edges = 'BRTL'
  118. _edge_aliases = {'open': '',
  119. 'closed': _edges, # default
  120. 'horizontal': 'BT',
  121. 'vertical': 'RL'
  122. }
  123. def __init__(self, *args, visible_edges, **kwargs):
  124. super().__init__(*args, **kwargs)
  125. self.visible_edges = visible_edges
  126. @property
  127. def visible_edges(self):
  128. return self._visible_edges
  129. @visible_edges.setter
  130. def visible_edges(self, value):
  131. if value is None:
  132. self._visible_edges = self._edges
  133. elif value in self._edge_aliases:
  134. self._visible_edges = self._edge_aliases[value]
  135. else:
  136. for edge in value:
  137. if edge not in self._edges:
  138. raise ValueError('Invalid edge param {}, must only be one '
  139. 'of {} or string of {}'.format(
  140. value,
  141. ", ".join(self._edge_aliases),
  142. ", ".join(self._edges)))
  143. self._visible_edges = value
  144. self.stale = True
  145. def get_path(self):
  146. """
  147. Return a path where the edges specified by _visible_edges are drawn.
  148. """
  149. codes = [Path.MOVETO]
  150. for edge in self._edges:
  151. if edge in self._visible_edges:
  152. codes.append(Path.LINETO)
  153. else:
  154. codes.append(Path.MOVETO)
  155. if Path.MOVETO not in codes[1:]: # All sides are visible
  156. codes[-1] = Path.CLOSEPOLY
  157. return Path(
  158. [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]],
  159. codes,
  160. readonly=True
  161. )
  162. class Table(Artist):
  163. """
  164. Create a table of cells.
  165. Table can have (optional) row and column headers.
  166. Each entry in the table can be either text or patches.
  167. Column widths and row heights for the table can be specified.
  168. Return value is a sequence of text, line and patch instances that make
  169. up the table
  170. """
  171. codes = {'best': 0,
  172. 'upper right': 1, # default
  173. 'upper left': 2,
  174. 'lower left': 3,
  175. 'lower right': 4,
  176. 'center left': 5,
  177. 'center right': 6,
  178. 'lower center': 7,
  179. 'upper center': 8,
  180. 'center': 9,
  181. 'top right': 10,
  182. 'top left': 11,
  183. 'bottom left': 12,
  184. 'bottom right': 13,
  185. 'right': 14,
  186. 'left': 15,
  187. 'top': 16,
  188. 'bottom': 17,
  189. }
  190. FONTSIZE = 10
  191. AXESPAD = 0.02 # the border between the axes and table edge
  192. def __init__(self, ax, loc=None, bbox=None, **kwargs):
  193. Artist.__init__(self)
  194. if isinstance(loc, str):
  195. if loc not in self.codes:
  196. warnings.warn('Unrecognized location %s. Falling back on '
  197. 'bottom; valid locations are\n%s\t' %
  198. (loc, '\n\t'.join(self.codes)))
  199. loc = 'bottom'
  200. loc = self.codes[loc]
  201. self.set_figure(ax.figure)
  202. self._axes = ax
  203. self._loc = loc
  204. self._bbox = bbox
  205. # use axes coords
  206. self.set_transform(ax.transAxes)
  207. self._texts = []
  208. self._cells = {}
  209. self._edges = None
  210. self._autoRows = []
  211. self._autoColumns = []
  212. self._autoFontsize = True
  213. self.update(kwargs)
  214. self.set_clip_on(False)
  215. def add_cell(self, row, col, *args, **kwargs):
  216. """
  217. Add a cell to the table.
  218. Parameters
  219. ----------
  220. row : int
  221. Row index.
  222. col : int
  223. Column index.
  224. Returns
  225. -------
  226. `CustomCell`: Automatically created cell
  227. """
  228. xy = (0, 0)
  229. cell = CustomCell(xy, visible_edges=self.edges, *args, **kwargs)
  230. self[row, col] = cell
  231. return cell
  232. def __setitem__(self, position, cell):
  233. """
  234. Set a custom cell in a given position.
  235. """
  236. if not isinstance(cell, CustomCell):
  237. raise TypeError('Table only accepts CustomCell')
  238. try:
  239. row, col = position[0], position[1]
  240. except Exception:
  241. raise KeyError('Only tuples length 2 are accepted as coordinates')
  242. cell.set_figure(self.figure)
  243. cell.set_transform(self.get_transform())
  244. cell.set_clip_on(False)
  245. self._cells[row, col] = cell
  246. self.stale = True
  247. def __getitem__(self, position):
  248. """
  249. Retrieve a custom cell from a given position.
  250. """
  251. try:
  252. row, col = position[0], position[1]
  253. except Exception:
  254. raise KeyError('Only tuples length 2 are accepted as coordinates')
  255. return self._cells[row, col]
  256. @property
  257. def edges(self):
  258. return self._edges
  259. @edges.setter
  260. def edges(self, value):
  261. self._edges = value
  262. self.stale = True
  263. def _approx_text_height(self):
  264. return (self.FONTSIZE / 72.0 * self.figure.dpi /
  265. self._axes.bbox.height * 1.2)
  266. @allow_rasterization
  267. def draw(self, renderer):
  268. # Need a renderer to do hit tests on mouseevent; assume the last one
  269. # will do
  270. if renderer is None:
  271. renderer = self.figure._cachedRenderer
  272. if renderer is None:
  273. raise RuntimeError('No renderer defined')
  274. if not self.get_visible():
  275. return
  276. renderer.open_group('table')
  277. self._update_positions(renderer)
  278. for key in sorted(self._cells):
  279. self._cells[key].draw(renderer)
  280. renderer.close_group('table')
  281. self.stale = False
  282. def _get_grid_bbox(self, renderer):
  283. """Get a bbox, in axes co-ordinates for the cells.
  284. Only include those in the range (0,0) to (maxRow, maxCol)"""
  285. boxes = [cell.get_window_extent(renderer)
  286. for (row, col), cell in self._cells.items()
  287. if row >= 0 and col >= 0]
  288. bbox = Bbox.union(boxes)
  289. return bbox.inverse_transformed(self.get_transform())
  290. def contains(self, mouseevent):
  291. """Test whether the mouse event occurred in the table.
  292. Returns T/F, {}
  293. """
  294. if callable(self._contains):
  295. return self._contains(self, mouseevent)
  296. # TODO: Return index of the cell containing the cursor so that the user
  297. # doesn't have to bind to each one individually.
  298. renderer = self.figure._cachedRenderer
  299. if renderer is not None:
  300. boxes = [cell.get_window_extent(renderer)
  301. for (row, col), cell in self._cells.items()
  302. if row >= 0 and col >= 0]
  303. bbox = Bbox.union(boxes)
  304. return bbox.contains(mouseevent.x, mouseevent.y), {}
  305. else:
  306. return False, {}
  307. def get_children(self):
  308. """Return the Artists contained by the table."""
  309. return list(self._cells.values())
  310. get_child_artists = cbook.deprecated("3.0")(get_children)
  311. def get_window_extent(self, renderer):
  312. """Return the bounding box of the table in window coords."""
  313. boxes = [cell.get_window_extent(renderer)
  314. for cell in self._cells.values()]
  315. return Bbox.union(boxes)
  316. def _do_cell_alignment(self):
  317. """ Calculate row heights and column widths.
  318. Position cells accordingly.
  319. """
  320. # Calculate row/column widths
  321. widths = {}
  322. heights = {}
  323. for (row, col), cell in self._cells.items():
  324. height = heights.setdefault(row, 0.0)
  325. heights[row] = max(height, cell.get_height())
  326. width = widths.setdefault(col, 0.0)
  327. widths[col] = max(width, cell.get_width())
  328. # work out left position for each column
  329. xpos = 0
  330. lefts = {}
  331. for col in sorted(widths):
  332. lefts[col] = xpos
  333. xpos += widths[col]
  334. ypos = 0
  335. bottoms = {}
  336. for row in sorted(heights, reverse=True):
  337. bottoms[row] = ypos
  338. ypos += heights[row]
  339. # set cell positions
  340. for (row, col), cell in self._cells.items():
  341. cell.set_x(lefts[col])
  342. cell.set_y(bottoms[row])
  343. def auto_set_column_width(self, col):
  344. """ Given column indexs in either List, Tuple or int. Will be able to
  345. automatically set the columns into optimal sizes.
  346. Here is the example of the input, which triger automatic adjustment on
  347. columns to optimal size by given index numbers.
  348. -1: the row labling
  349. 0: the 1st column
  350. 1: the 2nd column
  351. Args:
  352. col(List): list of indexs
  353. >>>table.auto_set_column_width([-1,0,1])
  354. col(Tuple): tuple of indexs
  355. >>>table.auto_set_column_width((-1,0,1))
  356. col(int): index integer
  357. >>>table.auto_set_column_width(-1)
  358. >>>table.auto_set_column_width(0)
  359. >>>table.auto_set_column_width(1)
  360. """
  361. # check for col possibility on iteration
  362. try:
  363. iter(col)
  364. except (TypeError, AttributeError):
  365. self._autoColumns.append(col)
  366. else:
  367. for cell in col:
  368. self._autoColumns.append(cell)
  369. self.stale = True
  370. def _auto_set_column_width(self, col, renderer):
  371. """Automatically set width for column."""
  372. cells = [key for key in self._cells if key[1] == col]
  373. # find max width
  374. width = 0
  375. for cell in cells:
  376. c = self._cells[cell]
  377. width = max(c.get_required_width(renderer), width)
  378. # Now set the widths
  379. for cell in cells:
  380. self._cells[cell].set_width(width)
  381. def auto_set_font_size(self, value=True):
  382. """ Automatically set font size. """
  383. self._autoFontsize = value
  384. self.stale = True
  385. def _auto_set_font_size(self, renderer):
  386. if len(self._cells) == 0:
  387. return
  388. fontsize = next(iter(self._cells.values())).get_fontsize()
  389. cells = []
  390. for key, cell in self._cells.items():
  391. # ignore auto-sized columns
  392. if key[1] in self._autoColumns:
  393. continue
  394. size = cell.auto_set_font_size(renderer)
  395. fontsize = min(fontsize, size)
  396. cells.append(cell)
  397. # now set all fontsizes equal
  398. for cell in self._cells.values():
  399. cell.set_fontsize(fontsize)
  400. def scale(self, xscale, yscale):
  401. """ Scale column widths by xscale and row heights by yscale. """
  402. for c in self._cells.values():
  403. c.set_width(c.get_width() * xscale)
  404. c.set_height(c.get_height() * yscale)
  405. def set_fontsize(self, size):
  406. """
  407. Set the font size, in points, of the cell text.
  408. Parameters
  409. ----------
  410. size : float
  411. """
  412. for cell in self._cells.values():
  413. cell.set_fontsize(size)
  414. self.stale = True
  415. def _offset(self, ox, oy):
  416. """Move all the artists by ox, oy (axes coords)."""
  417. for c in self._cells.values():
  418. x, y = c.get_x(), c.get_y()
  419. c.set_x(x + ox)
  420. c.set_y(y + oy)
  421. def _update_positions(self, renderer):
  422. # called from renderer to allow more precise estimates of
  423. # widths and heights with get_window_extent
  424. # Do any auto width setting
  425. for col in self._autoColumns:
  426. self._auto_set_column_width(col, renderer)
  427. if self._autoFontsize:
  428. self._auto_set_font_size(renderer)
  429. # Align all the cells
  430. self._do_cell_alignment()
  431. bbox = self._get_grid_bbox(renderer)
  432. l, b, w, h = bbox.bounds
  433. if self._bbox is not None:
  434. # Position according to bbox
  435. rl, rb, rw, rh = self._bbox
  436. self.scale(rw / w, rh / h)
  437. ox = rl - l
  438. oy = rb - b
  439. self._do_cell_alignment()
  440. else:
  441. # Position using loc
  442. (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C,
  443. TR, TL, BL, BR, R, L, T, B) = range(len(self.codes))
  444. # defaults for center
  445. ox = (0.5 - w / 2) - l
  446. oy = (0.5 - h / 2) - b
  447. if self._loc in (UL, LL, CL): # left
  448. ox = self.AXESPAD - l
  449. if self._loc in (BEST, UR, LR, R, CR): # right
  450. ox = 1 - (l + w + self.AXESPAD)
  451. if self._loc in (BEST, UR, UL, UC): # upper
  452. oy = 1 - (b + h + self.AXESPAD)
  453. if self._loc in (LL, LR, LC): # lower
  454. oy = self.AXESPAD - b
  455. if self._loc in (LC, UC, C): # center x
  456. ox = (0.5 - w / 2) - l
  457. if self._loc in (CL, CR, C): # center y
  458. oy = (0.5 - h / 2) - b
  459. if self._loc in (TL, BL, L): # out left
  460. ox = - (l + w)
  461. if self._loc in (TR, BR, R): # out right
  462. ox = 1.0 - l
  463. if self._loc in (TR, TL, T): # out top
  464. oy = 1.0 - b
  465. if self._loc in (BL, BR, B): # out bottom
  466. oy = - (b + h)
  467. self._offset(ox, oy)
  468. def get_celld(self):
  469. """Return a dict of cells in the table."""
  470. return self._cells
  471. def table(ax,
  472. cellText=None, cellColours=None,
  473. cellLoc='right', colWidths=None,
  474. rowLabels=None, rowColours=None, rowLoc='left',
  475. colLabels=None, colColours=None, colLoc='center',
  476. loc='bottom', bbox=None, edges='closed',
  477. **kwargs):
  478. """
  479. TABLE(cellText=None, cellColours=None,
  480. cellLoc='right', colWidths=None,
  481. rowLabels=None, rowColours=None, rowLoc='left',
  482. colLabels=None, colColours=None, colLoc='center',
  483. loc='bottom', bbox=None, edges='closed')
  484. Factory function to generate a Table instance.
  485. Thanks to John Gill for providing the class and table.
  486. """
  487. if cellColours is None and cellText is None:
  488. raise ValueError('At least one argument from "cellColours" or '
  489. '"cellText" must be provided to create a table.')
  490. # Check we have some cellText
  491. if cellText is None:
  492. # assume just colours are needed
  493. rows = len(cellColours)
  494. cols = len(cellColours[0])
  495. cellText = [[''] * cols] * rows
  496. rows = len(cellText)
  497. cols = len(cellText[0])
  498. for row in cellText:
  499. if len(row) != cols:
  500. raise ValueError("Each row in 'cellText' must have {} columns"
  501. .format(cols))
  502. if cellColours is not None:
  503. if len(cellColours) != rows:
  504. raise ValueError("'cellColours' must have {} rows".format(rows))
  505. for row in cellColours:
  506. if len(row) != cols:
  507. raise ValueError("Each row in 'cellColours' must have {} "
  508. "columns".format(cols))
  509. else:
  510. cellColours = ['w' * cols] * rows
  511. # Set colwidths if not given
  512. if colWidths is None:
  513. colWidths = [1.0 / cols] * cols
  514. # Fill in missing information for column
  515. # and row labels
  516. rowLabelWidth = 0
  517. if rowLabels is None:
  518. if rowColours is not None:
  519. rowLabels = [''] * rows
  520. rowLabelWidth = colWidths[0]
  521. elif rowColours is None:
  522. rowColours = 'w' * rows
  523. if rowLabels is not None:
  524. if len(rowLabels) != rows:
  525. raise ValueError("'rowLabels' must be of length {0}".format(rows))
  526. # If we have column labels, need to shift
  527. # the text and colour arrays down 1 row
  528. offset = 1
  529. if colLabels is None:
  530. if colColours is not None:
  531. colLabels = [''] * cols
  532. else:
  533. offset = 0
  534. elif colColours is None:
  535. colColours = 'w' * cols
  536. # Set up cell colours if not given
  537. if cellColours is None:
  538. cellColours = ['w' * cols] * rows
  539. # Now create the table
  540. table = Table(ax, loc, bbox, **kwargs)
  541. table.edges = edges
  542. height = table._approx_text_height()
  543. # Add the cells
  544. for row in range(rows):
  545. for col in range(cols):
  546. table.add_cell(row + offset, col,
  547. width=colWidths[col], height=height,
  548. text=cellText[row][col],
  549. facecolor=cellColours[row][col],
  550. loc=cellLoc)
  551. # Do column labels
  552. if colLabels is not None:
  553. for col in range(cols):
  554. table.add_cell(0, col,
  555. width=colWidths[col], height=height,
  556. text=colLabels[col], facecolor=colColours[col],
  557. loc=colLoc)
  558. # Do row labels
  559. if rowLabels is not None:
  560. for row in range(rows):
  561. table.add_cell(row + offset, -1,
  562. width=rowLabelWidth or 1e-15, height=height,
  563. text=rowLabels[row], facecolor=rowColours[row],
  564. loc=rowLoc)
  565. if rowLabelWidth == 0:
  566. table.auto_set_column_width(-1)
  567. ax.add_table(table)
  568. return table
  569. docstring.interpd.update(Table=artist.kwdoc(Table))