table.py 20.1 KB
Newer Older
xuebingbing's avatar
xuebingbing committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
"""
Place a table below the x-axis at location loc.

The table consists of a grid of cells.

The grid need not be rectangular and can have holes.

Cells are added by specifying their row and column.

For the purposes of positioning the cell at (0, 0) is
assumed to be at the top left and the cell at (max_row, max_col)
is assumed to be at bottom right.

You can add additional cells outside this range to have convenient
ways of positioning more interesting grids.

Author    : John Gill <jng@europe.renre.com>
Copyright : 2004 John Gill and John Hunter
License   : matplotlib license

"""
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import six
from six.moves import xrange

import warnings

from . import artist
from .artist import Artist, allow_rasterization
from .patches import Rectangle
from .cbook import is_string_like
from matplotlib import docstring
from .text import Text
from .transforms import Bbox
from matplotlib.path import Path


class Cell(Rectangle):
    """
    A cell is a Rectangle with some associated text.

    """
    PAD = 0.1  # padding between text and rectangle

    def __init__(self, xy, width, height,
                 edgecolor='k', facecolor='w',
                 fill=True,
                 text='',
                 loc=None,
                 fontproperties=None
                 ):

        # Call base
        Rectangle.__init__(self, xy, width=width, height=height,
                           edgecolor=edgecolor, facecolor=facecolor)
        self.set_clip_on(False)

        # Create text object
        if loc is None:
            loc = 'right'
        self._loc = loc
        self._text = Text(x=xy[0], y=xy[1], text=text,
                          fontproperties=fontproperties)
        self._text.set_clip_on(False)

    def set_transform(self, trans):
        Rectangle.set_transform(self, trans)
        # the text does not get the transform!
        self.stale = True

    def set_figure(self, fig):
        Rectangle.set_figure(self, fig)
        self._text.set_figure(fig)

    def get_text(self):
        'Return the cell Text intance'
        return self._text

    def set_fontsize(self, size):
        self._text.set_fontsize(size)
        self.stale = True

    def get_fontsize(self):
        'Return the cell fontsize'
        return self._text.get_fontsize()

    def auto_set_font_size(self, renderer):
        """ Shrink font size until text fits. """
        fontsize = self.get_fontsize()
        required = self.get_required_width(renderer)
        while fontsize > 1 and required > self.get_width():
            fontsize -= 1
            self.set_fontsize(fontsize)
            required = self.get_required_width(renderer)

        return fontsize

    @allow_rasterization
    def draw(self, renderer):
        if not self.get_visible():
            return
        # draw the rectangle
        Rectangle.draw(self, renderer)

        # position the text
        self._set_text_position(renderer)
        self._text.draw(renderer)
        self.stale = False

    def _set_text_position(self, renderer):
        """ Set text up so it draws in the right place.

        Currently support 'left', 'center' and 'right'
        """
        bbox = self.get_window_extent(renderer)
        l, b, w, h = bbox.bounds

        # draw in center vertically
        self._text.set_verticalalignment('center')
        y = b + (h / 2.0)

        # now position horizontally
        if self._loc == 'center':
            self._text.set_horizontalalignment('center')
            x = l + (w / 2.0)
        elif self._loc == 'left':
            self._text.set_horizontalalignment('left')
            x = l + (w * self.PAD)
        else:
            self._text.set_horizontalalignment('right')
            x = l + (w * (1.0 - self.PAD))

        self._text.set_position((x, y))

    def get_text_bounds(self, renderer):
        """ Get text bounds in axes co-ordinates. """
        bbox = self._text.get_window_extent(renderer)
        bboxa = bbox.inverse_transformed(self.get_data_transform())
        return bboxa.bounds

    def get_required_width(self, renderer):
        """ Get width required for this cell. """
        l, b, w, h = self.get_text_bounds(renderer)
        return w * (1.0 + (2.0 * self.PAD))

    def set_text_props(self, **kwargs):
        'update the text properties with kwargs'
        self._text.update(kwargs)
        self.stale = True


class CustomCell(Cell):
    """
    A subclass of Cell where the sides may be visibly toggled.

    """

    _edges = 'BRTL'
    _edge_aliases = {'open':         '',
                     'closed':       _edges,  # default
                     'horizontal':   'BT',
                     'vertical':     'RL'
                     }

    def __init__(self, *args, **kwargs):
        visible_edges = kwargs.pop('visible_edges')
        Cell.__init__(self, *args, **kwargs)
        self.visible_edges = visible_edges

    @property
    def visible_edges(self):
        return self._visible_edges

    @visible_edges.setter
    def visible_edges(self, value):
        if value is None:
            self._visible_edges = self._edges
        elif value in self._edge_aliases:
            self._visible_edges = self._edge_aliases[value]
        else:
            for edge in value:
                if edge not in self._edges:
                    msg = ('Invalid edge param {0}, must only be one of'
                           ' {1} or string of {2}.').format(
                                   value,
                                   ", ".join(self._edge_aliases.keys()),
                                   ", ".join(self._edges),
                                   )
                    raise ValueError(msg)
            self._visible_edges = value
        self.stale = True

    def get_path(self):
        'Return a path where the edges specificed by _visible_edges are drawn'

        codes = [Path.MOVETO]

        for edge in self._edges:
            if edge in self._visible_edges:
                codes.append(Path.LINETO)
            else:
                codes.append(Path.MOVETO)

        if Path.MOVETO not in codes[1:]:  # All sides are visible
            codes[-1] = Path.CLOSEPOLY

        return Path(
            [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]],
            codes,
            readonly=True
            )


class Table(Artist):
    """
    Create a table of cells.

    Table can have (optional) row and column headers.

    Each entry in the table can be either text or patches.

    Column widths and row heights for the table can be specified.

    Return value is a sequence of text, line and patch instances that make
    up the table
    """
    codes = {'best': 0,
             'upper right':  1,  # default
             'upper left':   2,
             'lower left':   3,
             'lower right':  4,
             'center left':  5,
             'center right': 6,
             'lower center': 7,
             'upper center': 8,
             'center':       9,
             'top right':    10,
             'top left':     11,
             'bottom left':  12,
             'bottom right': 13,
             'right':        14,
             'left':         15,
             'top':          16,
             'bottom':       17,
             }

    FONTSIZE = 10
    AXESPAD = 0.02    # the border between the axes and table edge

    def __init__(self, ax, loc=None, bbox=None, **kwargs):

        Artist.__init__(self)

        if is_string_like(loc) and loc not in self.codes:
            warnings.warn('Unrecognized location %s. Falling back on '
                          'bottom; valid locations are\n%s\t' %
                          (loc, '\n\t'.join(six.iterkeys(self.codes))))
            loc = 'bottom'
        if is_string_like(loc):
            loc = self.codes.get(loc, 1)
        self.set_figure(ax.figure)
        self._axes = ax
        self._loc = loc
        self._bbox = bbox

        # use axes coords
        self.set_transform(ax.transAxes)

        self._texts = []
        self._cells = {}
        self._edges = None
        self._autoRows = []
        self._autoColumns = []
        self._autoFontsize = True
        self.update(kwargs)

        self.set_clip_on(False)

    def add_cell(self, row, col, *args, **kwargs):
        """ Add a cell to the table. """
        xy = (0, 0)

        cell = CustomCell(xy, visible_edges=self.edges, *args, **kwargs)
        cell.set_figure(self.figure)
        cell.set_transform(self.get_transform())

        cell.set_clip_on(False)
        self._cells[(row, col)] = cell
        self.stale = True

    @property
    def edges(self):
        return self._edges

    @edges.setter
    def edges(self, value):
        self._edges = value
        self.stale = True

    def _approx_text_height(self):
        return (self.FONTSIZE / 72.0 * self.figure.dpi /
                self._axes.bbox.height * 1.2)

    @allow_rasterization
    def draw(self, renderer):
        # Need a renderer to do hit tests on mouseevent; assume the last one
        # will do
        if renderer is None:
            renderer = self.figure._cachedRenderer
        if renderer is None:
            raise RuntimeError('No renderer defined')

        if not self.get_visible():
            return
        renderer.open_group('table')
        self._update_positions(renderer)

        keys = list(six.iterkeys(self._cells))
        keys.sort()
        for key in keys:
            self._cells[key].draw(renderer)
        # for c in self._cells.itervalues():
        #     c.draw(renderer)
        renderer.close_group('table')
        self.stale = False

    def _get_grid_bbox(self, renderer):
        """Get a bbox, in axes co-ordinates for the cells.

        Only include those in the range (0,0) to (maxRow, maxCol)"""
        boxes = [self._cells[pos].get_window_extent(renderer)
                 for pos in six.iterkeys(self._cells)
                 if pos[0] >= 0 and pos[1] >= 0]

        bbox = Bbox.union(boxes)
        return bbox.inverse_transformed(self.get_transform())

    def contains(self, mouseevent):
        """Test whether the mouse event occurred in the table.

        Returns T/F, {}
        """
        if six.callable(self._contains):
            return self._contains(self, mouseevent)

        # TODO: Return index of the cell containing the cursor so that the user
        # doesn't have to bind to each one individually.
        renderer = self.figure._cachedRenderer
        if renderer is not None:
            boxes = [self._cells[pos].get_window_extent(renderer)
                     for pos in six.iterkeys(self._cells)
                     if pos[0] >= 0 and pos[1] >= 0]
            bbox = Bbox.union(boxes)
            return bbox.contains(mouseevent.x, mouseevent.y), {}
        else:
            return False, {}

    def get_children(self):
        'Return the Artists contained by the table'
        return list(six.itervalues(self._cells))
    get_child_artists = get_children  # backward compatibility

    def get_window_extent(self, renderer):
        'Return the bounding box of the table in window coords'
        boxes = [cell.get_window_extent(renderer)
                 for cell in six.itervalues(self._cells)]

        return Bbox.union(boxes)

    def _do_cell_alignment(self):
        """ Calculate row heights and column widths.

        Position cells accordingly.
        """
        # Calculate row/column widths
        widths = {}
        heights = {}
        for (row, col), cell in six.iteritems(self._cells):
            height = heights.setdefault(row, 0.0)
            heights[row] = max(height, cell.get_height())
            width = widths.setdefault(col, 0.0)
            widths[col] = max(width, cell.get_width())

        # work out left position for each column
        xpos = 0
        lefts = {}
        cols = list(six.iterkeys(widths))
        cols.sort()
        for col in cols:
            lefts[col] = xpos
            xpos += widths[col]

        ypos = 0
        bottoms = {}
        rows = list(six.iterkeys(heights))
        rows.sort()
        rows.reverse()
        for row in rows:
            bottoms[row] = ypos
            ypos += heights[row]

        # set cell positions
        for (row, col), cell in six.iteritems(self._cells):
            cell.set_x(lefts[col])
            cell.set_y(bottoms[row])

    def auto_set_column_width(self, col):

        self._autoColumns.append(col)
        self.stale = True

    def _auto_set_column_width(self, col, renderer):
        """ Automagically set width for column.
        """
        cells = [key for key in self._cells if key[1] == col]

        # find max width
        width = 0
        for cell in cells:
            c = self._cells[cell]
            width = max(c.get_required_width(renderer), width)

        # Now set the widths
        for cell in cells:
            self._cells[cell].set_width(width)

    def auto_set_font_size(self, value=True):
        """ Automatically set font size. """
        self._autoFontsize = value
        self.stale = True

    def _auto_set_font_size(self, renderer):

        if len(self._cells) == 0:
            return
        fontsize = list(six.itervalues(self._cells))[0].get_fontsize()
        cells = []
        for key, cell in six.iteritems(self._cells):
            # ignore auto-sized columns
            if key[1] in self._autoColumns:
                continue
            size = cell.auto_set_font_size(renderer)
            fontsize = min(fontsize, size)
            cells.append(cell)

        # now set all fontsizes equal
        for cell in six.itervalues(self._cells):
            cell.set_fontsize(fontsize)

    def scale(self, xscale, yscale):
        """ Scale column widths by xscale and row heights by yscale. """
        for c in six.itervalues(self._cells):
            c.set_width(c.get_width() * xscale)
            c.set_height(c.get_height() * yscale)

    def set_fontsize(self, size):
        """
        Set the fontsize of the cell text

        ACCEPTS: a float in points
        """

        for cell in six.itervalues(self._cells):
            cell.set_fontsize(size)
        self.stale = True

    def _offset(self, ox, oy):
        'Move all the artists by ox,oy (axes coords)'

        for c in six.itervalues(self._cells):
            x, y = c.get_x(), c.get_y()
            c.set_x(x + ox)
            c.set_y(y + oy)

    def _update_positions(self, renderer):
        # called from renderer to allow more precise estimates of
        # widths and heights with get_window_extent

        # Do any auto width setting
        for col in self._autoColumns:
            self._auto_set_column_width(col, renderer)

        if self._autoFontsize:
            self._auto_set_font_size(renderer)

        # Align all the cells
        self._do_cell_alignment()

        bbox = self._get_grid_bbox(renderer)
        l, b, w, h = bbox.bounds

        if self._bbox is not None:
            # Position according to bbox
            rl, rb, rw, rh = self._bbox
            self.scale(rw / w, rh / h)
            ox = rl - l
            oy = rb - b
            self._do_cell_alignment()
        else:
            # Position using loc
            (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C,
             TR, TL, BL, BR, R, L, T, B) = list(xrange(len(self.codes)))
            # defaults for center
            ox = (0.5 - w / 2) - l
            oy = (0.5 - h / 2) - b
            if self._loc in (UL, LL, CL):   # left
                ox = self.AXESPAD - l
            if self._loc in (BEST, UR, LR, R, CR):  # right
                ox = 1 - (l + w + self.AXESPAD)
            if self._loc in (BEST, UR, UL, UC):     # upper
                oy = 1 - (b + h + self.AXESPAD)
            if self._loc in (LL, LR, LC):           # lower
                oy = self.AXESPAD - b
            if self._loc in (LC, UC, C):            # center x
                ox = (0.5 - w / 2) - l
            if self._loc in (CL, CR, C):            # center y
                oy = (0.5 - h / 2) - b

            if self._loc in (TL, BL, L):            # out left
                ox = - (l + w)
            if self._loc in (TR, BR, R):            # out right
                ox = 1.0 - l
            if self._loc in (TR, TL, T):            # out top
                oy = 1.0 - b
            if self._loc in (BL, BR, B):           # out bottom
                oy = - (b + h)

        self._offset(ox, oy)

    def get_celld(self):
        'return a dict of cells in the table'
        return self._cells


def table(ax,
          cellText=None, cellColours=None,
          cellLoc='right', colWidths=None,
          rowLabels=None, rowColours=None, rowLoc='left',
          colLabels=None, colColours=None, colLoc='center',
          loc='bottom', bbox=None, edges='closed',
          **kwargs):
    """
    TABLE(cellText=None, cellColours=None,
          cellLoc='right', colWidths=None,
          rowLabels=None, rowColours=None, rowLoc='left',
          colLabels=None, colColours=None, colLoc='center',
          loc='bottom', bbox=None, edges='closed')

    Factory function to generate a Table instance.

    Thanks to John Gill for providing the class and table.
    """

    if cellColours is None and cellText is None:
        raise ValueError('At least one argument from "cellColours" or '
                         '"cellText" must be provided to create a table.')

    # Check we have some cellText
    if cellText is None:
        # assume just colours are needed
        rows = len(cellColours)
        cols = len(cellColours[0])
        cellText = [[''] * cols] * rows

    rows = len(cellText)
    cols = len(cellText[0])
    for row in cellText:
        if len(row) != cols:
            msg = "Each row in 'cellText' must have {0} columns"
            raise ValueError(msg.format(cols))

    if cellColours is not None:
        if len(cellColours) != rows:
            raise ValueError("'cellColours' must have {0} rows".format(rows))
        for row in cellColours:
            if len(row) != cols:
                msg = "Each row in 'cellColours' must have {0} columns"
                raise ValueError(msg.format(cols))
    else:
        cellColours = ['w' * cols] * rows

    # Set colwidths if not given
    if colWidths is None:
        colWidths = [1.0 / cols] * cols

    # Fill in missing information for column
    # and row labels
    rowLabelWidth = 0
    if rowLabels is None:
        if rowColours is not None:
            rowLabels = [''] * rows
            rowLabelWidth = colWidths[0]
    elif rowColours is None:
        rowColours = 'w' * rows

    if rowLabels is not None:
        if len(rowLabels) != rows:
            raise ValueError("'rowLabels' must be of length {0}".format(rows))

    # If we have column labels, need to shift
    # the text and colour arrays down 1 row
    offset = 1
    if colLabels is None:
        if colColours is not None:
            colLabels = [''] * cols
        else:
            offset = 0
    elif colColours is None:
        colColours = 'w' * cols

    # Set up cell colours if not given
    if cellColours is None:
        cellColours = ['w' * cols] * rows

    # Now create the table
    table = Table(ax, loc, bbox, **kwargs)
    table.edges = edges
    height = table._approx_text_height()

    # Add the cells
    for row in xrange(rows):
        for col in xrange(cols):
            table.add_cell(row + offset, col,
                           width=colWidths[col], height=height,
                           text=cellText[row][col],
                           facecolor=cellColours[row][col],
                           loc=cellLoc)
    # Do column labels
    if colLabels is not None:
        for col in xrange(cols):
            table.add_cell(0, col,
                           width=colWidths[col], height=height,
                           text=colLabels[col], facecolor=colColours[col],
                           loc=colLoc)

    # Do row labels
    if rowLabels is not None:
        for row in xrange(rows):
            table.add_cell(row + offset, -1,
                           width=rowLabelWidth or 1e-15, height=height,
                           text=rowLabels[row], facecolor=rowColours[row],
                           loc=rowLoc)
        if rowLabelWidth == 0:
            table.auto_set_column_width(-1)

    ax.add_table(table)
    return table


docstring.interpd.update(Table=artist.kwdoc(Table))