table.py 26 KB

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