table.py 27 KB

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