table.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. # Original code by:
  2. # John Gill <jng@europe.renre.com>
  3. # Copyright 2004 John Gill and John Hunter
  4. #
  5. # Subsequent changes:
  6. # The Matplotlib development team
  7. # Copyright The Matplotlib development team
  8. """
  9. Tables drawing.
  10. .. note::
  11. The table implementation in Matplotlib is lightly maintained. For a more
  12. featureful table implementation, you may wish to try `blume
  13. <https://github.com/swfiua/blume>`_.
  14. Use the factory function `~matplotlib.table.table` to create a ready-made
  15. table from texts. If you need more control, use the `.Table` class and its
  16. methods.
  17. The table consists of a grid of cells, which are indexed by (row, column).
  18. The cell (0, 0) is positioned at the top left.
  19. Thanks to John Gill for providing the class and table.
  20. """
  21. import numpy as np
  22. from . import _api, _docstring
  23. from .artist import Artist, allow_rasterization
  24. from .patches import Rectangle
  25. from .text import Text
  26. from .transforms import Bbox
  27. from .path import Path
  28. class Cell(Rectangle):
  29. """
  30. A cell is a `.Rectangle` with some associated `.Text`.
  31. As a user, you'll most likely not creates cells yourself. Instead, you
  32. should use either the `~matplotlib.table.table` factory function or
  33. `.Table.add_cell`.
  34. """
  35. PAD = 0.1
  36. """Padding between text and rectangle."""
  37. _edges = 'BRTL'
  38. _edge_aliases = {'open': '',
  39. 'closed': _edges, # default
  40. 'horizontal': 'BT',
  41. 'vertical': 'RL'
  42. }
  43. def __init__(self, xy, width, height, *,
  44. edgecolor='k', facecolor='w',
  45. fill=True,
  46. text='',
  47. loc=None,
  48. fontproperties=None,
  49. visible_edges='closed',
  50. ):
  51. """
  52. Parameters
  53. ----------
  54. xy : 2-tuple
  55. The position of the bottom left corner of the cell.
  56. width : float
  57. The cell width.
  58. height : float
  59. The cell height.
  60. edgecolor : color
  61. The color of the cell border.
  62. facecolor : color
  63. The cell facecolor.
  64. fill : bool
  65. Whether the cell background is filled.
  66. text : str
  67. The cell text.
  68. loc : {'left', 'center', 'right'}, default: 'right'
  69. The alignment of the text within the cell.
  70. fontproperties : dict
  71. A dict defining the font properties of the text. Supported keys and
  72. values are the keyword arguments accepted by `.FontProperties`.
  73. visible_edges : str, default: 'closed'
  74. The cell edges to be drawn with a line: a substring of 'BRTL'
  75. (bottom, right, top, left), or one of 'open' (no edges drawn),
  76. 'closed' (all edges drawn), 'horizontal' (bottom and top),
  77. 'vertical' (right and left).
  78. """
  79. # Call base
  80. super().__init__(xy, width=width, height=height, fill=fill,
  81. edgecolor=edgecolor, facecolor=facecolor)
  82. self.set_clip_on(False)
  83. self.visible_edges = visible_edges
  84. # Create text object
  85. if loc is None:
  86. loc = 'right'
  87. self._loc = loc
  88. self._text = Text(x=xy[0], y=xy[1], clip_on=False,
  89. text=text, fontproperties=fontproperties,
  90. horizontalalignment=loc, verticalalignment='center')
  91. @_api.rename_parameter("3.8", "trans", "t")
  92. def set_transform(self, t):
  93. super().set_transform(t)
  94. # the text does not get the transform!
  95. self.stale = True
  96. def set_figure(self, fig):
  97. super().set_figure(fig)
  98. self._text.set_figure(fig)
  99. def get_text(self):
  100. """Return the cell `.Text` instance."""
  101. return self._text
  102. def set_fontsize(self, size):
  103. """Set the text fontsize."""
  104. self._text.set_fontsize(size)
  105. self.stale = True
  106. def get_fontsize(self):
  107. """Return the cell fontsize."""
  108. return self._text.get_fontsize()
  109. def auto_set_font_size(self, renderer):
  110. """Shrink font size until the text fits into the cell width."""
  111. fontsize = self.get_fontsize()
  112. required = self.get_required_width(renderer)
  113. while fontsize > 1 and required > self.get_width():
  114. fontsize -= 1
  115. self.set_fontsize(fontsize)
  116. required = self.get_required_width(renderer)
  117. return fontsize
  118. @allow_rasterization
  119. def draw(self, renderer):
  120. if not self.get_visible():
  121. return
  122. # draw the rectangle
  123. super().draw(renderer)
  124. # position the text
  125. self._set_text_position(renderer)
  126. self._text.draw(renderer)
  127. self.stale = False
  128. def _set_text_position(self, renderer):
  129. """Set text up so it is drawn in the right place."""
  130. bbox = self.get_window_extent(renderer)
  131. # center vertically
  132. y = bbox.y0 + bbox.height / 2
  133. # position horizontally
  134. loc = self._text.get_horizontalalignment()
  135. if loc == 'center':
  136. x = bbox.x0 + bbox.width / 2
  137. elif loc == 'left':
  138. x = bbox.x0 + bbox.width * self.PAD
  139. else: # right.
  140. x = bbox.x0 + bbox.width * (1 - self.PAD)
  141. self._text.set_position((x, y))
  142. def get_text_bounds(self, renderer):
  143. """
  144. Return the text bounds as *(x, y, width, height)* in table coordinates.
  145. """
  146. return (self._text.get_window_extent(renderer)
  147. .transformed(self.get_data_transform().inverted())
  148. .bounds)
  149. def get_required_width(self, renderer):
  150. """Return the minimal required width for the cell."""
  151. l, b, w, h = self.get_text_bounds(renderer)
  152. return w * (1.0 + (2.0 * self.PAD))
  153. @_docstring.dedent_interpd
  154. def set_text_props(self, **kwargs):
  155. """
  156. Update the text properties.
  157. Valid keyword arguments are:
  158. %(Text:kwdoc)s
  159. """
  160. self._text._internal_update(kwargs)
  161. self.stale = True
  162. @property
  163. def visible_edges(self):
  164. """
  165. The cell edges to be drawn with a line.
  166. Reading this property returns a substring of 'BRTL' (bottom, right,
  167. top, left').
  168. When setting this property, you can use a substring of 'BRTL' or one
  169. of {'open', 'closed', 'horizontal', 'vertical'}.
  170. """
  171. return self._visible_edges
  172. @visible_edges.setter
  173. def visible_edges(self, value):
  174. if value is None:
  175. self._visible_edges = self._edges
  176. elif value in self._edge_aliases:
  177. self._visible_edges = self._edge_aliases[value]
  178. else:
  179. if any(edge not in self._edges for edge in value):
  180. raise ValueError('Invalid edge param {}, must only be one of '
  181. '{} or string of {}'.format(
  182. value,
  183. ", ".join(self._edge_aliases),
  184. ", ".join(self._edges)))
  185. self._visible_edges = value
  186. self.stale = True
  187. def get_path(self):
  188. """Return a `.Path` for the `.visible_edges`."""
  189. codes = [Path.MOVETO]
  190. codes.extend(
  191. Path.LINETO if edge in self._visible_edges else Path.MOVETO
  192. for edge in self._edges)
  193. if Path.MOVETO not in codes[1:]: # All sides are visible
  194. codes[-1] = Path.CLOSEPOLY
  195. return Path(
  196. [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]],
  197. codes,
  198. readonly=True
  199. )
  200. CustomCell = Cell # Backcompat. alias.
  201. class Table(Artist):
  202. """
  203. A table of cells.
  204. The table consists of a grid of cells, which are indexed by (row, column).
  205. For a simple table, you'll have a full grid of cells with indices from
  206. (0, 0) to (num_rows-1, num_cols-1), in which the cell (0, 0) is positioned
  207. at the top left. However, you can also add cells with negative indices.
  208. You don't have to add a cell to every grid position, so you can create
  209. tables that have holes.
  210. *Note*: You'll usually not create an empty table from scratch. Instead use
  211. `~matplotlib.table.table` to create a table from data.
  212. """
  213. codes = {'best': 0,
  214. 'upper right': 1, # default
  215. 'upper left': 2,
  216. 'lower left': 3,
  217. 'lower right': 4,
  218. 'center left': 5,
  219. 'center right': 6,
  220. 'lower center': 7,
  221. 'upper center': 8,
  222. 'center': 9,
  223. 'top right': 10,
  224. 'top left': 11,
  225. 'bottom left': 12,
  226. 'bottom right': 13,
  227. 'right': 14,
  228. 'left': 15,
  229. 'top': 16,
  230. 'bottom': 17,
  231. }
  232. """Possible values where to place the table relative to the Axes."""
  233. FONTSIZE = 10
  234. AXESPAD = 0.02
  235. """The border between the Axes and the table edge in Axes units."""
  236. def __init__(self, ax, loc=None, bbox=None, **kwargs):
  237. """
  238. Parameters
  239. ----------
  240. ax : `~matplotlib.axes.Axes`
  241. The `~.axes.Axes` to plot the table into.
  242. loc : str
  243. The position of the cell with respect to *ax*. This must be one of
  244. the `~.Table.codes`.
  245. bbox : `.Bbox` or [xmin, ymin, width, height], optional
  246. A bounding box to draw the table into. If this is not *None*, this
  247. overrides *loc*.
  248. Other Parameters
  249. ----------------
  250. **kwargs
  251. `.Artist` properties.
  252. """
  253. super().__init__()
  254. if isinstance(loc, str):
  255. if loc not in self.codes:
  256. raise ValueError(
  257. "Unrecognized location {!r}. Valid locations are\n\t{}"
  258. .format(loc, '\n\t'.join(self.codes)))
  259. loc = self.codes[loc]
  260. self.set_figure(ax.figure)
  261. self._axes = ax
  262. self._loc = loc
  263. self._bbox = bbox
  264. # use axes coords
  265. ax._unstale_viewLim()
  266. self.set_transform(ax.transAxes)
  267. self._cells = {}
  268. self._edges = None
  269. self._autoColumns = []
  270. self._autoFontsize = True
  271. self._internal_update(kwargs)
  272. self.set_clip_on(False)
  273. def add_cell(self, row, col, *args, **kwargs):
  274. """
  275. Create a cell and add it to the table.
  276. Parameters
  277. ----------
  278. row : int
  279. Row index.
  280. col : int
  281. Column index.
  282. *args, **kwargs
  283. All other parameters are passed on to `Cell`.
  284. Returns
  285. -------
  286. `.Cell`
  287. The created cell.
  288. """
  289. xy = (0, 0)
  290. cell = Cell(xy, visible_edges=self.edges, *args, **kwargs)
  291. self[row, col] = cell
  292. return cell
  293. def __setitem__(self, position, cell):
  294. """
  295. Set a custom cell in a given position.
  296. """
  297. _api.check_isinstance(Cell, cell=cell)
  298. try:
  299. row, col = position[0], position[1]
  300. except Exception as err:
  301. raise KeyError('Only tuples length 2 are accepted as '
  302. 'coordinates') from err
  303. cell.set_figure(self.figure)
  304. cell.set_transform(self.get_transform())
  305. cell.set_clip_on(False)
  306. self._cells[row, col] = cell
  307. self.stale = True
  308. def __getitem__(self, position):
  309. """Retrieve a custom cell from a given position."""
  310. return self._cells[position]
  311. @property
  312. def edges(self):
  313. """
  314. The default value of `~.Cell.visible_edges` for newly added
  315. cells using `.add_cell`.
  316. Notes
  317. -----
  318. This setting does currently only affect newly created cells using
  319. `.add_cell`.
  320. To change existing cells, you have to set their edges explicitly::
  321. for c in tab.get_celld().values():
  322. c.visible_edges = 'horizontal'
  323. """
  324. return self._edges
  325. @edges.setter
  326. def edges(self, value):
  327. self._edges = value
  328. self.stale = True
  329. def _approx_text_height(self):
  330. return (self.FONTSIZE / 72.0 * self.figure.dpi /
  331. self._axes.bbox.height * 1.2)
  332. @allow_rasterization
  333. def draw(self, renderer):
  334. # docstring inherited
  335. # Need a renderer to do hit tests on mouseevent; assume the last one
  336. # will do
  337. if renderer is None:
  338. renderer = self.figure._get_renderer()
  339. if renderer is None:
  340. raise RuntimeError('No renderer defined')
  341. if not self.get_visible():
  342. return
  343. renderer.open_group('table', gid=self.get_gid())
  344. self._update_positions(renderer)
  345. for key in sorted(self._cells):
  346. self._cells[key].draw(renderer)
  347. renderer.close_group('table')
  348. self.stale = False
  349. def _get_grid_bbox(self, renderer):
  350. """
  351. Get a bbox, in axes coordinates for the cells.
  352. Only include those in the range (0, 0) to (maxRow, maxCol).
  353. """
  354. boxes = [cell.get_window_extent(renderer)
  355. for (row, col), cell in self._cells.items()
  356. if row >= 0 and col >= 0]
  357. bbox = Bbox.union(boxes)
  358. return bbox.transformed(self.get_transform().inverted())
  359. def contains(self, mouseevent):
  360. # docstring inherited
  361. if self._different_canvas(mouseevent):
  362. return False, {}
  363. # TODO: Return index of the cell containing the cursor so that the user
  364. # doesn't have to bind to each one individually.
  365. renderer = self.figure._get_renderer()
  366. if renderer is not None:
  367. boxes = [cell.get_window_extent(renderer)
  368. for (row, col), cell in self._cells.items()
  369. if row >= 0 and col >= 0]
  370. bbox = Bbox.union(boxes)
  371. return bbox.contains(mouseevent.x, mouseevent.y), {}
  372. else:
  373. return False, {}
  374. def get_children(self):
  375. """Return the Artists contained by the table."""
  376. return list(self._cells.values())
  377. def get_window_extent(self, renderer=None):
  378. # docstring inherited
  379. if renderer is None:
  380. renderer = self.figure._get_renderer()
  381. self._update_positions(renderer)
  382. boxes = [cell.get_window_extent(renderer)
  383. for cell in self._cells.values()]
  384. return Bbox.union(boxes)
  385. def _do_cell_alignment(self):
  386. """
  387. Calculate row heights and column widths; position cells accordingly.
  388. """
  389. # Calculate row/column widths
  390. widths = {}
  391. heights = {}
  392. for (row, col), cell in self._cells.items():
  393. height = heights.setdefault(row, 0.0)
  394. heights[row] = max(height, cell.get_height())
  395. width = widths.setdefault(col, 0.0)
  396. widths[col] = max(width, cell.get_width())
  397. # work out left position for each column
  398. xpos = 0
  399. lefts = {}
  400. for col in sorted(widths):
  401. lefts[col] = xpos
  402. xpos += widths[col]
  403. ypos = 0
  404. bottoms = {}
  405. for row in sorted(heights, reverse=True):
  406. bottoms[row] = ypos
  407. ypos += heights[row]
  408. # set cell positions
  409. for (row, col), cell in self._cells.items():
  410. cell.set_x(lefts[col])
  411. cell.set_y(bottoms[row])
  412. def auto_set_column_width(self, col):
  413. """
  414. Automatically set the widths of given columns to optimal sizes.
  415. Parameters
  416. ----------
  417. col : int or sequence of ints
  418. The indices of the columns to auto-scale.
  419. """
  420. col1d = np.atleast_1d(col)
  421. if not np.issubdtype(col1d.dtype, np.integer):
  422. _api.warn_deprecated("3.8", name="col",
  423. message="%(name)r must be an int or sequence of ints. "
  424. "Passing other types is deprecated since %(since)s "
  425. "and will be removed %(removal)s.")
  426. return
  427. for cell in col1d:
  428. self._autoColumns.append(cell)
  429. self.stale = True
  430. def _auto_set_column_width(self, col, renderer):
  431. """Automatically set width for column."""
  432. cells = [cell for key, cell in self._cells.items() if key[1] == col]
  433. max_width = max((cell.get_required_width(renderer) for cell in cells),
  434. default=0)
  435. for cell in cells:
  436. cell.set_width(max_width)
  437. def auto_set_font_size(self, value=True):
  438. """Automatically set font size."""
  439. self._autoFontsize = value
  440. self.stale = True
  441. def _auto_set_font_size(self, renderer):
  442. if len(self._cells) == 0:
  443. return
  444. fontsize = next(iter(self._cells.values())).get_fontsize()
  445. cells = []
  446. for key, cell in self._cells.items():
  447. # ignore auto-sized columns
  448. if key[1] in self._autoColumns:
  449. continue
  450. size = cell.auto_set_font_size(renderer)
  451. fontsize = min(fontsize, size)
  452. cells.append(cell)
  453. # now set all fontsizes equal
  454. for cell in self._cells.values():
  455. cell.set_fontsize(fontsize)
  456. def scale(self, xscale, yscale):
  457. """Scale column widths by *xscale* and row heights by *yscale*."""
  458. for c in self._cells.values():
  459. c.set_width(c.get_width() * xscale)
  460. c.set_height(c.get_height() * yscale)
  461. def set_fontsize(self, size):
  462. """
  463. Set the font size, in points, of the cell text.
  464. Parameters
  465. ----------
  466. size : float
  467. Notes
  468. -----
  469. As long as auto font size has not been disabled, the value will be
  470. clipped such that the text fits horizontally into the cell.
  471. You can disable this behavior using `.auto_set_font_size`.
  472. >>> the_table.auto_set_font_size(False)
  473. >>> the_table.set_fontsize(20)
  474. However, there is no automatic scaling of the row height so that the
  475. text may exceed the cell boundary.
  476. """
  477. for cell in self._cells.values():
  478. cell.set_fontsize(size)
  479. self.stale = True
  480. def _offset(self, ox, oy):
  481. """Move all the artists by ox, oy (axes coords)."""
  482. for c in self._cells.values():
  483. x, y = c.get_x(), c.get_y()
  484. c.set_x(x + ox)
  485. c.set_y(y + oy)
  486. def _update_positions(self, renderer):
  487. # called from renderer to allow more precise estimates of
  488. # widths and heights with get_window_extent
  489. # Do any auto width setting
  490. for col in self._autoColumns:
  491. self._auto_set_column_width(col, renderer)
  492. if self._autoFontsize:
  493. self._auto_set_font_size(renderer)
  494. # Align all the cells
  495. self._do_cell_alignment()
  496. bbox = self._get_grid_bbox(renderer)
  497. l, b, w, h = bbox.bounds
  498. if self._bbox is not None:
  499. # Position according to bbox
  500. if isinstance(self._bbox, Bbox):
  501. rl, rb, rw, rh = self._bbox.bounds
  502. else:
  503. rl, rb, rw, rh = self._bbox
  504. self.scale(rw / w, rh / h)
  505. ox = rl - l
  506. oy = rb - b
  507. self._do_cell_alignment()
  508. else:
  509. # Position using loc
  510. (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C,
  511. TR, TL, BL, BR, R, L, T, B) = range(len(self.codes))
  512. # defaults for center
  513. ox = (0.5 - w / 2) - l
  514. oy = (0.5 - h / 2) - b
  515. if self._loc in (UL, LL, CL): # left
  516. ox = self.AXESPAD - l
  517. if self._loc in (BEST, UR, LR, R, CR): # right
  518. ox = 1 - (l + w + self.AXESPAD)
  519. if self._loc in (BEST, UR, UL, UC): # upper
  520. oy = 1 - (b + h + self.AXESPAD)
  521. if self._loc in (LL, LR, LC): # lower
  522. oy = self.AXESPAD - b
  523. if self._loc in (LC, UC, C): # center x
  524. ox = (0.5 - w / 2) - l
  525. if self._loc in (CL, CR, C): # center y
  526. oy = (0.5 - h / 2) - b
  527. if self._loc in (TL, BL, L): # out left
  528. ox = - (l + w)
  529. if self._loc in (TR, BR, R): # out right
  530. ox = 1.0 - l
  531. if self._loc in (TR, TL, T): # out top
  532. oy = 1.0 - b
  533. if self._loc in (BL, BR, B): # out bottom
  534. oy = - (b + h)
  535. self._offset(ox, oy)
  536. def get_celld(self):
  537. r"""
  538. Return a dict of cells in the table mapping *(row, column)* to
  539. `.Cell`\s.
  540. Notes
  541. -----
  542. You can also directly index into the Table object to access individual
  543. cells::
  544. cell = table[row, col]
  545. """
  546. return self._cells
  547. @_docstring.dedent_interpd
  548. def table(ax,
  549. cellText=None, cellColours=None,
  550. cellLoc='right', colWidths=None,
  551. rowLabels=None, rowColours=None, rowLoc='left',
  552. colLabels=None, colColours=None, colLoc='center',
  553. loc='bottom', bbox=None, edges='closed',
  554. **kwargs):
  555. """
  556. Add a table to an `~.axes.Axes`.
  557. At least one of *cellText* or *cellColours* must be specified. These
  558. parameters must be 2D lists, in which the outer lists define the rows and
  559. the inner list define the column values per row. Each row must have the
  560. same number of elements.
  561. The table can optionally have row and column headers, which are configured
  562. using *rowLabels*, *rowColours*, *rowLoc* and *colLabels*, *colColours*,
  563. *colLoc* respectively.
  564. For finer grained control over tables, use the `.Table` class and add it to
  565. the axes with `.Axes.add_table`.
  566. Parameters
  567. ----------
  568. cellText : 2D list of str, optional
  569. The texts to place into the table cells.
  570. *Note*: Line breaks in the strings are currently not accounted for and
  571. will result in the text exceeding the cell boundaries.
  572. cellColours : 2D list of colors, optional
  573. The background colors of the cells.
  574. cellLoc : {'left', 'center', 'right'}, default: 'right'
  575. The alignment of the text within the cells.
  576. colWidths : list of float, optional
  577. The column widths in units of the axes. If not given, all columns will
  578. have a width of *1 / ncols*.
  579. rowLabels : list of str, optional
  580. The text of the row header cells.
  581. rowColours : list of colors, optional
  582. The colors of the row header cells.
  583. rowLoc : {'left', 'center', 'right'}, default: 'left'
  584. The text alignment of the row header cells.
  585. colLabels : list of str, optional
  586. The text of the column header cells.
  587. colColours : list of colors, optional
  588. The colors of the column header cells.
  589. colLoc : {'left', 'center', 'right'}, default: 'left'
  590. The text alignment of the column header cells.
  591. loc : str, optional
  592. The position of the cell with respect to *ax*. This must be one of
  593. the `~.Table.codes`.
  594. bbox : `.Bbox` or [xmin, ymin, width, height], optional
  595. A bounding box to draw the table into. If this is not *None*, this
  596. overrides *loc*.
  597. edges : substring of 'BRTL' or {'open', 'closed', 'horizontal', 'vertical'}
  598. The cell edges to be drawn with a line. See also
  599. `~.Cell.visible_edges`.
  600. Returns
  601. -------
  602. `~matplotlib.table.Table`
  603. The created table.
  604. Other Parameters
  605. ----------------
  606. **kwargs
  607. `.Table` properties.
  608. %(Table:kwdoc)s
  609. """
  610. if cellColours is None and cellText is None:
  611. raise ValueError('At least one argument from "cellColours" or '
  612. '"cellText" must be provided to create a table.')
  613. # Check we have some cellText
  614. if cellText is None:
  615. # assume just colours are needed
  616. rows = len(cellColours)
  617. cols = len(cellColours[0])
  618. cellText = [[''] * cols] * rows
  619. rows = len(cellText)
  620. cols = len(cellText[0])
  621. for row in cellText:
  622. if len(row) != cols:
  623. raise ValueError(f"Each row in 'cellText' must have {cols} "
  624. "columns")
  625. if cellColours is not None:
  626. if len(cellColours) != rows:
  627. raise ValueError(f"'cellColours' must have {rows} rows")
  628. for row in cellColours:
  629. if len(row) != cols:
  630. raise ValueError("Each row in 'cellColours' must have "
  631. f"{cols} columns")
  632. else:
  633. cellColours = ['w' * cols] * rows
  634. # Set colwidths if not given
  635. if colWidths is None:
  636. colWidths = [1.0 / cols] * cols
  637. # Fill in missing information for column
  638. # and row labels
  639. rowLabelWidth = 0
  640. if rowLabels is None:
  641. if rowColours is not None:
  642. rowLabels = [''] * rows
  643. rowLabelWidth = colWidths[0]
  644. elif rowColours is None:
  645. rowColours = 'w' * rows
  646. if rowLabels is not None:
  647. if len(rowLabels) != rows:
  648. raise ValueError(f"'rowLabels' must be of length {rows}")
  649. # If we have column labels, need to shift
  650. # the text and colour arrays down 1 row
  651. offset = 1
  652. if colLabels is None:
  653. if colColours is not None:
  654. colLabels = [''] * cols
  655. else:
  656. offset = 0
  657. elif colColours is None:
  658. colColours = 'w' * cols
  659. # Set up cell colours if not given
  660. if cellColours is None:
  661. cellColours = ['w' * cols] * rows
  662. # Now create the table
  663. table = Table(ax, loc, bbox, **kwargs)
  664. table.edges = edges
  665. height = table._approx_text_height()
  666. # Add the cells
  667. for row in range(rows):
  668. for col in range(cols):
  669. table.add_cell(row + offset, col,
  670. width=colWidths[col], height=height,
  671. text=cellText[row][col],
  672. facecolor=cellColours[row][col],
  673. loc=cellLoc)
  674. # Do column labels
  675. if colLabels is not None:
  676. for col in range(cols):
  677. table.add_cell(0, col,
  678. width=colWidths[col], height=height,
  679. text=colLabels[col], facecolor=colColours[col],
  680. loc=colLoc)
  681. # Do row labels
  682. if rowLabels is not None:
  683. for row in range(rows):
  684. table.add_cell(row + offset, -1,
  685. width=rowLabelWidth or 1e-15, height=height,
  686. text=rowLabels[row], facecolor=rowColours[row],
  687. loc=rowLoc)
  688. if rowLabelWidth == 0:
  689. table.auto_set_column_width(-1)
  690. ax.add_table(table)
  691. return table