Esempio n. 1
0
    def __init__(
            self,
            figsize=None,  # defaults to rc figure.figsize
            dpi=None,  # defaults to rc figure.dpi
            facecolor=None,  # defaults to rc figure.facecolor
            edgecolor=None,  # defaults to rc figure.edgecolor
            linewidth=1.0,  # the default linewidth of the frame
            frameon=True,  # whether or not to draw the figure frame
            subplotpars=None,  # default to rc
    ):
        """
        figsize is a w,h tuple in inches
        dpi is dots per inch
        subplotpars is a SubplotParams instance, defaults to rc
        """
        Artist.__init__(self)
        #self.set_figure(self)
        self._axstack = Stack()  # maintain the current axes
        self._axobservers = []
        self._seen = {}  # axes args we've seen

        if figsize is None: figsize = rcParams['figure.figsize']
        if dpi is None: dpi = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self._unit_conversions = {}

        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point(Value(0), Value(0))
        self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi)
        self.bbox = Bbox(self.ll, self.ur)

        self.frameon = frameon

        self.transFigure = get_bbox_transform(unit_bbox(), self.bbox)

        self.figurePatch = Rectangle(
            xy=(0, 0),
            width=1,
            height=1,
            facecolor=facecolor,
            edgecolor=edgecolor,
            linewidth=linewidth,
        )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.canvas = None

        if subplotpars is None:
            subplotpars = SubplotParams()

        self.subplotpars = subplotpars

        self.clf()

        self._cachedRenderer = None
Esempio n. 2
0
 def get_window_extent(self, renderer):
     bbox = Bbox([[0, 0], [0, 0]])
     trans_data_to_xy = self.get_transform().transform
     bbox.update_from_data_xy(trans_data_to_xy(self.get_xydata()), ignore=True)
     # correct for marker size, if any
     if self._marker:
         ms = (self._markersize / 72.0 * self.figure.dpi) * 0.5
         bbox = bbox.padded(ms)
     return bbox
Esempio n. 3
0
 def get_window_extent(self, renderer):
     bbox = Bbox([[0, 0], [0, 0]])
     trans_data_to_xy = self.get_transform().transform
     bbox.update_from_data_xy(trans_data_to_xy(self.get_xydata()),
                              ignore=True)
     # correct for marker size, if any
     if self._marker:
         ms = (self._markersize / 72.0 * self.figure.dpi) * 0.5
         bbox = bbox.padded(ms)
     return bbox
Esempio n. 4
0
    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 self._cells.values()
        ]

        return Bbox.union(boxes)
Esempio n. 5
0
def get_path_collection_extents(
        master_transform, paths, transforms, offsets, offset_transform):
    """
    Given a sequence of :class:`Path` objects,
    :class:`~matplotlib.transforms.Transform` objects and offsets, as
    found in a :class:`~matplotlib.collections.PathCollection`,
    returns the bounding box that encapsulates all of them.

    *master_transform* is a global transformation to apply to all paths

    *paths* is a sequence of :class:`Path` instances.

    *transforms* is a sequence of
    :class:`~matplotlib.transforms.Affine2D` instances.

    *offsets* is a sequence of (x, y) offsets (or an Nx2 array)

    *offset_transform* is a :class:`~matplotlib.transforms.Affine2D`
    to apply to the offsets before applying the offset to the path.

    The way that *paths*, *transforms* and *offsets* are combined
    follows the same method as for collections.  Each is iterated over
    independently, so if you have 3 paths, 2 transforms and 1 offset,
    their combinations are as follows:

        (A, A, A), (B, B, A), (C, A, A)
    """
    from transforms import Bbox
    if len(paths) == 0:
        raise ValueError("No paths provided")
    return Bbox.from_extents(*_get_path_collection_extents(
        master_transform, paths, transforms, offsets, offset_transform))
Esempio n. 6
0
def get_path_collection_extents(master_transform, paths, transforms, offsets,
                                offset_transform):
    """
    Given a sequence of :class:`Path` objects,
    :class:`~matplotlib.transforms.Transform` objects and offsets, as
    found in a :class:`~matplotlib.collections.PathCollection`,
    returns the bounding box that encapsulates all of them.

    *master_transform* is a global transformation to apply to all paths

    *paths* is a sequence of :class:`Path` instances.

    *transforms* is a sequence of
    :class:`~matplotlib.transforms.Affine2D` instances.

    *offsets* is a sequence of (x, y) offsets (or an Nx2 array)

    *offset_transform* is a :class:`~matplotlib.transforms.Affine2D`
    to apply to the offsets before applying the offset to the path.

    The way that *paths*, *transforms* and *offsets* are combined
    follows the same method as for collections.  Each is iterated over
    independently, so if you have 3 paths, 2 transforms and 1 offset,
    their combinations are as follows:

        (A, A, A), (B, B, A), (C, A, A)
    """
    from transforms import Bbox
    if len(paths) == 0:
        raise ValueError("No paths provided")
    return Bbox.from_extents(*_path.get_path_collection_extents(
        master_transform, paths, transforms, offsets, offset_transform))
Esempio n. 7
0
    def __init__(self,
                 figsize   = None,  # defaults to rc figure.figsize
                 dpi       = None,  # defaults to rc figure.dpi
                 facecolor = None,  # defaults to rc figure.facecolor
                 edgecolor = None,  # defaults to rc figure.edgecolor
                 linewidth = 1.0,   # the default linewidth of the frame
                 frameon = True,    # whether or not to draw the figure frame
                 subplotpars = None, # default to rc
                 ):
        """
        figsize is a w,h tuple in inches
        dpi is dots per inch
        subplotpars is a SubplotParams instance, defaults to rc
        """
        Artist.__init__(self)
        #self.set_figure(self)
        self._axstack = Stack()  # maintain the current axes
        self._axobservers = []
        self._seen = {}          # axes args we've seen

        if figsize is None  : figsize   = rcParams['figure.figsize']
        if dpi is None      : dpi       = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self._unit_conversions = {}

        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point( Value(0), Value(0) )
        self.ur = Point( self.figwidth*self.dpi,
                         self.figheight*self.dpi )
        self.bbox = Bbox(self.ll, self.ur)

        self.frameon = frameon

        self.transFigure = get_bbox_transform( unit_bbox(), self.bbox)



        self.figurePatch = Rectangle(
            xy=(0,0), width=1, height=1,
            facecolor=facecolor, edgecolor=edgecolor,
            linewidth=linewidth,
            )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.canvas = None

        if subplotpars is None:
            subplotpars = SubplotParams()

        self.subplotpars = subplotpars

        self.clf()

        self._cachedRenderer = None
Esempio n. 8
0
 def get_window_extent(self, renderer):
     bbox = Bbox.unit()
     bbox.update_from_data_xy(self.get_transform().transform(self.get_xydata()), ignore=True)
     # correct for marker size, if any
     if self._marker is not None:
         ms = (self._markersize / 72.0 * self.figure.dpi) * 0.5
         bbox = bbox.padded(ms)
     return bbox
Esempio n. 9
0
    def __init__(
        self,
        figsize=None,  # defaults to rc figure.figsize
        dpi=None,  # defaults to rc figure.dpi
        facecolor=None,  # defaults to rc figure.facecolor
        edgecolor=None,  # defaults to rc figure.edgecolor
        linewidth=1.0,  # the default linewidth of the frame
        frameon=True,
    ):
        """
        paper size is a w,h tuple in inches
        DPI is dots per inch 
        """
        Artist.__init__(self)
        #self.set_figure(self)
        self._axstack = Stack()  # maintain the current axes
        self._axobservers = []
        self._seen = {}  # axes args we've seen

        if figsize is None: figsize = rcParams['figure.figsize']
        if dpi is None: dpi = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point(Value(0), Value(0))
        self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi)
        self.bbox = Bbox(self.ll, self.ur)
        self.frameon = frameon

        self.transFigure = get_bbox_transform(unit_bbox(), self.bbox)

        self.figurePatch = Rectangle(
            xy=(0, 0),
            width=1,
            height=1,
            facecolor=facecolor,
            edgecolor=edgecolor,
            linewidth=linewidth,
        )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.clf()
Esempio n. 10
0
 def get_window_extent(self, renderer):
     """
     Get the axes bounding box in display space.
     Subclasses should override for inclusion in the bounding box
     "tight" calculation. Default is to return an empty bounding
     box at 0, 0.
     """
     return Bbox([[0, 0], [0, 0]])
Esempio n. 11
0
 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 self._cells.keys() if pos[0] >= 0 and pos[1] >= 0
     ]
     bbox = Bbox.union(boxes)
     return bbox.inverse_transformed(self.get_transform())
Esempio n. 12
0
def get_path_collection_extents(*args):
    """
    Given a sequence of :class:`Path` objects, returns the bounding
    box that encapsulates all of them.
    """
    from transforms import Bbox
    if len(args[1]) == 0:
        raise ValueError("No paths provided")
    return Bbox.from_extents(*_get_path_collection_extents(*args))
Esempio n. 13
0
 def get_window_extent(self, renderer):
     bbox = Bbox.unit()
     bbox.update_from_data_xy(self.get_transform().transform(self.get_xydata()),
                              ignore=True)
     # correct for marker size, if any
     if self._marker is not None:
         ms = (self._markersize / 72.0 * self.figure.dpi) * 0.5
         bbox = bbox.padded(ms)
     return bbox
Esempio n. 14
0
def get_path_collection_extents(*args):
    """
    Given a sequence of :class:`Path` objects, returns the bounding
    box that encapsulates all of them.
    """
    from transforms import Bbox
    if len(args[1]) == 0:
        raise ValueError("No paths provided")
    return Bbox.from_extents(*_get_path_collection_extents(*args))
Esempio n. 15
0
    def get_window_extent(self, renderer=None):
        #return _unit_box
        if not self.get_visible(): return Bbox.unit()
        if self._text == '':
            tx, ty = self._get_xy_display()
            return Bbox.from_bounds(tx,ty,0,0)

        if renderer is not None:
            self._renderer = renderer
        if self._renderer is None:
            raise RuntimeError('Cannot get window extent w/o renderer')

        angle = self.get_rotation()
        bbox, info = self._get_layout(self._renderer)
        x, y = self.get_position()
        x, y = self.get_transform().transform_point((x, y))
        bbox = bbox.translated(x, y)
        return bbox
Esempio n. 16
0
    def get_window_extent(self, renderer=None):
        #return _unit_box
        if not self.get_visible(): return Bbox.unit()
        if self._text == '':
            tx, ty = self._get_xy_display()
            return Bbox.from_bounds(tx, ty, 0, 0)

        if renderer is not None:
            self._renderer = renderer
        if self._renderer is None:
            raise RuntimeError('Cannot get window extent w/o renderer')

        angle = self.get_rotation()
        bbox, info = self._get_layout(self._renderer)
        x, y = self.get_position()
        x, y = self.get_transform().transform_point((x, y))
        bbox = bbox.translated(x, y)
        return bbox
Esempio n. 17
0
 def __init__(
         self,
         figsize=None,  # defaults to rc figure.figsize
         dpi=None,  # defaults to rc figure.dpi
         facecolor=None,  # defaults to rc figure.facecolor
         edgecolor=None,  # defaults to rc figure.edgecolor
         linewidth=1.0,  # the default linewidth of the frame
         frameon=True,  # whether or not to draw the figure frame
         subplotpars=None,  # default to rc
 ):
     """
     *figsize*
         w,h tuple in inches
     *dpi*
         dots per inch
     *facecolor*
         the figure patch facecolor; defaults to rc ``figure.facecolor``
     *edgecolor*
         the figure patch edge color; defaults to rc ``figure.edgecolor``
     *linewidth*
         the figure patch edge linewidth; the default linewidth of the frame
     *frameon*
         if False, suppress drawing the figure frame
     *subplotpars*
         a :class:`SubplotParams` instance, defaults to rc
     """
     Artist.__init__(self)
     self.callbacks = cbook.CallbackRegistry(('dpi_changed', ))
     if figsize is None: figsize = rcParams['figure.figsize']
     if dpi is None: dpi = rcParams['figure.dpi']
     if facecolor is None: facecolor = rcParams['figure.facecolor']
     if edgecolor is None: edgecolor = rcParams['figure.edgecolor']
     self.dpi_scale_trans = Affine2D()
     self.dpi = dpi
     self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
     self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)
     self.frameon = frameon
     self.transFigure = BboxTransformTo(self.bbox)
     self.patch = self.figurePatch = Rectangle(
         xy=(0, 0),
         width=1,
         height=1,
         facecolor=facecolor,
         edgecolor=edgecolor,
         linewidth=linewidth,
     )
     self._set_artist_props(self.patch)
     self._hold = rcParams['axes.hold']
     self.canvas = None
     if subplotpars is None:
         subplotpars = SubplotParams()
     self.subplotpars = subplotpars
     self._axstack = Stack()  # maintain the current axes
     self.axes = []
     self.clf()
     self._cachedRenderer = None
Esempio n. 18
0
    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 self._cells.keys()
                 if pos[0] >= 0 and pos[1] >= 0]

        bbox = Bbox.union(boxes)
        return bbox.inverse_transformed(self.get_transform())
Esempio n. 19
0
    def __init__(
            self,
            figsize=None,  # defaults to rc figure.figsize
            dpi=None,  # defaults to rc figure.dpi
            facecolor=None,  # defaults to rc figure.facecolor
            edgecolor=None,  # defaults to rc figure.edgecolor
            linewidth=1.0,  # the default linewidth of the frame
            frameon=True,  # whether or not to draw the figure frame
            subplotpars=None,  # default to rc
    ):
        """
        figsize is a w,h tuple in inches
        dpi is dots per inch
        subplotpars is a SubplotParams instance, defaults to rc
        """
        Artist.__init__(self)

        if figsize is None: figsize = rcParams['figure.figsize']
        if dpi is None: dpi = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self._dpi_scale_trans = Affine2D()
        self.dpi = dpi
        self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
        self.bbox = TransformedBbox(self.bbox_inches, self._dpi_scale_trans)

        self.frameon = frameon

        self.transFigure = BboxTransformTo(self.bbox)

        self.figurePatch = Rectangle(
            xy=(0, 0),
            width=1,
            height=1,
            facecolor=facecolor,
            edgecolor=edgecolor,
            linewidth=linewidth,
        )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.canvas = None

        if subplotpars is None:
            subplotpars = SubplotParams()

        self.subplotpars = subplotpars

        self._axstack = Stack()  # maintain the current axes
        self.axes = []
        self.clf()

        self._cachedRenderer = None
        self._autoLayout = rcParams['figure.autolayout']
Esempio n. 20
0
    def get_window_extent(self, renderer=None, dpi=None):
        '''
        Return a :class:`~matplotlib.transforms.Bbox` object bounding
        the text, in display units.

        In addition to being used internally, this is useful for
        specifying clickable regions in a png file on a web page.

        *renderer* defaults to the _renderer attribute of the text
        object.  This is not assigned until the first execution of
        :meth:`draw`, so you must use this kwarg if you want
        to call :meth:`get_window_extent` prior to the first
        :meth:`draw`.  For getting web page regions, it is
        simpler to call the method after saving the figure.

        *dpi* defaults to self.figure.dpi; the renderer dpi is
        irrelevant.  For the web application, if figure.dpi is not
        the value used when saving the figure, then the value that
        was used must be specified as the *dpi* argument.
        '''
        #return _unit_box
        if not self.get_visible(): return Bbox.unit()
        if dpi is not None:
            dpi_orig = self.figure.dpi
            self.figure.dpi = dpi
        if self._text == '':
            tx, ty = self._get_xy_display()
            return Bbox.from_bounds(tx,ty,0,0)

        if renderer is not None:
            self._renderer = renderer
        if self._renderer is None:
            raise RuntimeError('Cannot get window extent w/o renderer')

        bbox, info = self._get_layout(self._renderer)
        x, y = self.get_position()
        x, y = self.get_transform().transform_point((x, y))
        bbox = bbox.translated(x, y)
        if dpi is not None:
            self.figure.dpi = dpi_orig
        return bbox
Esempio n. 21
0
    def set_clip_path(self, path, transform=None):
        """
        Set the artist's clip path, which may be:

          * a :class:`~matplotlib.patches.Patch` (or subclass) instance

          * a :class:`~matplotlib.path.Path` instance, in which case
             an optional :class:`~matplotlib.transforms.Transform`
             instance may be provided, which will be applied to the
             path before using it for clipping.

          * *None*, to remove the clipping path

        For efficiency, if the path happens to be an axis-aligned
        rectangle, this method will set the clipping box to the
        corresponding rectangle and set the clipping path to *None*.

        ACCEPTS: [ (:class:`~matplotlib.path.Path`,
        :class:`~matplotlib.transforms.Transform`) |
        :class:`~matplotlib.patches.Patch` | None ]
        """
        from matplotlib.patches import Patch, Rectangle

        success = False
        if transform is None:
            if isinstance(path, Rectangle):
                self.clipbox = TransformedBbox(Bbox.unit(),
                                              path.get_transform())
                self._clippath = None
                success = True
            elif isinstance(path, Patch):
                self._clippath = TransformedPath(
                    path.get_path(),
                    path.get_transform())
                success = True
            elif isinstance(path, tuple):
                path, transform = path

        if path is None:
            self._clippath = None
            success = True
        elif isinstance(path, Path):
            self._clippath = TransformedPath(path, transform)
            success = True
        elif isinstance(path, TransformedPath):
            self._clippath = path
            success = True

        if not success:
            print(type(path), type(transform))
            raise TypeError("Invalid arguments to set_clip_path")

        self.pchanged()
Esempio n. 22
0
    def get_extents(self, transform=None):
        """
        Returns the extents (xmin, ymin, xmax, ymax) of the path.

        Unlike computing the extents on the vertices alone, this
        algorithm will take into account the curves and deal with
        control points appropriately.
        """
        from transforms import Bbox
        if transform is not None:
            transform = transform.frozen()
        return Bbox(get_path_extents(self, transform))
Esempio n. 23
0
    def set_clip_path(self, path, transform=None):
        """
        Set the artist's clip path, which may be:

          * a :class:`~matplotlib.patches.Patch` (or subclass) instance

          * a :class:`~matplotlib.path.Path` instance, in which case
             an optional :class:`~matplotlib.transforms.Transform`
             instance may be provided, which will be applied to the
             path before using it for clipping.

          * *None*, to remove the clipping path

        For efficiency, if the path happens to be an axis-aligned
        rectangle, this method will set the clipping box to the
        corresponding rectangle and set the clipping path to *None*.

        ACCEPTS: [ (:class:`~matplotlib.path.Path`,
        :class:`~matplotlib.transforms.Transform`) |
        :class:`~matplotlib.patches.Patch` | None ]
        """
        from matplotlib.patches import Patch, Rectangle

        success = False
        if transform is None:
            if isinstance(path, Rectangle):
                self.clipbox = TransformedBbox(Bbox.unit(),
                                              path.get_transform())
                self._clippath = None
                success = True
            elif isinstance(path, Patch):
                self._clippath = TransformedPath(
                    path.get_path(),
                    path.get_transform())
                success = True
            elif isinstance(path, tuple):
                path, transform = path

        if path is None:
            self._clippath = None
            success = True
        elif isinstance(path, Path):
            self._clippath = TransformedPath(path, transform)
            success = True
        elif isinstance(path, TransformedPath):
            self._clippath = path
            success = True

        if not success:
            print(type(path), type(transform))
            raise TypeError("Invalid arguments to set_clip_path")

        self.pchanged()
Esempio n. 24
0
 def get_tightbbox(self, renderer):
     """
     Return a (tight) bounding box of the figure in inches.
     It only accounts axes title, axis labels, and axis
     ticklabels. Needs improvement.
     """
     bb = []
     for ax in self.axes:
         if ax.get_visible():
             bb.append(ax.get_tightbbox(renderer))
     _bbox = Bbox.union([b for b in bb if b.width != 0 or b.height != 0])
     bbox_inches = TransformedBbox(_bbox, Affine2D().scale(1. / self.dpi))
     return bbox_inches
Esempio n. 25
0
    def __init__(self,
                 figsize   = None,  # defaults to rc figure.figsize
                 dpi       = None,  # defaults to rc figure.dpi
                 facecolor = None,  # defaults to rc figure.facecolor
                 edgecolor = None,  # defaults to rc figure.edgecolor
                 linewidth = 1.0,   # the default linewidth of the frame
                 frameon = True,    # whether or not to draw the figure frame
                 subplotpars = None, # default to rc
                 ):
        """
        figsize is a w,h tuple in inches
        dpi is dots per inch
        subplotpars is a SubplotParams instance, defaults to rc
        """
        Artist.__init__(self)

        if figsize is None  : figsize   = rcParams['figure.figsize']
        if dpi is None      : dpi       = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

	self._dpi_scale_trans = Affine2D()
        self.dpi = dpi
	self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
	self.bbox = TransformedBbox(self.bbox_inches, self._dpi_scale_trans)

        self.frameon = frameon

        self.transFigure = BboxTransformTo(self.bbox)

        self.figurePatch = Rectangle(
            xy=(0,0), width=1, height=1,
            facecolor=facecolor, edgecolor=edgecolor,
            linewidth=linewidth,
            )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.canvas = None

        if subplotpars is None:
            subplotpars = SubplotParams()

        self.subplotpars = subplotpars

        self._axstack = Stack()  # maintain the current axes
        self.axes = []
        self.clf()

        self._cachedRenderer = None
        self._autoLayout = rcParams['figure.autolayout']
Esempio n. 26
0
    def _get_handle_text_bbox(self, renderer):
        'Get a bbox for the text and lines in axes coords'

        bboxesText = [t.get_window_extent(renderer) for t in self.texts]
        bboxesHandles = [h.get_window_extent(renderer) for h in self.legendHandles if h is not None]

        bboxesAll = bboxesText
        bboxesAll.extend(bboxesHandles)
        bbox = Bbox.union(bboxesAll)

        self.save = bbox

        ibox = bbox.inverse_transformed(self.get_transform())
        self.ibox = ibox

        return ibox
Esempio n. 27
0
    def get_extents(self, transform=None):
        """
        Returns the extents (*xmin*, *ymin*, *xmax*, *ymax*) of the
        path.

        Unlike computing the extents on the *vertices* alone, this
        algorithm will take into account the curves and deal with
        control points appropriately.
        """
        from transforms import Bbox
        path = self
        if transform is not None:
            transform = transform.frozen()
            if not transform.is_affine:
                path = self.transformed(transform)
                transform = None
        return Bbox(get_path_extents(path, transform))
Esempio n. 28
0
    def set_clip_path(self, path, transform=None):
        """
        Set the artist's clip path, which may be:

          a) a Patch (or subclass) instance

          b) a Path instance, in which cas aoptional transform may
             be provided, which will be applied to the path before using it
             for clipping.

          c) None, to remove the clipping path

        For efficiency, if the path happens to be an axis-aligned
        rectangle, this method will set the clipping box to the
        corresponding rectangle and set the clipping path to None.
             
        ACCEPTS: a Path instance and a Transform instance, a Patch
        instance, or None
        """
        from patches import Patch, Rectangle

        success = False
        if transform is None:
            if isinstance(path, Rectangle):
                self.clipbox = TransformedBbox(Bbox.unit(),
                                               path.get_transform())
                self._clippath = None
                success = True
            elif isinstance(path, Patch):
                self._clippath = TransformedPath(path.get_path(),
                                                 path.get_transform())
                success = True

        if path is None:
            self._clippath = None
            success = True
        elif isinstance(path, Path):
            self._clippath = TransformedPath(path, transform)
            success = True

        if not success:
            print type(path), type(transform)
            raise TypeError("Invalid arguments to set_clip_path")

        self._clipon = self.clipbox is not None or self._clippath is not None
        self.pchanged()
Esempio n. 29
0
    def set_clip_path(self, path, transform=None):
        """
        Set the artist's clip path, which may be:

          a) a Patch (or subclass) instance

          b) a Path instance, in which cas aoptional transform may
             be provided, which will be applied to the path before using it
             for clipping.

          c) None, to remove the clipping path

        For efficiency, if the path happens to be an axis-aligned
        rectangle, this method will set the clipping box to the
        corresponding rectangle and set the clipping path to None.

        ACCEPTS: a Path instance and a Transform instance, a Patch
        instance, or None
        """
        from patches import Patch, Rectangle

        success = False
        if transform is None:
            if isinstance(path, Rectangle):
                self.clipbox = TransformedBbox(Bbox.unit(), path.get_transform())
                self._clippath = None
                success = True
            elif isinstance(path, Patch):
                self._clippath = TransformedPath(
                    path.get_path(),
                    path.get_transform())
                success = True

        if path is None:
            self._clippath = None
            success = True
        elif isinstance(path, Path):
            self._clippath = TransformedPath(path, transform)
            success = True

        if not success:
            print type(path), type(transform)
            raise TypeError("Invalid arguments to set_clip_path")

        self._clipon = self.clipbox is not None or self._clippath is not None
        self.pchanged()
Esempio n. 30
0
def get_paths_extents(paths, transforms=[]):
    """
    Given a sequence of :class:`Path` objects and optional
    :class:`~matplotlib.transforms.Transform` objects, returns the
    bounding box that encapsulates all of them.

    *paths* is a sequence of :class:`Path` instances.

    *transforms* is an optional sequence of
    :class:`~matplotlib.transforms.Affine2D` instances to apply to
    each path.
    """
    from transforms import Bbox, Affine2D
    if len(paths) == 0:
        raise ValueError("No paths provided")
    return Bbox.from_extents(*_path.get_path_collection_extents(
        Affine2D(), paths, transforms, [], Affine2D()))
Esempio n. 31
0
    def __init__(
        self,
        figsize=None,  # defaults to rc figure.figsize
        dpi=None,  # defaults to rc figure.dpi
        facecolor=None,  # defaults to rc figure.facecolor
        edgecolor=None,  # defaults to rc figure.edgecolor
        linewidth=1.0,  # the default linewidth of the frame
        frameon=True,
    ):
        """
        paper size is a w,h tuple in inches
        DPI is dots per inch 
        """
        Artist.__init__(self)
        # self.set_figure(self)
        self._axstack = Stack()  # maintain the current axes
        self._axobservers = []
        self._seen = {}  # axes args we've seen

        if figsize is None:
            figsize = rcParams["figure.figsize"]
        if dpi is None:
            dpi = rcParams["figure.dpi"]
        if facecolor is None:
            facecolor = rcParams["figure.facecolor"]
        if edgecolor is None:
            edgecolor = rcParams["figure.edgecolor"]

        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point(Value(0), Value(0))
        self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi)
        self.bbox = Bbox(self.ll, self.ur)
        self.frameon = frameon

        self.transFigure = get_bbox_transform(unit_bbox(), self.bbox)

        self.figurePatch = Rectangle(
            xy=(0, 0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth
        )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams["axes.hold"]
        self.canvas = None
        self.clf()
Esempio n. 32
0
def get_paths_extents(paths, transforms=[]):
    """
    Given a sequence of :class:`Path` objects and optional
    :class:`~matplotlib.transforms.Transform` objects, returns the
    bounding box that encapsulates all of them.

    *paths* is a sequence of :class:`Path` instances.

    *transforms* is an optional sequence of
    :class:`~matplotlib.transforms.Affine2D` instances to apply to
    each path.
    """
    from transforms import Bbox, Affine2D
    if len(paths) == 0:
        raise ValueError("No paths provided")
    return Bbox.from_extents(*_get_path_collection_extents(
        Affine2D(), paths, transforms, [], Affine2D()))
Esempio n. 33
0
    def _find_best_position(self, width, height, consider=None):
        """Determine the best location to place the legend.

        `consider` is a list of (x, y) pairs to consider as a potential
        lower-left corner of the legend. All are axes coords.
        """

        assert self.isaxes  # should always hold because function is only called internally

        verts, bboxes, lines = self._auto_legend_data()

        consider = [
            self._loc_to_axes_coords(x, width, height)
            for x in range(1, len(self.codes))
        ]

        tx, ty = self.legendPatch.get_x(), self.legendPatch.get_y()

        candidates = []
        for l, b in consider:
            legendBox = Bbox.from_bounds(l, b, width, height)
            badness = 0
            badness = legendBox.count_contains(verts)
            badness += legendBox.count_overlaps(bboxes)
            for line in lines:
                if line.intersects_bbox(legendBox):
                    badness += 1

            ox, oy = l - tx, b - ty
            if badness == 0:
                return ox, oy

            candidates.append((badness, (ox, oy)))

        # rather than use min() or list.sort(), do this so that we are assured
        # that in the case of two equal badnesses, the one first considered is
        # returned.
        minCandidate = candidates[0]
        for candidate in candidates:
            if candidate[0] < minCandidate[0]:
                minCandidate = candidate

        ox, oy = minCandidate[1]

        return ox, oy
Esempio n. 34
0
    def contains(self, mouseevent):
        """Test whether the mouse event occurred in the table.

        Returns T/F, {}
        """
        if 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.
        if self._cachedRenderer is not None:
            boxes = [self._cells[pos].get_window_extent(self._cachedRenderer)
                 for pos in self._cells.iterkeys()
                 if pos[0] >= 0 and pos[1] >= 0]
            bbox = Bbox.union(boxes)
            return bbox.contains(mouseevent.x, mouseevent.y), {}
        else:
            return False, {}
Esempio n. 35
0
    def contains(self, mouseevent):
        """Test whether the mouse event occurred in the table.

        Returns T/F, {}
        """
        if 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.
        if self._cachedRenderer is not None:
            boxes = [self._cells[pos].get_window_extent(self._cachedRenderer)
                 for pos in self._cells.iterkeys()
                 if pos[0] >= 0 and pos[1] >= 0]
            bbox = Bbox.union(boxes)
            return bbox.contains(mouseevent.x, mouseevent.y), {}
        else:
            return False, {}
Esempio n. 36
0
    def get_tightbbox(self, renderer):
        """
        Return a (tight) bounding box of the figure in inches.

        It only accounts axes title, axis labels, and axis
        ticklabels. Needs improvement.
        """

        bb = []
        for ax in self.axes:
            if ax.get_visible():
                bb.append(ax.get_tightbbox(renderer))

        _bbox = Bbox.union([b for b in bb if b.width != 0 or b.height != 0])

        bbox_inches = TransformedBbox(_bbox, Affine2D().scale(1. / self.dpi))

        return bbox_inches
Esempio n. 37
0
    def __init__(self,
                 figsize   = None,  # defaults to rc figure.figsize
                 dpi       = None,  # defaults to rc figure.dpi
                 facecolor = None,  # defaults to rc figure.facecolor
                 edgecolor = None,  # defaults to rc figure.edgecolor
                 linewidth = 1.0,   # the default linewidth of the frame
                 frameon = True,
                 ):
        """
        paper size is a w,h tuple in inches
        DPI is dots per inch 
        """
        Artist.__init__(self)
        #self.set_figure(self)

        if figsize is None  : figsize   = rcParams['figure.figsize']
        if dpi is None      : dpi       = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']
        
        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point( Value(0), Value(0) )
        self.ur = Point( self.figwidth*self.dpi,
                         self.figheight*self.dpi )
        self.bbox = Bbox(self.ll, self.ur)
        self.frameon = frameon
        
        self.transFigure = get_bbox_transform( unit_bbox(), self.bbox) 


        
        self.figurePatch = Rectangle(
            xy=(0,0), width=1, height=1,
            facecolor=facecolor, edgecolor=edgecolor,
            linewidth=linewidth,
            )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.clf()
Esempio n. 38
0
    def _find_best_position(self, width, height, consider=None):
        """Determine the best location to place the legend.

        `consider` is a list of (x, y) pairs to consider as a potential
        lower-left corner of the legend. All are axes coords.
        """

        assert self.isaxes # should always hold because function is only called internally

        verts, bboxes, lines = self._auto_legend_data()

        consider = [self._loc_to_axes_coords(x, width, height) for x in range(1, len(self.codes))]

        tx, ty = self.legendPatch.get_x(), self.legendPatch.get_y()

        candidates = []
        for l, b in consider:
            legendBox = Bbox.from_bounds(l, b, width, height)
            badness = 0
            badness = legendBox.count_contains(verts)
            badness += legendBox.count_overlaps(bboxes)
            for line in lines:
                if line.intersects_bbox(legendBox):
                    badness += 1

            ox, oy = l-tx, b-ty
            if badness == 0:
                return ox, oy

            candidates.append((badness, (ox, oy)))

        # rather than use min() or list.sort(), do this so that we are assured
        # that in the case of two equal badnesses, the one first considered is
        # returned.
        minCandidate = candidates[0]
        for candidate in candidates:
            if candidate[0] < minCandidate[0]:
                minCandidate = candidate

        ox, oy = minCandidate[1]

        return ox, oy
Esempio n. 39
0
class Figure(Artist):
    
    def __init__(self,
                 figsize   = None,  # defaults to rc figure.figsize
                 dpi       = None,  # defaults to rc figure.dpi
                 facecolor = None,  # defaults to rc figure.facecolor
                 edgecolor = None,  # defaults to rc figure.edgecolor
                 linewidth = 1.0,   # the default linewidth of the frame
                 frameon = True,
                 ):
        """
        paper size is a w,h tuple in inches
        DPI is dots per inch 
        """
        Artist.__init__(self)
        #self.set_figure(self)
        self._axstack = Stack()  # maintain the current axes
        self._axobservers = []
        self._seen = {}          # axes args we've seen        

        if figsize is None  : figsize   = rcParams['figure.figsize']
        if dpi is None      : dpi       = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']
        
        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point( Value(0), Value(0) )
        self.ur = Point( self.figwidth*self.dpi,
                         self.figheight*self.dpi )
        self.bbox = Bbox(self.ll, self.ur)
        self.frameon = frameon
        
        self.transFigure = get_bbox_transform( unit_bbox(), self.bbox) 


        
        self.figurePatch = Rectangle(
            xy=(0,0), width=1, height=1,
            facecolor=facecolor, edgecolor=edgecolor,
            linewidth=linewidth,
            )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.clf()

        
    def hold(self, b=None):
        """
        Set the hold state.  If hold is None (default), toggle the
        hold state.  Else set the hold state to boolean value b.

        Eg
        hold()      # toggle hold
        hold(True)  # hold is on
        hold(False) # hold is off
        """
        if b is None: self._hold = not self._hold
        else: self._hold = b

    def figimage(self, X,
                 xo=0,
                 yo=0,
                 alpha=1.0,
                 norm=None,
                 cmap=None, 
                 vmin=None,
                 vmax=None,
                 origin=None):
        """\
FIGIMAGE(X) # add non-resampled array to figure

FIGIMAGE(X, xo, yo) # with pixel offsets

FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc

Add a nonresampled figure to the figure from array X.  xo and yo are
offsets in pixels

X must be a float array

    If X is MxN, assume luminance (grayscale)
    If X is MxNx3, assume RGB
    If X is MxNx4, assume RGBA

The following kwargs are allowed: 

  * cmap is a cm colormap instance, eg cm.jet.  If None, default to
    the rc image.cmap valuex

  * norm is a matplotlib.colors.normalize instance; default is
    normalization().  This scales luminance -> 0-1

  * vmin and vmax are used to scale a luminance image to 0-1.  If
    either is None, the min and max of the luminance values will be
    used.  Note if you pass a norm instance, the settings for vmin and
    vmax will be ignored.

  * alpha = 1.0 : the alpha blending value

  * origin is either 'upper' or 'lower', which indicates where the [0,0]
    index of the array is in the upper left or lower left corner of
    the axes.  Defaults to the rc image.origin value

This complements the axes image which will be resampled to fit the
current axes.  If you want a resampled image to fill the entire
figure, you can define an Axes with size [0,1,0,1].

A image.FigureImage instance is returned.
"""        

        if not self._hold: self.clf()

        im = FigureImage(self, cmap, norm, xo, yo, origin)
        im.set_array(X)
        im.set_alpha(alpha)
        if norm is None:
            im.set_clim(vmin, vmax)
        self.images.append(im )
        return im

        
    def set_figsize_inches(self, *args):
        """
Set the figure size in inches

Usage: set_figsize_inches(self, w,h)  OR
       set_figsize_inches(self, (w,h) )

ACCEPTS: a w,h tuple with w,h in inches
"""
        if len(args)==1:
            w,h = args[0]
        else:
            w,h = args
        self.figwidth.set(w)
        self.figheight.set(h)

    def get_size_inches(self):
        return self.figwidth.get(), self.figheight.get()

    def get_edgecolor(self):
        'Get the edge color of the Figure rectangle' 
        return self.figurePatch.get_edgecolor()

    def get_facecolor(self):
        'Get the face color of the Figure rectangle'
        return self.figurePatch.get_facecolor()

    def set_edgecolor(self, color):
        """
Set the edge color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)"""
        self.figurePatch.set_edgecolor(color)

    def set_facecolor(self, color):
        """
Set the face color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)"""
        self.figurePatch.set_facecolor(color)

    def delaxes(self, a):
        'remove a from the figure and update the current axes'
        self.axes.remove(a)
        self._axstack.remove(a)
        keys = []
        for key, thisax in self._seen.items():
            if a==thisax: del self._seen[key]
        for func in self._axobservers: func(self)        
            

    def add_axes(self, *args, **kwargs):
        """
Add an a axes with axes rect [left, bottom, width, height] where all
quantities are in fractions of figure width and height.  kwargs are
legal Axes kwargs plus"polar" which sets whether to create a polar axes

    add_axes((l,b,w,h))
    add_axes((l,b,w,h), frameon=False, axisbg='g')
    add_axes((l,b,w,h), polar=True)
    add_axes(ax)   # add an Axes instance


If the figure already has an axed with key *args, *kwargs then it
will simply make that axes current and return it

The Axes instance will be returned
        """

        if iterable(args[0]):
            key = tuple(args[0]), tuple(kwargs.items())
        else:
            key = args[0], tuple(kwargs.items())            

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return        
        if isinstance(args[0], Axes):
            a = args[0]
            a.set_figure(self)
        else:
            rect = args[0]
            ispolar = popd(kwargs, 'polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)            
                

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    def add_subplot(self, *args, **kwargs):
        """
Add an a subplot.  Examples

    add_subplot(111)
    add_subplot(212, axisbg='r')  # add subplot with red background
    add_subplot(111, polar=True)  # add a polar subplot
    add_subplot(sub)              # add Subplot instance sub
        
kwargs are legal Axes kwargs plus"polar" which sets whether to create a
polar axes.  The Axes instance will be returned.

If the figure already has a subplot with key *args, *kwargs then it will
simply make that subplot current and return it
        """
        
        key = args, tuple(kwargs.items())
        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax
        
                
        if not len(args): return        
        
        if isinstance(args[0], Subplot) or isinstance(args, PolarSubplot):
            a = args[0]
            a.set_figure(self)
        else:
            ispolar = popd(kwargs, 'polar', False)
            if ispolar:
                a = PolarSubplot(self, *args, **kwargs)
            else:
                a = Subplot(self, *args, **kwargs)

        
        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a
    
    def clf(self):
        """
        Clear the figure
        """
        self.axes = []
        self._axstack.clear()
        self._seen = {}
        self.lines = []
        self.patches = []
        self.texts=[]
        self.images = []
        self.legends = []

    def clear(self):
        """
        Clear the figure
        """
        self.clf()
        
    def draw(self, renderer):
        """
        Render the figure using RendererGD instance renderer
        """
        # draw the figure bounding box, perhaps none for white figure
        #print 'figure draw'
        if not self.get_visible(): return 
        renderer.open_group('figure')
        self.transFigure.freeze()  # eval the lazy objects
        if self.frameon: self.figurePatch.draw(renderer)

        for p in self.patches: p.draw(renderer)
        for l in self.lines: l.draw(renderer)

        if len(self.images)==1:
            im = self.images[0]
            im.draw(renderer)
        elif len(self.images)>1:
            # make a composite image blending alpha
            # list of (_image.Image, ox, oy)
            if not allequal([im.origin for im in self.images]):
                raise ValueError('Composite images with different origins not supported')
            else:
                origin = self.images[0].origin

            ims = [(im.make_image(), im.ox, im.oy) for im in self.images]
            im = _image.from_images(self.bbox.height(), self.bbox.width(), ims)
            im.is_grayscale = False
            l, b, w, h = self.bbox.get_bounds()
            renderer.draw_image(0, 0, im, origin, self.bbox)



        # render the axes
        for a in self.axes: a.draw(renderer)

        # render the figure text
        for t in self.texts: t.draw(renderer)

        for legend in self.legends:
            legend.draw(renderer)

        self.transFigure.thaw()  # release the lazy objects
        renderer.close_group('figure')

    def get_axes(self):
        return self.axes

    def legend(self, handles, labels, loc, **kwargs):
        """
        Place a legend in the figure.  Labels are a sequence of
        strings, handles is a sequence of line or patch instances, and
        loc can be a string or an integer specifying the legend
        location

        USAGE: 
          legend( (line1, line2, line3),
                  ('label1', 'label2', 'label3'),
                  'upper right')

        The LOC location codes are

          'best' : 0,          (currently not supported, defaults to upper right)
          'upper right'  : 1,  (default)
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,

        The legend instance is returned
        """


        handles = flatten(handles)
        l = Legend(self, handles, labels, loc, isaxes=False, **kwargs)
        self._set_artist_props(l)
        self.legends.append(l)
        return l
    
    def text(self, x, y, s, *args, **kwargs):
        """
        Add text to figure at location x,y (relative 0-1 coords) See
        the help for Axis text for the meaning of the other arguments
        """

        override = _process_text_args({}, *args, **kwargs)
        t = Text(
            x=x, y=y, text=s,
            )

        t.update(override)
        self._set_artist_props(t)
        self.texts.append(t)
        return t

    def _set_artist_props(self, a):
        if a!= self:
            a.set_figure(self)
        a.set_transform(self.transFigure)

    def get_width_height(self):
        'return the figure width and height in pixels'
        w = self.bbox.width()
        h = self.bbox.height()
        return w, h


    def gca(self, **kwargs):
        """
Return the current axes, creating one if necessary
        """
        ax = self._axstack()
        if ax is not None: return ax
        return self.add_subplot(111, **kwargs)
        
    def sca(self, a):
        'Set the current axes to be a and return a'
        self._axstack.bubble(a)
        for func in self._axobservers: func(self)
        return a

    def add_axobserver(self, func):
        'whenever the axes state change, func(self) will be called'
        self._axobservers.append(func)
Esempio n. 40
0
class Figure(Artist):
    def __str__(self):
        return "Figure(%gx%g)" % (self.figwidth.get(), self.figheight.get())

    def __init__(
            self,
            figsize=None,  # defaults to rc figure.figsize
            dpi=None,  # defaults to rc figure.dpi
            facecolor=None,  # defaults to rc figure.facecolor
            edgecolor=None,  # defaults to rc figure.edgecolor
            linewidth=1.0,  # the default linewidth of the frame
            frameon=True,  # whether or not to draw the figure frame
            subplotpars=None,  # default to rc
    ):
        """
        figsize is a w,h tuple in inches
        dpi is dots per inch
        subplotpars is a SubplotParams instance, defaults to rc
        """
        Artist.__init__(self)

        if figsize is None: figsize = rcParams['figure.figsize']
        if dpi is None: dpi = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point(Value(0), Value(0))
        self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi)
        self.bbox = Bbox(self.ll, self.ur)

        self.frameon = frameon

        self.transFigure = get_bbox_transform(unit_bbox(), self.bbox)

        self.figurePatch = Rectangle(
            xy=(0, 0),
            width=1,
            height=1,
            facecolor=facecolor,
            edgecolor=edgecolor,
            linewidth=linewidth,
        )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.canvas = None

        if subplotpars is None:
            subplotpars = SubplotParams()

        self.subplotpars = subplotpars

        self._axstack = Stack()  # maintain the current axes
        self.axes = []
        self.clf()

        self._cachedRenderer = None

    def autofmt_xdate(self, bottom=0.2, rotation=30, ha='right'):
        """
        Date ticklabels often overlap, so it is useful to rotate them
        and right align them.  Also, a common use case is a number of
        subplots with shared xaxes where the x-axis is date data.  The
        ticklabels are often long, and it helps to rotate them on the
        bottom subplot and turn them off on other subplots, as well as
        turn off xlabels.


        bottom : the bottom of the subplots for subplots_adjust
        rotation: the rotation of the xtick labels
        ha : the horizontal alignment of the xticklabels


        """

        allsubplots = npy.alltrue(
            [hasattr(ax, 'is_last_row') for ax in self.axes])
        if len(self.axes) == 1:
            for label in ax.get_xticklabels():
                label.set_ha(ha)
                label.set_rotation(rotation)
        else:
            if allsubplots:
                for ax in self.get_axes():
                    if ax.is_last_row():
                        for label in ax.get_xticklabels():
                            label.set_ha(ha)
                            label.set_rotation(rotation)
                    else:
                        for label in ax.get_xticklabels():
                            label.set_visible(False)
                        ax.set_xlabel('')

        if allsubplots:
            self.subplots_adjust(bottom=bottom)

    def get_children(self):
        'get a list of artists contained in the figure'
        children = [self.figurePatch]
        children.extend(self.axes)
        children.extend(self.lines)
        children.extend(self.patches)
        children.extend(self.texts)
        children.extend(self.images)
        children.extend(self.legends)
        return children

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

        Returns True,{}
        """
        if callable(self._contains): return self._contains(self, mouseevent)
        #inside = mouseevent.x >= 0 and mouseevent.y >= 0
        inside = self.bbox.contains(mouseevent.x, mouseevent.y)

        return inside, {}

    def get_window_extent(self, *args, **kwargs):
        'get the figure bounding box in display space; kwargs are void'
        return self.bbox

    def set_canvas(self, canvas):
        """
        Set the canvas the contains the figure

        ACCEPTS: a FigureCanvas instance
        """
        self.canvas = canvas

    def hold(self, b=None):
        """
        Set the hold state.  If hold is None (default), toggle the
        hold state.  Else set the hold state to boolean value b.

        Eg
        hold()      # toggle hold
        hold(True)  # hold is on
        hold(False) # hold is off
        """
        if b is None: self._hold = not self._hold
        else: self._hold = b

    def figimage(self,
                 X,
                 xo=0,
                 yo=0,
                 alpha=1.0,
                 norm=None,
                 cmap=None,
                 vmin=None,
                 vmax=None,
                 origin=None):
        """
        FIGIMAGE(X) # add non-resampled array to figure

        FIGIMAGE(X, xo, yo) # with pixel offsets

        FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc

        Add a nonresampled figure to the figure from array X.  xo and yo are
        offsets in pixels

        X must be a float array

            If X is MxN, assume luminance (grayscale)
            If X is MxNx3, assume RGB
            If X is MxNx4, assume RGBA

        The following kwargs are allowed:

          * cmap is a cm colormap instance, eg cm.jet.  If None, default to
            the rc image.cmap valuex

          * norm is a matplotlib.colors.Normalize instance; default is
            normalization().  This scales luminance -> 0-1

          * vmin and vmax are used to scale a luminance image to 0-1.  If
            either is None, the min and max of the luminance values will be
            used.  Note if you pass a norm instance, the settings for vmin and
            vmax will be ignored.

          * alpha = 1.0 : the alpha blending value

          * origin is either 'upper' or 'lower', which indicates where the [0,0]
            index of the array is in the upper left or lower left corner of
            the axes.  Defaults to the rc image.origin value

        This complements the axes image (Axes.imshow) which will be resampled
        to fit the current axes.  If you want a resampled image to fill the
        entire figure, you can define an Axes with size [0,1,0,1].

        A image.FigureImage instance is returned.
        """

        if not self._hold: self.clf()

        im = FigureImage(self, cmap, norm, xo, yo, origin)
        im.set_array(X)
        im.set_alpha(alpha)
        if norm is None:
            im.set_clim(vmin, vmax)
        self.images.append(im)
        return im

    def set_figsize_inches(self, *args, **kwargs):
        import warnings
        warnings.warn('Use set_size_inches instead!', DeprecationWarning)
        self.set_size_inches(*args, **kwargs)

    def set_size_inches(self, *args, **kwargs):
        """
        set_size_inches(w,h, forward=False)

        Set the figure size in inches

        Usage: set_size_inches(self, w,h)  OR
               set_size_inches(self, (w,h) )

        optional kwarg forward=True will cause the canvas size to be
        automatically updated; eg you can resize the figure window
        from the shell

        WARNING: forward=True is broken on all backends except GTK*

        ACCEPTS: a w,h tuple with w,h in inches
        """

        forward = kwargs.get('forward', False)
        if len(args) == 1:
            w, h = args[0]
        else:
            w, h = args
        self.figwidth.set(w)
        self.figheight.set(h)

        if forward:
            dpival = self.dpi.get()
            canvasw = w * dpival
            canvash = h * dpival
            manager = getattr(self.canvas, 'manager', None)
            if manager is not None:
                manager.resize(int(canvasw), int(canvash))

    def get_size_inches(self):
        return self.figwidth.get(), self.figheight.get()

    def get_edgecolor(self):
        'Get the edge color of the Figure rectangle'
        return self.figurePatch.get_edgecolor()

    def get_facecolor(self):
        'Get the face color of the Figure rectangle'
        return self.figurePatch.get_facecolor()

    def get_figwidth(self):
        'Return the figwidth as a float'
        return self.figwidth.get()

    def get_figheight(self):
        'Return the figheight as a float'
        return self.figheight.get()

    def get_dpi(self):
        'Return the dpi as a float'
        return self.dpi.get()

    def get_frameon(self):
        'get the boolean indicating frameon'
        return self.frameon

    def set_edgecolor(self, color):
        """
        Set the edge color of the Figure rectangle

        ACCEPTS: any matplotlib color - see help(colors)
        """
        self.figurePatch.set_edgecolor(color)

    def set_facecolor(self, color):
        """
        Set the face color of the Figure rectangle

        ACCEPTS: any matplotlib color - see help(colors)
        """
        self.figurePatch.set_facecolor(color)

    def set_dpi(self, val):
        """
        Set the dots-per-inch of the figure

        ACCEPTS: float
        """
        self.dpi.set(val)

    def set_figwidth(self, val):
        """
        Set the width of the figure in inches

        ACCEPTS: float
        """
        self.figwidth.set(val)

    def set_figheight(self, val):
        """
        Set the height of the figure in inches

        ACCEPTS: float
        """
        self.figheight.set(val)

    def set_frameon(self, b):
        """
        Set whether the figure frame (background) is displayed or invisible

        ACCEPTS: boolean
        """
        self.frameon = b

    def delaxes(self, a):
        'remove a from the figure and update the current axes'
        self.axes.remove(a)
        self._axstack.remove(a)
        keys = []
        for key, thisax in self._seen.items():
            if a == thisax: del self._seen[key]
        for func in self._axobservers:
            func(self)

    def _make_key(self, *args, **kwargs):
        'make a hashable key out of args and kwargs'

        def fixitems(items):
            #items may have arrays and lists in them, so convert them
            # to tuples for the key
            ret = []
            for k, v in items:
                if iterable(v): v = tuple(v)
                ret.append((k, v))
            return tuple(ret)

        def fixlist(args):
            ret = []
            for a in args:
                if iterable(a): a = tuple(a)
                ret.append(a)
            return tuple(ret)

        key = fixlist(args), fixitems(kwargs.items())
        return key

    def add_axes(self, *args, **kwargs):
        """
        Add an a axes with axes rect [left, bottom, width, height] where all
        quantities are in fractions of figure width and height.  kwargs are
        legal Axes kwargs plus "polar" which sets whether to create a polar axes

            rect = l,b,w,h
            add_axes(rect)
            add_axes(rect, frameon=False, axisbg='g')
            add_axes(rect, polar=True)
            add_axes(ax)   # add an Axes instance


        If the figure already has an axes with key *args, *kwargs then it will
        simply make that axes current and return it.  If you do not want this
        behavior, eg you want to force the creation of a new axes, you must
        use a unique set of args and kwargs.  The artist "label" attribute has
        been exposed for this purpose.  Eg, if you want two axes that are
        otherwise identical to be added to the figure, make sure you give them
        unique labels:

            add_axes(rect, label='axes1')
            add_axes(rect, label='axes2')

        The Axes instance will be returned

        The following kwargs are supported:
        %(Axes)s
        """

        key = self._make_key(*args, **kwargs)

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return
        if isinstance(args[0], Axes):
            a = args[0]
            assert (a.get_figure() is self)
        else:
            rect = args[0]
            ispolar = kwargs.pop('polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    add_axes.__doc__ = dedent(add_axes.__doc__) % artist.kwdocd

    def add_subplot(self, *args, **kwargs):
        """
        Add a subplot.  Examples

            add_subplot(111)
            add_subplot(1,1,1)            # equivalent but more general
            add_subplot(212, axisbg='r')  # add subplot with red background
            add_subplot(111, polar=True)  # add a polar subplot
            add_subplot(sub)              # add Subplot instance sub

        kwargs are legal Axes kwargs plus"polar" which sets whether to create a
        polar axes.  The Axes instance will be returned.

        If the figure already has a subplot with key *args, *kwargs then it will
        simply make that subplot current and return it

        The following kwargs are supported:
        %(Axes)s
        """

        key = self._make_key(*args, **kwargs)
        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return

        if isinstance(args[0], Subplot) or isinstance(args[0], PolarSubplot):
            a = args[0]
            assert (a.get_figure() is self)
        else:
            ispolar = kwargs.pop('polar', False)
            if ispolar:
                a = PolarSubplot(self, *args, **kwargs)
            else:
                a = Subplot(self, *args, **kwargs)

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    add_subplot.__doc__ = dedent(add_subplot.__doc__) % artist.kwdocd

    def clf(self):
        """
        Clear the figure
        """
        for ax in tuple(self.axes):  # Iterate over the copy.
            ax.cla()
            self.delaxes(ax)  # removes ax from self.axes

        toolbar = getattr(self.canvas, 'toolbar', None)
        if toolbar is not None:
            toolbar.update()
        self._axstack.clear()
        self._seen = {}
        self.lines = []
        self.patches = []
        self.texts = []
        self.images = []
        self.legends = []
        self._axobservers = []

    def clear(self):
        """
        Clear the figure
        """
        self.clf()

    def draw(self, renderer):
        """
        Render the figure using Renderer instance renderer
        """
        # draw the figure bounding box, perhaps none for white figure
        #print 'figure draw'
        if not self.get_visible(): return
        renderer.open_group('figure')
        self.transFigure.freeze()  # eval the lazy objects

        if self.frameon: self.figurePatch.draw(renderer)

        for p in self.patches:
            p.draw(renderer)
        for l in self.lines:
            l.draw(renderer)

        if len(self.images) <= 1 or renderer.option_image_nocomposite(
        ) or not allequal([im.origin for im in self.images]):
            for im in self.images:
                im.draw(renderer)
        else:
            # make a composite image blending alpha
            # list of (_image.Image, ox, oy)

            mag = renderer.get_image_magnification()
            ims = [(im.make_image(mag), im.ox * mag, im.oy * mag)
                   for im in self.images]
            im = _image.from_images(self.bbox.height() * mag,
                                    self.bbox.width() * mag, ims)
            im.is_grayscale = False
            l, b, w, h = self.bbox.get_bounds()
            renderer.draw_image(l, b, im, self.bbox)

        # render the axes
        for a in self.axes:
            a.draw(renderer)

        # render the figure text
        for t in self.texts:
            t.draw(renderer)

        for legend in self.legends:
            legend.draw(renderer)

        self.transFigure.thaw()  # release the lazy objects
        renderer.close_group('figure')

        self._cachedRenderer = renderer

        self.canvas.draw_event(renderer)

    def draw_artist(self, a):
        'draw artist only -- this is available only after the figure is drawn'
        assert self._cachedRenderer is not None
        a.draw(self._cachedRenderer)

    def get_axes(self):
        return self.axes

    def legend(self, handles, labels, *args, **kwargs):
        """
        Place a legend in the figure.  Labels are a sequence of
        strings, handles is a sequence of line or patch instances, and
        loc can be a string or an integer specifying the legend
        location

        USAGE:
          legend( (line1, line2, line3),
                  ('label1', 'label2', 'label3'),
                  'upper right')

        The LOC location codes are

          'best' : 0,          (currently not supported for figure legends)
          'upper right'  : 1,
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,

        loc can also be an (x,y) tuple in figure coords, which
        specifies the lower left of the legend box.  figure coords are
        (0,0) is the left, bottom of the figure and 1,1 is the right,
        top.

        The legend instance is returned.  The following kwargs are supported:

        loc = "upper right" #
        numpoints = 4         # the number of points in the legend line
        prop = FontProperties(size='smaller')  # the font property
        pad = 0.2             # the fractional whitespace inside the legend border
        markerscale = 0.6     # the relative size of legend markers vs. original
        shadow                # if True, draw a shadow behind legend
        labelsep = 0.005     # the vertical space between the legend entries
        handlelen = 0.05     # the length of the legend lines
        handletextsep = 0.02 # the space between the legend line and legend text
        axespad = 0.02       # the border between the axes and legend edge

        """

        handles = flatten(handles)
        l = Legend(self, handles, labels, *args, **kwargs)
        self._set_artist_props(l)
        self.legends.append(l)
        return l

    def text(self, x, y, s, *args, **kwargs):
        """
        Add text to figure at location x,y (relative 0-1 coords) See
        the help for Axis text for the meaning of the other arguments

        kwargs control the Text properties:
        %(Text)s
        """

        override = _process_text_args({}, *args, **kwargs)
        t = Text(
            x=x,
            y=y,
            text=s,
        )

        t.update(override)
        self._set_artist_props(t)
        self.texts.append(t)
        return t

    text.__doc__ = dedent(text.__doc__) % artist.kwdocd

    def _set_artist_props(self, a):
        if a != self:
            a.set_figure(self)
        a.set_transform(self.transFigure)

    def gca(self, **kwargs):
        """
        Return the current axes, creating one if necessary

        The following kwargs are supported
        %(Axes)s
        """
        ax = self._axstack()
        if ax is not None: return ax
        return self.add_subplot(111, **kwargs)

    gca.__doc__ = dedent(gca.__doc__) % artist.kwdocd

    def sca(self, a):
        'Set the current axes to be a and return a'
        self._axstack.bubble(a)
        for func in self._axobservers:
            func(self)
        return a

    def add_axobserver(self, func):
        'whenever the axes state change, func(self) will be called'
        self._axobservers.append(func)

    def savefig(self, *args, **kwargs):
        """
        SAVEFIG(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None):

        Save the current figure.

        fname - the filename to save the current figure to.  The
                output formats supported depend on the backend being
                used.  and are deduced by the extension to fname.
                Possibilities are eps, jpeg, pdf, png, ps, svg.  fname
                can also be a file or file-like object - cairo backend
                only.

        dpi - is the resolution in dots per inch.  If
              None it will default to the value savefig.dpi in the
              matplotlibrc file

        facecolor and edgecolor are the colors of the figure rectangle

        orientation is either 'landscape' or 'portrait' - not supported on
        all backends; currently only on postscript output

        papertype is is one of 'letter', 'legal', 'executive', 'ledger', 'a0'
        through 'a10', or 'b0' through 'b10' - only supported for postscript
        output

        format - one of the file extensions supported by the active backend.
        """

        for key in ('dpi', 'facecolor', 'edgecolor'):
            if not kwargs.has_key(key):
                kwargs[key] = rcParams['savefig.%s' % key]

        self.canvas.print_figure(*args, **kwargs)

    def colorbar(self, mappable, cax=None, ax=None, **kw):
        if ax is None:
            ax = self.gca()
        if cax is None:
            cax, kw = cbar.make_axes(ax, **kw)
        cb = cbar.Colorbar(cax, mappable, **kw)
        mappable.add_observer(cb)
        mappable.set_colorbar(cb, cax)
        self.sca(ax)
        return cb

    colorbar.__doc__ = '''
        Create a colorbar for a ScalarMappable instance.

        Documentation for the pylab thin wrapper: %s
        ''' % cbar.colorbar_doc

    def subplots_adjust(self, *args, **kwargs):
        """
        subplots_adjust(self, left=None, bottom=None, right=None, top=None,
                        wspace=None, hspace=None)
        fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None):
        Update the SubplotParams with kwargs (defaulting to rc where
        None) and update the subplot locations
        """
        self.subplotpars.update(*args, **kwargs)
        import matplotlib.axes
        for ax in self.axes:
            if not isinstance(ax, matplotlib.axes.Subplot):
                # Check if sharing a subplots axis
                if ax._sharex is not None and isinstance(
                        ax._sharex, matplotlib.axes.Subplot):
                    ax._sharex.update_params()
                    ax.set_position([
                        ax._sharex.figLeft, ax._sharex.figBottom,
                        ax._sharex.figW, ax._sharex.figH
                    ])
                elif ax._sharey is not None and isinstance(
                        ax._sharey, matplotlib.axes.Subplot):
                    ax._sharey.update_params()
                    ax.set_position([
                        ax._sharey.figLeft, ax._sharey.figBottom,
                        ax._sharey.figW, ax._sharey.figH
                    ])
            else:
                ax.update_params()
                ax.set_position([ax.figLeft, ax.figBottom, ax.figW, ax.figH])
Esempio n. 41
0
class Figure(Artist):
    def __init__(
        self,
        figsize=None,  # defaults to rc figure.figsize
        dpi=None,  # defaults to rc figure.dpi
        facecolor=None,  # defaults to rc figure.facecolor
        edgecolor=None,  # defaults to rc figure.edgecolor
        linewidth=1.0,  # the default linewidth of the frame
        frameon=True,
    ):
        """
        paper size is a w,h tuple in inches
        DPI is dots per inch 
        """
        Artist.__init__(self)
        #self.set_figure(self)
        self._axstack = Stack()  # maintain the current axes
        self._axobservers = []
        self._seen = {}  # axes args we've seen

        if figsize is None: figsize = rcParams['figure.figsize']
        if dpi is None: dpi = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point(Value(0), Value(0))
        self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi)
        self.bbox = Bbox(self.ll, self.ur)
        self.frameon = frameon

        self.transFigure = get_bbox_transform(unit_bbox(), self.bbox)

        self.figurePatch = Rectangle(
            xy=(0, 0),
            width=1,
            height=1,
            facecolor=facecolor,
            edgecolor=edgecolor,
            linewidth=linewidth,
        )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.canvas = None
        self.clf()

    def set_canvas(self, canvas):
        """\
Set the canvas the contains the figure

ACCEPTS: a FigureCanvas instance"""
        self.canvas = canvas

    def hold(self, b=None):
        """
        Set the hold state.  If hold is None (default), toggle the
        hold state.  Else set the hold state to boolean value b.

        Eg
        hold()      # toggle hold
        hold(True)  # hold is on
        hold(False) # hold is off
        """
        if b is None: self._hold = not self._hold
        else: self._hold = b

    def figimage(self,
                 X,
                 xo=0,
                 yo=0,
                 alpha=1.0,
                 norm=None,
                 cmap=None,
                 vmin=None,
                 vmax=None,
                 origin=None):
        """\
FIGIMAGE(X) # add non-resampled array to figure

FIGIMAGE(X, xo, yo) # with pixel offsets

FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc

Add a nonresampled figure to the figure from array X.  xo and yo are
offsets in pixels

X must be a float array

    If X is MxN, assume luminance (grayscale)
    If X is MxNx3, assume RGB
    If X is MxNx4, assume RGBA

The following kwargs are allowed: 

  * cmap is a cm colormap instance, eg cm.jet.  If None, default to
    the rc image.cmap valuex

  * norm is a matplotlib.colors.normalize instance; default is
    normalization().  This scales luminance -> 0-1

  * vmin and vmax are used to scale a luminance image to 0-1.  If
    either is None, the min and max of the luminance values will be
    used.  Note if you pass a norm instance, the settings for vmin and
    vmax will be ignored.

  * alpha = 1.0 : the alpha blending value

  * origin is either 'upper' or 'lower', which indicates where the [0,0]
    index of the array is in the upper left or lower left corner of
    the axes.  Defaults to the rc image.origin value

This complements the axes image (Axes.imshow) which will be resampled
to fit the current axes.  If you want a resampled image to fill the
entire figure, you can define an Axes with size [0,1,0,1].

A image.FigureImage instance is returned.
"""

        if not self._hold: self.clf()

        im = FigureImage(self, cmap, norm, xo, yo, origin)
        im.set_array(X)
        im.set_alpha(alpha)
        if norm is None:
            im.set_clim(vmin, vmax)
        self.images.append(im)
        return im

    def set_figsize_inches(self, *args):
        """
Set the figure size in inches

Usage: set_figsize_inches(self, w,h)  OR
       set_figsize_inches(self, (w,h) )

ACCEPTS: a w,h tuple with w,h in inches
"""
        if len(args) == 1:
            w, h = args[0]
        else:
            w, h = args
        self.figwidth.set(w)
        self.figheight.set(h)

    def get_size_inches(self):
        return self.figwidth.get(), self.figheight.get()

    def get_edgecolor(self):
        'Get the edge color of the Figure rectangle'
        return self.figurePatch.get_edgecolor()

    def get_facecolor(self):
        'Get the face color of the Figure rectangle'
        return self.figurePatch.get_facecolor()

    def get_figwidth(self):
        'Return the figwidth as a float'
        return self.figwidth.get()

    def get_figheight(self):
        'Return the figheight as a float'
        return self.figheight.get()

    def get_dpi(self):
        'Return the dpi as a float'
        return self.dpi.get()

    def get_frameon(self):
        'get the boolean indicating frameon'
        return self.frameon

    def set_edgecolor(self, color):
        """
Set the edge color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)"""
        self.figurePatch.set_edgecolor(color)

    def set_facecolor(self, color):
        """
Set the face color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)"""
        self.figurePatch.set_facecolor(color)

    def set_dpi(self, val):
        """
Set the dots-per-inch of the figure

ACCEPTS: float"""
        self.dpi.set(val)

    def set_figwidth(self, val):
        """
Set the width of the figure in inches

ACCEPTS: float"""
        self.figwidth.set(val)

    def set_figheight(self, val):
        """
Set the height of the figure in inches

ACCEPTS: float"""
        self.figheight.set(val)

    def set_frameon(self, b):
        """
Set whether the figure frame (background) is displayed or invisible

ACCEPTS: boolean"""
        self.frameon = b

    def delaxes(self, a):
        'remove a from the figure and update the current axes'
        self.axes.remove(a)
        self._axstack.remove(a)
        keys = []
        for key, thisax in self._seen.items():
            if a == thisax: del self._seen[key]
        for func in self._axobservers:
            func(self)

    def add_axes(self, *args, **kwargs):
        """
Add an a axes with axes rect [left, bottom, width, height] where all
quantities are in fractions of figure width and height.  kwargs are
legal Axes kwargs plus"polar" which sets whether to create a polar axes

    add_axes((l,b,w,h))
    add_axes((l,b,w,h), frameon=False, axisbg='g')
    add_axes((l,b,w,h), polar=True)
    add_axes(ax)   # add an Axes instance


If the figure already has an axes with key *args, *kwargs then it will
simply make that axes current and return it.  If you do not want this
behavior, eg you want to force the creation of a new axes, you must
use a unique set of args and kwargs.  The artist "label" attribute has
been exposed for this purpose.  Eg, if you want two axes that are
otherwise identical to be added to the axes, make sure you give them
unique labels:

    add_axes((l,b,w,h), label='1')
    add_axes((l,b,w,h), label='2')

The Axes instance will be returned
        """

        if iterable(args[0]):
            key = tuple(args[0]), tuple(kwargs.items())
        else:
            key = args[0], tuple(kwargs.items())

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return
        if isinstance(args[0], Axes):
            a = args[0]
            a.set_figure(self)
        else:
            rect = args[0]
            ispolar = popd(kwargs, 'polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    def add_subplot(self, *args, **kwargs):
        """
Add an a subplot.  Examples

    add_subplot(111)
    add_subplot(212, axisbg='r')  # add subplot with red background
    add_subplot(111, polar=True)  # add a polar subplot
    add_subplot(sub)              # add Subplot instance sub
        
kwargs are legal Axes kwargs plus"polar" which sets whether to create a
polar axes.  The Axes instance will be returned.

If the figure already has a subplot with key *args, *kwargs then it will
simply make that subplot current and return it
        """

        key = args, tuple(kwargs.items())
        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return

        if isinstance(args[0], Subplot) or isinstance(args, PolarSubplot):
            a = args[0]
            a.set_figure(self)
        else:
            ispolar = popd(kwargs, 'polar', False)
            if ispolar:
                a = PolarSubplot(self, *args, **kwargs)
            else:
                a = Subplot(self, *args, **kwargs)

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    def clf(self):
        """
        Clear the figure
        """
        self.axes = []
        self._axstack.clear()
        self._seen = {}
        self.lines = []
        self.patches = []
        self.texts = []
        self.images = []
        self.legends = []

    def clear(self):
        """
        Clear the figure
        """
        self.clf()

    def draw(self, renderer):
        """
        Render the figure using RendererGD instance renderer
        """
        # draw the figure bounding box, perhaps none for white figure
        #print 'figure draw'
        if not self.get_visible(): return
        renderer.open_group('figure')
        self.transFigure.freeze()  # eval the lazy objects
        if self.frameon: self.figurePatch.draw(renderer)

        for p in self.patches:
            p.draw(renderer)
        for l in self.lines:
            l.draw(renderer)

        if len(self.images) == 1:
            im = self.images[0]
            im.draw(renderer)
        elif len(self.images) > 1:
            # make a composite image blending alpha
            # list of (_image.Image, ox, oy)
            if not allequal([im.origin for im in self.images]):
                raise ValueError(
                    'Composite images with different origins not supported')
            else:
                origin = self.images[0].origin

            ims = [(im.make_image(), im.ox, im.oy) for im in self.images]
            im = _image.from_images(self.bbox.height(), self.bbox.width(), ims)
            im.is_grayscale = False
            l, b, w, h = self.bbox.get_bounds()
            renderer.draw_image(0, 0, im, origin, self.bbox)

        # render the axes
        for a in self.axes:
            a.draw(renderer)

        # render the figure text
        for t in self.texts:
            t.draw(renderer)

        for legend in self.legends:
            legend.draw(renderer)

        self.transFigure.thaw()  # release the lazy objects
        renderer.close_group('figure')

    def get_axes(self):
        return self.axes

    def legend(self, handles, labels, loc, **kwargs):
        """
        Place a legend in the figure.  Labels are a sequence of
        strings, handles is a sequence of line or patch instances, and
        loc can be a string or an integer specifying the legend
        location

        USAGE: 
          legend( (line1, line2, line3),
                  ('label1', 'label2', 'label3'),
                  'upper right')

        The LOC location codes are

          'best' : 0,          (currently not supported, defaults to upper right)
          'upper right'  : 1,  (default)
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,

        loc can also be an (x,y) tuple in figure coords, which
        specifies the lower left of the legend box.  figure coords are
        (0,0) is the left, bottom of the figure and 1,1 is the right,
        top.

        The legend instance is returned
        """

        handles = flatten(handles)
        l = Legend(self, handles, labels, loc, isaxes=False, **kwargs)
        self._set_artist_props(l)
        self.legends.append(l)
        return l

    def text(self, x, y, s, *args, **kwargs):
        """
        Add text to figure at location x,y (relative 0-1 coords) See
        the help for Axis text for the meaning of the other arguments
        """

        override = _process_text_args({}, *args, **kwargs)
        t = Text(
            x=x,
            y=y,
            text=s,
        )

        t.update(override)
        self._set_artist_props(t)
        self.texts.append(t)
        return t

    def _set_artist_props(self, a):
        if a != self:
            a.set_figure(self)
        a.set_transform(self.transFigure)

    def get_width_height(self):
        'return the figure width and height in pixels'
        w = self.bbox.width()
        h = self.bbox.height()
        return w, h

    def gca(self, **kwargs):
        """
Return the current axes, creating one if necessary
        """
        ax = self._axstack()
        if ax is not None: return ax
        return self.add_subplot(111, **kwargs)

    def sca(self, a):
        'Set the current axes to be a and return a'
        self._axstack.bubble(a)
        for func in self._axobservers:
            func(self)
        return a

    def add_axobserver(self, func):
        'whenever the axes state change, func(self) will be called'
        self._axobservers.append(func)

    def savefig(self, *args, **kwargs):
        """
SAVEFIG(fname, dpi=150, facecolor='w', edgecolor='w',
orientation='portrait'):

Save the current figure to filename fname.  dpi is the resolution
in dots per inch.

Output file types currently supported are jpeg and png and will be
deduced by the extension to fname

facecolor and edgecolor are the colors os the figure rectangle

orientation is either 'landscape' or 'portrait' - not supported on
all backends; currently only on postscript output."""

        for key in ('dpi', 'facecolor', 'edgecolor'):
            if not kwargs.has_key(key):
                kwargs[key] = rcParams['savefig.%s' % key]

        self.canvas.print_figure(*args, **kwargs)

    def colorbar(self,
                 mappable,
                 tickfmt='%1.1f',
                 cax=None,
                 orientation='vertical'):
        """
        Create a colorbar for mappable image

        tickfmt is a format string to format the colorbar ticks

        cax is a colorbar axes instance in which the colorbar will be
        placed.  If None, as default axesd will be created resizing the
        current aqxes to make room for it.  If not None, the supplied axes
        will be used and the other axes positions will be unchanged.

        orientation is the colorbar orientation: one of 'vertical' | 'horizontal'
        return value is the colorbar axes instance
        """

        if orientation not in ('horizontal', 'vertical'):
            raise ValueError('Orientation must be horizontal or vertical')

        if isinstance(mappable, FigureImage) and cax is None:
            raise TypeError(
                'Colorbars for figure images currently not supported unless you provide a colorbar axes in cax'
            )

        ax = self.gca()

        cmap = mappable.cmap
        norm = mappable.norm

        if norm.vmin is None or norm.vmax is None:
            mappable.autoscale()
        cmin = norm.vmin
        cmax = norm.vmax

        if cax is None:
            l, b, w, h = ax.get_position()
            if orientation == 'vertical':
                neww = 0.8 * w
                ax.set_position((l, b, neww, h))
                cax = self.add_axes([l + 0.9 * w, b, 0.1 * w, h])
            else:
                newh = 0.8 * h
                ax.set_position((l, b + 0.2 * h, w, newh))
                cax = self.add_axes([l, b, w, 0.1 * h])

        else:
            if not isinstance(cax, Axes):
                raise TypeError('Expected an Axes instance for cax')

        N = cmap.N

        c = linspace(cmin, cmax, N)
        C = array([c, c])

        if orientation == 'vertical':
            C = transpose(C)

        if orientation == 'vertical':
            extent = (0, 1, cmin, cmax)
        else:
            extent = (cmin, cmax, 0, 1)
        coll = cax.imshow(C,
                          interpolation='nearest',
                          origin='lower',
                          cmap=cmap,
                          norm=norm,
                          extent=extent)
        mappable.add_observer(coll)
        mappable.set_colorbar(coll, cax)

        if orientation == 'vertical':
            cax.set_xticks([])
            cax.yaxis.tick_right()
            cax.yaxis.set_major_formatter(FormatStrFormatter(tickfmt))
        else:
            cax.set_yticks([])
            cax.xaxis.set_major_formatter(FormatStrFormatter(tickfmt))

        self.sca(ax)
        return cax
Esempio n. 42
0
    def __init__(
        self,
        figsize=None,  # defaults to rc figure.figsize
        dpi=None,  # defaults to rc figure.dpi
        facecolor=None,  # defaults to rc figure.facecolor
        edgecolor=None,  # defaults to rc figure.edgecolor
        linewidth=0.0,  # the default linewidth of the frame
        frameon=True,  # whether or not to draw the figure frame
        subplotpars=None,  # default to rc
    ):
        """
        *figsize*
            w,h tuple in inches

        *dpi*
            Dots per inch

        *facecolor*
            The figure patch facecolor; defaults to rc ``figure.facecolor``

        *edgecolor*
            The figure patch edge color; defaults to rc ``figure.edgecolor``

        *linewidth*
            The figure patch edge linewidth; the default linewidth of the frame

        *frameon*
            If *False*, suppress drawing the figure frame

        *subplotpars*
            A :class:`SubplotParams` instance, defaults to rc
        """
        Artist.__init__(self)

        self.callbacks = cbook.CallbackRegistry()

        if figsize is None:
            figsize = rcParams["figure.figsize"]
        if dpi is None:
            dpi = rcParams["figure.dpi"]
        if facecolor is None:
            facecolor = rcParams["figure.facecolor"]
        if edgecolor is None:
            edgecolor = rcParams["figure.edgecolor"]

        self.dpi_scale_trans = Affine2D()
        self.dpi = dpi
        self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
        self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)

        self.frameon = frameon

        self.transFigure = BboxTransformTo(self.bbox)

        # the figurePatch name is deprecated
        self.patch = self.figurePatch = Rectangle(
            xy=(0, 0), width=1, height=1, facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth
        )
        self._set_artist_props(self.patch)
        self.patch.set_aa(False)

        self._hold = rcParams["axes.hold"]
        self.canvas = None

        if subplotpars is None:
            subplotpars = SubplotParams()

        self.subplotpars = subplotpars

        self._axstack = AxesStack()  # track all figure axes and current axes
        self.clf()
        self._cachedRenderer = None
Esempio n. 43
0
class Figure(Artist):
    def __init__(
        self,
        figsize=None,  # defaults to rc figure.figsize
        dpi=None,  # defaults to rc figure.dpi
        facecolor=None,  # defaults to rc figure.facecolor
        edgecolor=None,  # defaults to rc figure.edgecolor
        linewidth=1.0,  # the default linewidth of the frame
        frameon=True,
    ):
        """
        paper size is a w,h tuple in inches
        DPI is dots per inch 
        """
        Artist.__init__(self)
        #self.set_figure(self)

        if figsize is None: figsize = rcParams['figure.figsize']
        if dpi is None: dpi = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point(Value(0), Value(0))
        self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi)
        self.bbox = Bbox(self.ll, self.ur)
        self.frameon = frameon

        self.transFigure = get_bbox_transform(unit_bbox(), self.bbox)

        self.figurePatch = Rectangle(
            xy=(0, 0),
            width=1,
            height=1,
            facecolor=facecolor,
            edgecolor=edgecolor,
            linewidth=linewidth,
        )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.clf()

    def hold(self, b=None):
        """
        Set the hold state.  If hold is None (default), toggle the
        hold state.  Else set the hold state to boolean value b.

        Eg
        hold()      # toggle hold
        hold(True)  # hold is on
        hold(False) # hold is off
        """
        if b is None: self._hold = not self._hold
        else: self._hold = b

    def figimage(self,
                 X,
                 xo=0,
                 yo=0,
                 alpha=1.0,
                 norm=None,
                 cmap=None,
                 vmin=None,
                 vmax=None,
                 origin=None):
        """\
FIGIMAGE(X) # add non-resampled array to figure

FIGIMAGE(X, xo, yo) # with pixel offsets

FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc

Add a nonresampled figure to the figure from array X.  xo and yo are
offsets in pixels

X must be a float array

    If X is MxN, assume luminance (grayscale)
    If X is MxNx3, assume RGB
    If X is MxNx4, assume RGBA

The following kwargs are allowed: 

  * cmap is a cm colormap instance, eg cm.jet.  If None, default to
    the rc image.cmap valuex

  * norm is a matplotlib.colors.normalize instance; default is
    normalization().  This scales luminance -> 0-1

  * vmin and vmax are used to scale a luminance image to 0-1.  If
    either is None, the min and max of the luminance values will be
    used.  Note if you pass a norm instance, the settings for vmin and
    vmax will be ignored.

  * alpha = 1.0 : the alpha blending value

  * origin is either 'upper' or 'lower', which indicates where the [0,0]
    index of the array is in the upper left or lower left corner of
    the axes.  Defaults to the rc image.origin value

This complements the axes image which will be resampled to fit the
current axes.  If you want a resampled image to fill the entire
figure, you can define an Axes with size [0,1,0,1].

A image.FigureImage instance is returned.
"""

        if not self._hold: self.clf()

        im = FigureImage(self, cmap, norm, xo, yo, origin)
        im.set_array(X)
        im.set_alpha(alpha)
        if norm is None:
            im.set_clim(vmin, vmax)
        self.images.append(im)
        return im

    def set_figsize_inches(self, w, h):
        'set the figure size in inches'
        self.figwidth.set(w)
        self.figheight.set(h)

    def get_size_inches(self):
        return self.figwidth.get(), self.figheight.get()

    def get_edgecolor(self):
        'Get the edge color of the Figure rectangle'  #
        return self.figurePatch.get_edgecolor()

    def get_facecolor(self):
        'Get the face color of the Figure rectangle'
        return self.figurePatch.get_facecolor()

    def set_edgecolor(self, color):
        'Set the edge color of the Figure rectangle'
        self.figurePatch.set_edgecolor(color)

    def set_facecolor(self, color):
        'Set the face color of the Figure rectangle'
        self.figurePatch.set_facecolor(color)

    def add_axis(self, *args, **kwargs):
        raise SystemExit("""\
matplotlib changed its axes creation API in 0.54.
Please see http://matplotlib.sourceforge.net/API_CHANGES for
instructions on how to port your code.
""")

    def add_axes(self, rect, axisbg=None, frameon=True, **kwargs):
        """
        Add an a axes with axes rect [left, bottom, width, height]
        where all quantities are in fractions of figure width and
        height.

        The Axes instance will be returned
        """
        if axisbg is None: axisbg = rcParams['axes.facecolor']
        ispolar = kwargs.get('polar', False)
        if ispolar:
            a = PolarAxes(self, rect, axisbg, frameon)
        else:
            a = Axes(self, rect, axisbg, frameon)
        self.axes.append(a)
        return a

    def add_subplot(self, *args, **kwargs):
        """
        Add an a subplot, eg
        add_subplot(111) or add_subplot(212, axisbg='r')

        The Axes instance will be returned
        """
        ispolar = kwargs.get('polar', False)
        dict_delall(kwargs, ('polar', ))
        if ispolar:
            a = PolarSubplot(self, *args, **kwargs)
        else:
            a = Subplot(self, *args, **kwargs)

        self.axes.append(a)

        return a

    def clf(self):
        """
        Clear the figure
        """
        self.axes = []
        self.lines = []
        self.patches = []
        self.texts = []
        self.images = []
        self.legends = []

    def clear(self):
        """
        Clear the figure
        """
        self.clf()

    def draw(self, renderer):
        """
        Render the figure using RendererGD instance renderer
        """
        # draw the figure bounding box, perhaps none for white figure

        renderer.open_group('figure')
        self.transFigure.freeze()  # eval the lazy objects
        if self.frameon: self.figurePatch.draw(renderer)

        for p in self.patches:
            p.draw(renderer)
        for l in self.lines:
            l.draw(renderer)

        if len(self.images) == 1:
            im = self.images[0]
            im.draw(renderer)
        elif len(self.images) > 1:
            # make a composite image blending alpha
            # list of (_image.Image, ox, oy)
            if not allequal([im.origin for im in self.images]):
                raise ValueError(
                    'Composite images with different origins not supported')
            else:
                origin = self.images[0].origin

            ims = [(im.make_image(), im.ox, im.oy) for im in self.images]
            im = _image.from_images(self.bbox.height(), self.bbox.width(), ims)
            im.is_grayscale = False
            l, b, w, h = self.bbox.get_bounds()
            renderer.draw_image(0, 0, im, origin, self.bbox)

        # render the axes
        for a in self.axes:
            a.draw(renderer)

        # render the figure text
        for t in self.texts:
            t.draw(renderer)

        for legend in self.legends:
            legend.draw(renderer)

        self.transFigure.thaw()  # release the lazy objects
        renderer.close_group('figure')

    def get_axes(self):
        return self.axes

    def legend(self, handles, labels, loc, **kwargs):
        """
        Place a legend in the figure.  Labels are a sequence of
        strings, handles is a sequence of line or patch instances, and
        loc can be a string or an integer specifying the legend
        location

        USAGE: 
          legend( (line1, line2, line3),
                  ('label1', 'label2', 'label3'),
                  'upper right')

        The LOC location codes are

          'best' : 0,          (currently not supported, defaults to upper right)
          'upper right'  : 1,  (default)
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,

        The legend instance is returned
        """

        handles = flatten(handles)
        l = Legend(self, handles, labels, loc, isaxes=False, **kwargs)
        self._set_artist_props(l)
        self.legends.append(l)
        return l

    def text(self, x, y, s, *args, **kwargs):
        """
        Add text to figure at location x,y (relative 0-1 coords) See
        the help for Axis text for the meaning of the other arguments
        """

        override = _process_text_args({}, *args, **kwargs)
        t = Text(
            x=x,
            y=y,
            text=s,
        )

        t.update(override)
        self._set_artist_props(t)
        self.texts.append(t)
        return t

    def _set_artist_props(self, a):
        if a != self:
            a.set_figure(self)
        a.set_transform(self.transFigure)

    def get_width_height(self):
        'return the figure width and height in pixels'
        w = self.bbox.width()
        h = self.bbox.height()
        return w, h
Esempio n. 44
0
    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 self._cells.values()]

        return Bbox.union(boxes)
Esempio n. 45
0
class Figure(Artist):

    def __init__(self,
                 figsize   = None,  # defaults to rc figure.figsize
                 dpi       = None,  # defaults to rc figure.dpi
                 facecolor = None,  # defaults to rc figure.facecolor
                 edgecolor = None,  # defaults to rc figure.edgecolor
                 linewidth = 1.0,   # the default linewidth of the frame
                 frameon = True,    # whether or not to draw the figure frame
                 subplotpars = None, # default to rc
                 ):
        """
        figsize is a w,h tuple in inches
        dpi is dots per inch
        subplotpars is a SubplotParams instance, defaults to rc
        """
        Artist.__init__(self)
        #self.set_figure(self)
        self._axstack = Stack()  # maintain the current axes
        self._axobservers = []
        self._seen = {}          # axes args we've seen

        if figsize is None  : figsize   = rcParams['figure.figsize']
        if dpi is None      : dpi       = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self._unit_conversions = {}

        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point( Value(0), Value(0) )
        self.ur = Point( self.figwidth*self.dpi,
                         self.figheight*self.dpi )
        self.bbox = Bbox(self.ll, self.ur)

        self.frameon = frameon

        self.transFigure = get_bbox_transform( unit_bbox(), self.bbox)



        self.figurePatch = Rectangle(
            xy=(0,0), width=1, height=1,
            facecolor=facecolor, edgecolor=edgecolor,
            linewidth=linewidth,
            )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.canvas = None

        if subplotpars is None:
            subplotpars = SubplotParams()

        self.subplotpars = subplotpars

        self.clf()

        self._cachedRenderer = None

    def get_window_extent(self, *args, **kwargs):
        'get the figure bounding box in display space'
        return self.bbox

    def set_canvas(self, canvas):
        """
        Set the canvas the contains the figure

        ACCEPTS: a FigureCanvas instance
        """
        self.canvas = canvas

    def _get_unit_conversion(self, python_type):
        """
        Get a unit conversion corresponding to a python type
        """
        maps = [self._unit_conversions, Figure._default_unit_conversions]

        for m in maps:
            classes = [python_type]
            for current in classes:
                if (current in m):
                    # found it!
                    #print 'Found unit conversion for %s!' % (`python_type`)
                    return m[current]
        return None 

    def register_unit_conversion(self, python_type, conversion):
        """
        Register a unit conversion class

        ACCEPTS: a Unit instance
        """
        self._unit_conversions[python_type] = conversion

    def unregister_unit_conversion(self, python_type):
        """
        Unregister a unit conversion class

        ACCEPTS: any Python type
        """
        self._unit_conversions.remove(python_type)
    
    def _register_default_unit_conversion(python_type, conversion):
        """
        Register a unit conversion class

        ACCEPTS: a Unit instance
        """
        Figure._default_unit_conversions[python_type] = conversion

    _default_unit_conversions = {}
    register_default_unit_conversion = \
        staticmethod(_register_default_unit_conversion)
 
    def _unregister_default_unit_conversion(python_type):
        """
        Unregister a unit conversion class

        ACCEPTS: any Python type
        """
        Figure._default_unit_conversions.remove(python_type)

    unregister_default_unit_conversion = \
        staticmethod(_unregister_default_unit_conversion)

    def hold(self, b=None):
        """
        Set the hold state.  If hold is None (default), toggle the
        hold state.  Else set the hold state to boolean value b.

        Eg
        hold()      # toggle hold
        hold(True)  # hold is on
        hold(False) # hold is off
        """
        if b is None: self._hold = not self._hold
        else: self._hold = b

    def figimage(self, X,
                 xo=0,
                 yo=0,
                 alpha=1.0,
                 norm=None,
                 cmap=None,
                 vmin=None,
                 vmax=None,
                 origin=None):
        """
        FIGIMAGE(X) # add non-resampled array to figure

        FIGIMAGE(X, xo, yo) # with pixel offsets

        FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc

        Add a nonresampled figure to the figure from array X.  xo and yo are
        offsets in pixels

        X must be a float array

            If X is MxN, assume luminance (grayscale)
            If X is MxNx3, assume RGB
            If X is MxNx4, assume RGBA

        The following kwargs are allowed:

          * cmap is a cm colormap instance, eg cm.jet.  If None, default to
            the rc image.cmap valuex

          * norm is a matplotlib.colors.normalize instance; default is
            normalization().  This scales luminance -> 0-1

          * vmin and vmax are used to scale a luminance image to 0-1.  If
            either is None, the min and max of the luminance values will be
            used.  Note if you pass a norm instance, the settings for vmin and
            vmax will be ignored.

          * alpha = 1.0 : the alpha blending value

          * origin is either 'upper' or 'lower', which indicates where the [0,0]
            index of the array is in the upper left or lower left corner of
            the axes.  Defaults to the rc image.origin value

        This complements the axes image (Axes.imshow) which will be resampled
        to fit the current axes.  If you want a resampled image to fill the
        entire figure, you can define an Axes with size [0,1,0,1].

        A image.FigureImage instance is returned.
        """

        if not self._hold: self.clf()

        im = FigureImage(self, cmap, norm, xo, yo, origin)
        im.set_array(X)
        im.set_alpha(alpha)
        if norm is None:
            im.set_clim(vmin, vmax)
        self.images.append(im)
        return im

    def set_figsize_inches(self, *args, **kwargs):
        import warnings
        warnings.warn('Use set_size_inches instead!', DeprecationWarning)
        self.set_size_inches(*args, **kwargs)

    def set_size_inches(self, *args, **kwargs):
        """
        set_size_inches(w,h, forward=False)

        Set the figure size in inches

        Usage: set_size_inches(self, w,h)  OR
               set_size_inches(self, (w,h) )

        optional kwarg forward=True will cause the canvas size to be
        automatically updated; eg you can resize the figure window
        from the shell

        WARNING: forward=True is broken on all backends except GTK*

        ACCEPTS: a w,h tuple with w,h in inches
        """

        forward = kwargs.get('forward', False)
        if len(args)==1:
            w,h = args[0]
        else:
            w,h = args
        self.figwidth.set(w)
        self.figheight.set(h)

        if forward:
            dpival = self.dpi.get()
            canvasw = w*dpival
            canvash = h*dpival
            manager = getattr(self.canvas, 'manager', None)
            if manager is not None:
                manager.resize(int(canvasw), int(canvash))

    def get_size_inches(self):
        return self.figwidth.get(), self.figheight.get()

    def get_edgecolor(self):
        'Get the edge color of the Figure rectangle'
        return self.figurePatch.get_edgecolor()

    def get_facecolor(self):
        'Get the face color of the Figure rectangle'
        return self.figurePatch.get_facecolor()

    def get_figwidth(self):
        'Return the figwidth as a float'
        return self.figwidth.get()

    def get_figheight(self):
        'Return the figheight as a float'
        return self.figheight.get()

    def get_dpi(self):
        'Return the dpi as a float'
        return self.dpi.get()

    def get_frameon(self):
        'get the boolean indicating frameon'
        return self.frameon

    def set_edgecolor(self, color):
        """
        Set the edge color of the Figure rectangle

        ACCEPTS: any matplotlib color - see help(colors)
        """
        self.figurePatch.set_edgecolor(color)

    def set_facecolor(self, color):
        """
        Set the face color of the Figure rectangle

        ACCEPTS: any matplotlib color - see help(colors)
        """
        self.figurePatch.set_facecolor(color)

    def set_dpi(self, val):
        """
        Set the dots-per-inch of the figure

        ACCEPTS: float
        """
        self.dpi.set(val)

    def set_figwidth(self, val):
        """
        Set the width of the figure in inches

        ACCEPTS: float
        """
        self.figwidth.set(val)

    def set_figheight(self, val):
        """
        Set the height of the figure in inches

        ACCEPTS: float
        """
        self.figheight.set(val)

    def set_frameon(self, b):
        """
        Set whether the figure frame (background) is displayed or invisible

        ACCEPTS: boolean
        """
        self.frameon = b

    def delaxes(self, a):
        'remove a from the figure and update the current axes'
        self.axes.remove(a)
        self._axstack.remove(a)
        keys = []
        for key, thisax in self._seen.items():
            if a==thisax: del self._seen[key]
        for func in self._axobservers: func(self)



    def _make_key(self, *args, **kwargs):
        'make a hashable key out of args and kwargs'

        def fixitems(items):
            #items may have arrays and lists in them, so convert them
            # to tuples for the key
            ret = []
            for k, v in items:
                if iterable(v): v = tuple(v)
                ret.append((k,v))
            return tuple(ret)

        def fixlist(args):
            ret = []
            for a in args:
                if iterable(a): a = tuple(a)
                ret.append(a)
            return tuple(ret)

        key = fixlist(args), fixitems(kwargs.items())
        return key

    def add_axes(self, *args, **kwargs):
        """
        Add an a axes with axes rect [left, bottom, width, height] where all
        quantities are in fractions of figure width and height.  kwargs are
        legal Axes kwargs plus "polar" which sets whether to create a polar axes

            rect = l,b,w,h
            add_axes(rect)
            add_axes(rect, frameon=False, axisbg='g')
            add_axes(rect, polar=True)
            add_axes(ax)   # add an Axes instance


        If the figure already has an axes with key *args, *kwargs then it will
        simply make that axes current and return it.  If you do not want this
        behavior, eg you want to force the creation of a new axes, you must
        use a unique set of args and kwargs.  The artist "label" attribute has
        been exposed for this purpose.  Eg, if you want two axes that are
        otherwise identical to be added to the figure, make sure you give them
        unique labels:

            add_axes(rect, label='axes1')
            add_axes(rect, label='axes2')

        The Axes instance will be returned
        """

        key = self._make_key(*args, **kwargs)

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return
        if isinstance(args[0], Axes):
            a = args[0]
            assert(a.get_figure() is self)            
        else:
            rect = args[0]
            ispolar = popd(kwargs, 'polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)


        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    def add_subplot(self, *args, **kwargs):
        """
        Add a subplot.  Examples

            add_subplot(111)
            add_subplot(212, axisbg='r')  # add subplot with red background
            add_subplot(111, polar=True)  # add a polar subplot
            add_subplot(sub)              # add Subplot instance sub

        kwargs are legal Axes kwargs plus"polar" which sets whether to create a
        polar axes.  The Axes instance will be returned.

        If the figure already has a subplot with key *args, *kwargs then it will
        simply make that subplot current and return it
        """

        key = self._make_key(*args, **kwargs)
        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax


        if not len(args): return

        if isinstance(args[0], Subplot) or isinstance(args[0], PolarSubplot):
            a = args[0]
            assert(a.get_figure() is self)
        else:
            ispolar = popd(kwargs, 'polar', False)
            if ispolar:
                a = PolarSubplot(self, *args, **kwargs)
            else:
                a = Subplot(self, *args, **kwargs)


        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    def clf(self):
        """
        Clear the figure
        """
        self.axes = []
        self._axstack.clear()
        self._seen = {}
        self.lines = []
        self.patches = []
        self.texts=[]
        self.images = []
        self.legends = []

    def clear(self):
        """
        Clear the figure
        """
        self.clf()

    def draw(self, renderer):
        """
        Render the figure using Renderer instance renderer
        """
        # draw the figure bounding box, perhaps none for white figure
        #print 'figure draw'
        if not self.get_visible(): return
        renderer.open_group('figure')
        self.transFigure.freeze()  # eval the lazy objects

        if self.frameon: self.figurePatch.draw(renderer)

        for p in self.patches: p.draw(renderer)
        for l in self.lines: l.draw(renderer)

        if len(self.images)==1:
            im = self.images[0]
            im.draw(renderer)
        elif len(self.images)>1:
            # make a composite image blending alpha
            # list of (_image.Image, ox, oy)
            if not allequal([im.origin for im in self.images]):
                raise ValueError('Composite images with different origins not supported')
            ims = [(im.make_image(), im.ox, im.oy) for im in self.images]
            im = _image.from_images(self.bbox.height(), self.bbox.width(), ims)
            im.is_grayscale = False
            l, b, w, h = self.bbox.get_bounds()
            renderer.draw_image(0, 0, im, self.bbox)


        # render the axes
        for a in self.axes: a.draw(renderer)

        # render the figure text
        for t in self.texts: t.draw(renderer)

        for legend in self.legends:
            legend.draw(renderer)

        self.transFigure.thaw()  # release the lazy objects
        renderer.close_group('figure')

        self._cachedRenderer = renderer

        self.canvas.draw_event(renderer)

    def draw_artist(self, a):
        'draw artist only -- this is available only after the figure is drawn'
        assert self._cachedRenderer is not None
        a.draw(self._cachedRenderer)

    def get_axes(self):
        return self.axes

    def legend(self, handles, labels, loc, **kwargs):
        """
        Place a legend in the figure.  Labels are a sequence of
        strings, handles is a sequence of line or patch instances, and
        loc can be a string or an integer specifying the legend
        location

        USAGE:
          legend( (line1, line2, line3),
                  ('label1', 'label2', 'label3'),
                  'upper right')

        The LOC location codes are

          'best' : 0,          (currently not supported, defaults to upper right)
          'upper right'  : 1,  (default)
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,

        loc can also be an (x,y) tuple in figure coords, which
        specifies the lower left of the legend box.  figure coords are
        (0,0) is the left, bottom of the figure and 1,1 is the right,
        top.

        The legend instance is returned
        """


        handles = flatten(handles)
        l = Legend(self, handles, labels, loc, isaxes=False, **kwargs)
        self._set_artist_props(l)
        self.legends.append(l)
        return l

    def text(self, x, y, s, *args, **kwargs):
        """
        Add text to figure at location x,y (relative 0-1 coords) See
        the help for Axis text for the meaning of the other arguments
        """

        override = _process_text_args({}, *args, **kwargs)
        t = Text(
            x=x, y=y, text=s,
            )

        t.update(override)
        self._set_artist_props(t)
        self.texts.append(t)
        return t

    def _set_artist_props(self, a):
        if a!= self:
            a.set_figure(self)
        a.set_transform(self.transFigure)

    def gca(self, **kwargs):
        """
        Return the current axes, creating one if necessary
        """
        ax = self._axstack()
        if ax is not None: return ax
        return self.add_subplot(111, **kwargs)

    def sca(self, a):
        'Set the current axes to be a and return a'
        self._axstack.bubble(a)
        for func in self._axobservers: func(self)
        return a

    def add_axobserver(self, func):
        'whenever the axes state change, func(self) will be called'
        self._axobservers.append(func)


    def savefig(self, *args, **kwargs):
        """
        SAVEFIG(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None):

        Save the current figure.

        fname - the filename to save the current figure to.  The
                output formats supported depend on the backend being
                used.  and are deduced by the extension to fname.
                Possibilities are eps, jpeg, pdf, png, ps, svg.  fname
                can also be a file or file-like object - cairo backend
                only.  dpi - is the resolution in dots per inch.  If
                None it will default to the value savefig.dpi in the
                matplotlibrc file

        facecolor and edgecolor are the colors of the figure rectangle

        orientation is either 'landscape' or 'portrait' - not supported on
        all backends; currently only on postscript output

        papertype is is one of 'letter', 'legal', 'executive', 'ledger', 'a0'
        through 'a10', or 'b0' through 'b10' - only supported for postscript
        output

        format - one of 'pdf', 'png', 'ps', 'svg'. It is used to specify the
                 output when fname is a file or file-like object - cairo
                 backend only.
        """

        for key in ('dpi', 'facecolor', 'edgecolor'):
            if not kwargs.has_key(key):
                kwargs[key] = rcParams['savefig.%s'%key]

        self.canvas.print_figure(*args, **kwargs)

    def colorbar(self, mappable, cax=None, **kw):
        # Temporary compatibility code:
        old = ('tickfmt', 'cspacing', 'clabels', 'edgewidth', 'edgecolor')
        oldkw = [k for k in old if kw.has_key(k)]
        if oldkw:
            msg = 'Old colorbar kwargs (%s) found; using colorbar_classic.' % (','.join(oldkw),)
            warnings.warn(msg, DeprecationWarning)
            self.colorbar_classic(mappable, cax, **kw)
            return cax
        # End of compatibility code block.
        orientation = kw.get('orientation', 'vertical')
        ax = self.gca()
        if cax is None:
            cax, kw = cbar.make_axes(ax, **kw)
        cb = cbar.Colorbar(cax, mappable, **kw)
        mappable.add_observer(cb)
        mappable.set_colorbar(cb, cax)
        self.sca(ax)
        return cb
    colorbar.__doc__ =  '''
        Create a colorbar for a ScalarMappable instance.

        Documentation for the pylab thin wrapper: %s
        '''% cbar.colorbar_doc

    def colorbar_classic(self, mappable,  cax=None,
                    orientation='vertical', tickfmt='%1.1f',
                    cspacing='proportional',
                    clabels=None, drawedges=False, edgewidth=0.5,
                    edgecolor='k'):
        """
        Create a colorbar for mappable image

        mappable is the cm.ScalarMappable instance that you want the
        colorbar to apply to, e.g. an Image as returned by imshow or a
        PatchCollection as returned by scatter or pcolor.

        tickfmt is a format string to format the colorbar ticks

        cax is a colorbar axes instance in which the colorbar will be
        placed.  If None, as default axesd will be created resizing the
        current aqxes to make room for it.  If not None, the supplied axes
        will be used and the other axes positions will be unchanged.

        orientation is the colorbar orientation: one of 'vertical' | 'horizontal'

        cspacing controls how colors are distributed on the colorbar.
        if cspacing == 'linear', each color occupies an equal area
        on the colorbar, regardless of the contour spacing.
        if cspacing == 'proportional' (Default), the area each color
        occupies on the the colorbar is proportional to the contour interval.
        Only relevant for a Contour image.

        clabels can be a sequence containing the
        contour levels to be labelled on the colorbar, or None (Default).
        If clabels is None, labels for all contour intervals are
        displayed. Only relevant for a Contour image.

        if drawedges == True, lines are drawn at the edges between
        each color on the colorbar. Default False.

        edgecolor is the line color delimiting the edges of the colors
        on the colorbar (if drawedges == True). Default black ('k')

        edgewidth is the width of the lines delimiting the edges of
        the colors on the colorbar (if drawedges == True). Default 0.5

        return value is the colorbar axes instance
        """

        if orientation not in ('horizontal', 'vertical'):
            raise ValueError('Orientation must be horizontal or vertical')

        if isinstance(mappable, FigureImage) and cax is None:
            raise TypeError('Colorbars for figure images currently not supported unless you provide a colorbar axes in cax')


        ax = self.gca()

        cmap = mappable.cmap

        if cax is None:
            l,b,w,h = ax.get_position()
            if orientation=='vertical':
                neww = 0.8*w
                ax.set_position((l,b,neww,h), 'both')
                cax = self.add_axes([l + 0.9*w, b, 0.1*w, h])
            else:
                newh = 0.8*h
                ax.set_position((l,b+0.2*h,w,newh), 'both')
                cax = self.add_axes([l, b, w, 0.1*h])

        else:
            if not isinstance(cax, Axes):
                raise TypeError('Expected an Axes instance for cax')

        norm = mappable.norm
        if norm.vmin is None or norm.vmax is None:
            mappable.autoscale()
        cmin = norm.vmin
        cmax = norm.vmax
        if isinstance(mappable, ContourSet):
        # mappable image is from contour or contourf
            clevs = mappable.levels
            clevs = minimum(clevs, cmax)
            clevs = maximum(clevs, cmin)
            isContourSet = True
        elif isinstance(mappable, ScalarMappable):
        # from imshow or pcolor.
            isContourSet = False
            clevs = linspace(cmin, cmax, cmap.N+1) # boundaries, hence N+1
        else:
            raise TypeError("don't know how to handle type %s"%type(mappable))

        N = len(clevs)
        C = array([clevs, clevs])
        if cspacing == 'linear':
            X, Y = meshgrid(clevs, [0, 1])
        elif cspacing == 'proportional':
            X, Y = meshgrid(linspace(cmin, cmax, N), [0, 1])
        else:
            raise ValueError("cspacing must be 'linear' or 'proportional'")

        if orientation=='vertical':
            args = (transpose(Y), transpose(C), transpose(X), clevs)
        else:
            args = (C, Y, X, clevs)
        #If colors were listed in the original mappable, then
        # let contour handle them the same way.
        colors = getattr(mappable, 'colors', None)
        if colors is not None:
            kw = {'colors': colors}
        else:
            kw = {'cmap':cmap, 'norm':norm}
        if isContourSet and not mappable.filled:
            CS = cax.contour(*args, **kw)
            colls = mappable.collections
            for ii in range(len(colls)):
                CS.collections[ii].set_linewidth(colls[ii].get_linewidth())
        else:
            kw['antialiased'] = False
            CS = cax.contourf(*args, **kw)
        if drawedges:
            for col in CS.collections:
                col.set_edgecolor(edgecolor)
                col.set_linewidth(edgewidth)

        mappable.add_observer(CS)
        mappable.set_colorbar(CS, cax)


        if isContourSet:
            if cspacing == 'linear':
                ticks = linspace(cmin, cmax, N)
            else:
                ticks = clevs
            if cmin == mappable.levels[0]:
                ticklevs = clevs
            else: # We are not showing the full ends of the range.
                ticks = ticks[1:-1]
                ticklevs = clevs[1:-1]
            labs = [tickfmt % lev for lev in ticklevs]
            if clabels is not None:
                for i, lev in enumerate(ticklevs):
                    if lev not in clabels:
                        labs[i] = ''


        if orientation=='vertical':
            cax.set_xticks([])
            cax.yaxis.tick_right()
            cax.yaxis.set_label_position('right')
            if isContourSet:
                cax.set_yticks(ticks)
                cax.set_yticklabels(labs)
            else:
                cax.yaxis.set_major_formatter(FormatStrFormatter(tickfmt))
        else:
            cax.set_yticks([])
            if isContourSet:
                cax.set_xticks(ticks)
                cax.set_xticklabels(labs)
            else:
                cax.xaxis.set_major_formatter(FormatStrFormatter(tickfmt))

        self.sca(ax)
        return cax


    def subplots_adjust(self, *args, **kwargs):
        """
        fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None):
        Update the SubplotParams with kwargs (defaulting to rc where
        None) and update the subplot locations
        """
        self.subplotpars.update(*args, **kwargs)
        import matplotlib.axes
        for ax in self.axes:
            if not isinstance(ax, matplotlib.axes.Subplot):
                # Check if sharing a subplots axis
                if ax._sharex is not None and isinstance(ax._sharex, matplotlib.axes.Subplot):
                    ax._sharex.update_params()
                    ax.set_position([ax._sharex.figLeft, ax._sharex.figBottom, ax._sharex.figW, ax._sharex.figH])
                elif ax._sharey is not None and isinstance(ax._sharey, matplotlib.axes.Subplot):
                    ax._sharey.update_params()
                    ax.set_position([ax._sharey.figLeft, ax._sharey.figBottom, ax._sharey.figW, ax._sharey.figH])
            else:
                ax.update_params()
                ax.set_position([ax.figLeft, ax.figBottom, ax.figW, ax.figH])
Esempio n. 46
0
class Figure(Artist):
    def __init__(
        self,
        figsize=None,  # defaults to rc figure.figsize
        dpi=None,  # defaults to rc figure.dpi
        facecolor=None,  # defaults to rc figure.facecolor
        edgecolor=None,  # defaults to rc figure.edgecolor
        linewidth=1.0,  # the default linewidth of the frame
        frameon=True,
    ):
        """
        paper size is a w,h tuple in inches
        DPI is dots per inch 
        """
        Artist.__init__(self)
        #self.set_figure(self)
        self._axstack = Stack()  # maintain the current axes
        self._axobservers = []
        self._seen = {}  # axes args we've seen

        if figsize is None: figsize = rcParams['figure.figsize']
        if dpi is None: dpi = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point(Value(0), Value(0))
        self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi)
        self.bbox = Bbox(self.ll, self.ur)
        self.frameon = frameon

        self.transFigure = get_bbox_transform(unit_bbox(), self.bbox)

        self.figurePatch = Rectangle(
            xy=(0, 0),
            width=1,
            height=1,
            facecolor=facecolor,
            edgecolor=edgecolor,
            linewidth=linewidth,
        )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.clf()

    def hold(self, b=None):
        """
        Set the hold state.  If hold is None (default), toggle the
        hold state.  Else set the hold state to boolean value b.

        Eg
        hold()      # toggle hold
        hold(True)  # hold is on
        hold(False) # hold is off
        """
        if b is None: self._hold = not self._hold
        else: self._hold = b

    def figimage(self,
                 X,
                 xo=0,
                 yo=0,
                 alpha=1.0,
                 norm=None,
                 cmap=None,
                 vmin=None,
                 vmax=None,
                 origin=None):
        """\
FIGIMAGE(X) # add non-resampled array to figure

FIGIMAGE(X, xo, yo) # with pixel offsets

FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc

Add a nonresampled figure to the figure from array X.  xo and yo are
offsets in pixels

X must be a float array

    If X is MxN, assume luminance (grayscale)
    If X is MxNx3, assume RGB
    If X is MxNx4, assume RGBA

The following kwargs are allowed: 

  * cmap is a cm colormap instance, eg cm.jet.  If None, default to
    the rc image.cmap valuex

  * norm is a matplotlib.colors.normalize instance; default is
    normalization().  This scales luminance -> 0-1

  * vmin and vmax are used to scale a luminance image to 0-1.  If
    either is None, the min and max of the luminance values will be
    used.  Note if you pass a norm instance, the settings for vmin and
    vmax will be ignored.

  * alpha = 1.0 : the alpha blending value

  * origin is either 'upper' or 'lower', which indicates where the [0,0]
    index of the array is in the upper left or lower left corner of
    the axes.  Defaults to the rc image.origin value

This complements the axes image which will be resampled to fit the
current axes.  If you want a resampled image to fill the entire
figure, you can define an Axes with size [0,1,0,1].

A image.FigureImage instance is returned.
"""

        if not self._hold: self.clf()

        im = FigureImage(self, cmap, norm, xo, yo, origin)
        im.set_array(X)
        im.set_alpha(alpha)
        if norm is None:
            im.set_clim(vmin, vmax)
        self.images.append(im)
        return im

    def set_figsize_inches(self, *args):
        """
Set the figure size in inches

Usage: set_figsize_inches(self, w,h)  OR
       set_figsize_inches(self, (w,h) )

ACCEPTS: a w,h tuple with w,h in inches
"""
        if len(args) == 1:
            w, h = args[0]
        else:
            w, h = args
        self.figwidth.set(w)
        self.figheight.set(h)

    def get_size_inches(self):
        return self.figwidth.get(), self.figheight.get()

    def get_edgecolor(self):
        'Get the edge color of the Figure rectangle'
        return self.figurePatch.get_edgecolor()

    def get_facecolor(self):
        'Get the face color of the Figure rectangle'
        return self.figurePatch.get_facecolor()

    def set_edgecolor(self, color):
        """
Set the edge color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)"""
        self.figurePatch.set_edgecolor(color)

    def set_facecolor(self, color):
        """
Set the face color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)"""
        self.figurePatch.set_facecolor(color)

    def delaxes(self, a):
        'remove a from the figure and update the current axes'
        self.axes.remove(a)
        self._axstack.remove(a)
        keys = []
        for key, thisax in self._seen.items():
            if a == thisax: del self._seen[key]
        for func in self._axobservers:
            func(self)

    def add_axes(self, *args, **kwargs):
        """
Add an a axes with axes rect [left, bottom, width, height] where all
quantities are in fractions of figure width and height.  kwargs are
legal Axes kwargs plus"polar" which sets whether to create a polar axes

    add_axes((l,b,w,h))
    add_axes((l,b,w,h), frameon=False, axisbg='g')
    add_axes((l,b,w,h), polar=True)
    add_axes(ax)   # add an Axes instance


If the figure already has an axed with key *args, *kwargs then it
will simply make that axes current and return it

The Axes instance will be returned
        """

        if iterable(args[0]):
            key = tuple(args[0]), tuple(kwargs.items())
        else:
            key = args[0], tuple(kwargs.items())

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return
        if isinstance(args[0], Axes):
            a = args[0]
            a.set_figure(self)
        else:
            rect = args[0]
            ispolar = popd(kwargs, 'polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    def add_subplot(self, *args, **kwargs):
        """
Add an a subplot.  Examples

    add_subplot(111)
    add_subplot(212, axisbg='r')  # add subplot with red background
    add_subplot(111, polar=True)  # add a polar subplot
    add_subplot(sub)              # add Subplot instance sub
        
kwargs are legal Axes kwargs plus"polar" which sets whether to create a
polar axes.  The Axes instance will be returned.

If the figure already has a subplot with key *args, *kwargs then it will
simply make that subplot current and return it
        """

        key = args, tuple(kwargs.items())
        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return

        if isinstance(args[0], Subplot) or isinstance(args, PolarSubplot):
            a = args[0]
            a.set_figure(self)
        else:
            ispolar = popd(kwargs, 'polar', False)
            if ispolar:
                a = PolarSubplot(self, *args, **kwargs)
            else:
                a = Subplot(self, *args, **kwargs)

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    def clf(self):
        """
        Clear the figure
        """
        self.axes = []
        self._axstack.clear()
        self._seen = {}
        self.lines = []
        self.patches = []
        self.texts = []
        self.images = []
        self.legends = []

    def clear(self):
        """
        Clear the figure
        """
        self.clf()

    def draw(self, renderer):
        """
        Render the figure using RendererGD instance renderer
        """
        # draw the figure bounding box, perhaps none for white figure
        #print 'figure draw'
        if not self.get_visible(): return
        renderer.open_group('figure')
        self.transFigure.freeze()  # eval the lazy objects
        if self.frameon: self.figurePatch.draw(renderer)

        for p in self.patches:
            p.draw(renderer)
        for l in self.lines:
            l.draw(renderer)

        if len(self.images) == 1:
            im = self.images[0]
            im.draw(renderer)
        elif len(self.images) > 1:
            # make a composite image blending alpha
            # list of (_image.Image, ox, oy)
            if not allequal([im.origin for im in self.images]):
                raise ValueError(
                    'Composite images with different origins not supported')
            else:
                origin = self.images[0].origin

            ims = [(im.make_image(), im.ox, im.oy) for im in self.images]
            im = _image.from_images(self.bbox.height(), self.bbox.width(), ims)
            im.is_grayscale = False
            l, b, w, h = self.bbox.get_bounds()
            renderer.draw_image(0, 0, im, origin, self.bbox)

        # render the axes
        for a in self.axes:
            a.draw(renderer)

        # render the figure text
        for t in self.texts:
            t.draw(renderer)

        for legend in self.legends:
            legend.draw(renderer)

        self.transFigure.thaw()  # release the lazy objects
        renderer.close_group('figure')

    def get_axes(self):
        return self.axes

    def legend(self, handles, labels, loc, **kwargs):
        """
        Place a legend in the figure.  Labels are a sequence of
        strings, handles is a sequence of line or patch instances, and
        loc can be a string or an integer specifying the legend
        location

        USAGE: 
          legend( (line1, line2, line3),
                  ('label1', 'label2', 'label3'),
                  'upper right')

        The LOC location codes are

          'best' : 0,          (currently not supported, defaults to upper right)
          'upper right'  : 1,  (default)
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,

        The legend instance is returned
        """

        handles = flatten(handles)
        l = Legend(self, handles, labels, loc, isaxes=False, **kwargs)
        self._set_artist_props(l)
        self.legends.append(l)
        return l

    def text(self, x, y, s, *args, **kwargs):
        """
        Add text to figure at location x,y (relative 0-1 coords) See
        the help for Axis text for the meaning of the other arguments
        """

        override = _process_text_args({}, *args, **kwargs)
        t = Text(
            x=x,
            y=y,
            text=s,
        )

        t.update(override)
        self._set_artist_props(t)
        self.texts.append(t)
        return t

    def _set_artist_props(self, a):
        if a != self:
            a.set_figure(self)
        a.set_transform(self.transFigure)

    def get_width_height(self):
        'return the figure width and height in pixels'
        w = self.bbox.width()
        h = self.bbox.height()
        return w, h

    def gca(self, **kwargs):
        """
Return the current axes, creating one if necessary
        """
        ax = self._axstack()
        if ax is not None: return ax
        return self.add_subplot(111, **kwargs)

    def sca(self, a):
        'Set the current axes to be a and return a'
        self._axstack.bubble(a)
        for func in self._axobservers:
            func(self)
        return a

    def add_axobserver(self, func):
        'whenever the axes state change, func(self) will be called'
        self._axobservers.append(func)
Esempio n. 47
0
    def _get_layout(self, renderer):
        key = self.get_prop_tup()
        if self.cached.has_key(key): return self.cached[key]

        horizLayout = []

        thisx, thisy = 0.0, 0.0
        xmin, ymin = 0.0, 0.0
        width, height = 0.0, 0.0
        lines = self._text.split('\n')

        whs = np.zeros((len(lines), 2))
        horizLayout = np.zeros((len(lines), 4))

        # Find full vertical extent of font,
        # including ascenders and descenders:
        tmp, heightt, bl = renderer.get_text_width_height_descent(
            'lp', self._fontproperties, ismath=False)
        offsety = heightt * self._linespacing

        baseline = None
        for i, line in enumerate(lines):
            w, h, d = renderer.get_text_width_height_descent(
                line, self._fontproperties, ismath=self.is_math_text(line))
            if baseline is None:
                baseline = h - d
            whs[i] = w, h
            horizLayout[i] = thisx, thisy, w, h
            thisy -= offsety
            width = max(width, w)

        ymin = horizLayout[-1][1]
        ymax = horizLayout[0][1] + horizLayout[0][3]
        height = ymax - ymin
        xmax = xmin + width

        # get the rotation matrix
        M = Affine2D().rotate_deg(self.get_rotation())

        offsetLayout = np.zeros((len(lines), 2))
        offsetLayout[:] = horizLayout[:, 0:2]
        # now offset the individual text lines within the box
        if len(lines) > 1:  # do the multiline aligment
            malign = self._get_multialignment()
            if malign == 'center':
                offsetLayout[:, 0] += width / 2.0 - horizLayout[:, 2] / 2.0
            elif malign == 'right':
                offsetLayout[:, 0] += width - horizLayout[:, 2]

        # the corners of the unrotated bounding box
        cornersHoriz = np.array([(xmin, ymin), (xmin, ymax), (xmax, ymax),
                                 (xmax, ymin)], np.float_)
        # now rotate the bbox
        cornersRotated = M.transform(cornersHoriz)

        txs = cornersRotated[:, 0]
        tys = cornersRotated[:, 1]

        # compute the bounds of the rotated box
        xmin, xmax = txs.min(), txs.max()
        ymin, ymax = tys.min(), tys.max()
        width = xmax - xmin
        height = ymax - ymin

        # Now move the box to the targe position offset the display bbox by alignment
        halign = self._horizontalalignment
        valign = self._verticalalignment

        # compute the text location in display coords and the offsets
        # necessary to align the bbox with that location
        if halign == 'center': offsetx = (xmin + width / 2.0)
        elif halign == 'right': offsetx = (xmin + width)
        else: offsetx = xmin

        if valign == 'center': offsety = (ymin + height / 2.0)
        elif valign == 'top': offsety = (ymin + height)
        elif valign == 'baseline': offsety = (ymin + height) + baseline
        else: offsety = ymin

        xmin -= offsetx
        ymin -= offsety

        bbox = Bbox.from_bounds(xmin, ymin, width, height)

        # now rotate the positions around the first x,y position
        xys = M.transform(offsetLayout)
        xys -= (offsetx, offsety)

        xs, ys = xys[:, 0], xys[:, 1]

        ret = bbox, zip(lines, whs, xs, ys)
        self.cached[key] = ret
        return ret
Esempio n. 48
0
class Figure(Artist):

    def __str__(self):
        return "Figure(%gx%g)"%(self.figwidth.get(),self.figheight.get())

    def __init__(self,
                 figsize   = None,  # defaults to rc figure.figsize
                 dpi       = None,  # defaults to rc figure.dpi
                 facecolor = None,  # defaults to rc figure.facecolor
                 edgecolor = None,  # defaults to rc figure.edgecolor
                 linewidth = 1.0,   # the default linewidth of the frame
                 frameon = True,    # whether or not to draw the figure frame
                 subplotpars = None, # default to rc
                 ):
        """
        figsize is a w,h tuple in inches
        dpi is dots per inch
        subplotpars is a SubplotParams instance, defaults to rc
        """
        Artist.__init__(self)

        if figsize is None  : figsize   = rcParams['figure.figsize']
        if dpi is None      : dpi       = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point( Value(0), Value(0) )
        self.ur = Point( self.figwidth*self.dpi,
                         self.figheight*self.dpi )
        self.bbox = Bbox(self.ll, self.ur)

        self.frameon = frameon

        self.transFigure = get_bbox_transform( unit_bbox(), self.bbox)



        self.figurePatch = Rectangle(
            xy=(0,0), width=1, height=1,
            facecolor=facecolor, edgecolor=edgecolor,
            linewidth=linewidth,
            )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.canvas = None

        if subplotpars is None:
            subplotpars = SubplotParams()

        self.subplotpars = subplotpars

        self._axstack = Stack()  # maintain the current axes
        self.axes = []
        self.clf()

        self._cachedRenderer = None

    def autofmt_xdate(self, bottom=0.2, rotation=30, ha='right'):
        """
        A common use case is a number of subplots with shared xaxes
        where the x-axis is date data.  The ticklabels are often
        long,and it helps to rotate them on the bottom subplot and
        turn them off on other subplots.  This function will raise a
        RuntimeError if any of the Axes are not Subplots.

        bottom : the bottom of the subplots for subplots_adjust
        rotation: the rotation of the xtick labels
        ha : the horizontal alignment of the xticklabels


        """

        for ax in self.get_axes():
            if not hasattr(ax, 'is_last_row'):
                raise RuntimeError('Axes must be subplot instances; found %s'%type(ax))
            if ax.is_last_row():
                for label in ax.get_xticklabels():
                    label.set_ha(ha)
                    label.set_rotation(rotation)
            else:
                for label in ax.get_xticklabels():
                    label.set_visible(False)
        self.subplots_adjust(bottom=bottom)

    def get_children(self):
        'get a list of artists contained in the figure'
        children = [self.figurePatch]
        children.extend(self.axes)
        children.extend(self.lines)
        children.extend(self.patches)
        children.extend(self.texts)
        children.extend(self.images)
        children.extend(self.legends)
        return children

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

        Returns True,{}
        """
        if callable(self._contains): return self._contains(self,mouseevent)
        #inside = mouseevent.x >= 0 and mouseevent.y >= 0
        inside = self.bbox.contains(mouseevent.x,mouseevent.y)

        return inside,{}

    def get_window_extent(self, *args, **kwargs):
        'get the figure bounding box in display space; kwargs are void'
        return self.bbox

    def set_canvas(self, canvas):
        """
        Set the canvas the contains the figure

        ACCEPTS: a FigureCanvas instance
        """
        self.canvas = canvas

    def hold(self, b=None):
        """
        Set the hold state.  If hold is None (default), toggle the
        hold state.  Else set the hold state to boolean value b.

        Eg
        hold()      # toggle hold
        hold(True)  # hold is on
        hold(False) # hold is off
        """
        if b is None: self._hold = not self._hold
        else: self._hold = b

    def figimage(self, X,
                 xo=0,
                 yo=0,
                 alpha=1.0,
                 norm=None,
                 cmap=None,
                 vmin=None,
                 vmax=None,
                 origin=None):
        """
        FIGIMAGE(X) # add non-resampled array to figure

        FIGIMAGE(X, xo, yo) # with pixel offsets

        FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc

        Add a nonresampled figure to the figure from array X.  xo and yo are
        offsets in pixels

        X must be a float array

            If X is MxN, assume luminance (grayscale)
            If X is MxNx3, assume RGB
            If X is MxNx4, assume RGBA

        The following kwargs are allowed:

          * cmap is a cm colormap instance, eg cm.jet.  If None, default to
            the rc image.cmap valuex

          * norm is a matplotlib.colors.Normalize instance; default is
            normalization().  This scales luminance -> 0-1

          * vmin and vmax are used to scale a luminance image to 0-1.  If
            either is None, the min and max of the luminance values will be
            used.  Note if you pass a norm instance, the settings for vmin and
            vmax will be ignored.

          * alpha = 1.0 : the alpha blending value

          * origin is either 'upper' or 'lower', which indicates where the [0,0]
            index of the array is in the upper left or lower left corner of
            the axes.  Defaults to the rc image.origin value

        This complements the axes image (Axes.imshow) which will be resampled
        to fit the current axes.  If you want a resampled image to fill the
        entire figure, you can define an Axes with size [0,1,0,1].

        A image.FigureImage instance is returned.
        """

        if not self._hold: self.clf()

        im = FigureImage(self, cmap, norm, xo, yo, origin)
        im.set_array(X)
        im.set_alpha(alpha)
        if norm is None:
            im.set_clim(vmin, vmax)
        self.images.append(im)
        return im

    def set_figsize_inches(self, *args, **kwargs):
        import warnings
        warnings.warn('Use set_size_inches instead!', DeprecationWarning)
        self.set_size_inches(*args, **kwargs)

    def set_size_inches(self, *args, **kwargs):
        """
        set_size_inches(w,h, forward=False)

        Set the figure size in inches

        Usage: set_size_inches(self, w,h)  OR
               set_size_inches(self, (w,h) )

        optional kwarg forward=True will cause the canvas size to be
        automatically updated; eg you can resize the figure window
        from the shell

        WARNING: forward=True is broken on all backends except GTK*

        ACCEPTS: a w,h tuple with w,h in inches
        """

        forward = kwargs.get('forward', False)
        if len(args)==1:
            w,h = args[0]
        else:
            w,h = args
        self.figwidth.set(w)
        self.figheight.set(h)

        if forward:
            dpival = self.dpi.get()
            canvasw = w*dpival
            canvash = h*dpival
            manager = getattr(self.canvas, 'manager', None)
            if manager is not None:
                manager.resize(int(canvasw), int(canvash))

    def get_size_inches(self):
        return self.figwidth.get(), self.figheight.get()

    def get_edgecolor(self):
        'Get the edge color of the Figure rectangle'
        return self.figurePatch.get_edgecolor()

    def get_facecolor(self):
        'Get the face color of the Figure rectangle'
        return self.figurePatch.get_facecolor()

    def get_figwidth(self):
        'Return the figwidth as a float'
        return self.figwidth.get()

    def get_figheight(self):
        'Return the figheight as a float'
        return self.figheight.get()

    def get_dpi(self):
        'Return the dpi as a float'
        return self.dpi.get()

    def get_frameon(self):
        'get the boolean indicating frameon'
        return self.frameon

    def set_edgecolor(self, color):
        """
        Set the edge color of the Figure rectangle

        ACCEPTS: any matplotlib color - see help(colors)
        """
        self.figurePatch.set_edgecolor(color)

    def set_facecolor(self, color):
        """
        Set the face color of the Figure rectangle

        ACCEPTS: any matplotlib color - see help(colors)
        """
        self.figurePatch.set_facecolor(color)

    def set_dpi(self, val):
        """
        Set the dots-per-inch of the figure

        ACCEPTS: float
        """
        self.dpi.set(val)

    def set_figwidth(self, val):
        """
        Set the width of the figure in inches

        ACCEPTS: float
        """
        self.figwidth.set(val)

    def set_figheight(self, val):
        """
        Set the height of the figure in inches

        ACCEPTS: float
        """
        self.figheight.set(val)

    def set_frameon(self, b):
        """
        Set whether the figure frame (background) is displayed or invisible

        ACCEPTS: boolean
        """
        self.frameon = b

    def delaxes(self, a):
        'remove a from the figure and update the current axes'
        self.axes.remove(a)
        self._axstack.remove(a)
        keys = []
        for key, thisax in self._seen.items():
            if a==thisax: del self._seen[key]
        for func in self._axobservers: func(self)



    def _make_key(self, *args, **kwargs):
        'make a hashable key out of args and kwargs'

        def fixitems(items):
            #items may have arrays and lists in them, so convert them
            # to tuples for the key
            ret = []
            for k, v in items:
                if iterable(v): v = tuple(v)
                ret.append((k,v))
            return tuple(ret)

        def fixlist(args):
            ret = []
            for a in args:
                if iterable(a): a = tuple(a)
                ret.append(a)
            return tuple(ret)

        key = fixlist(args), fixitems(kwargs.items())
        return key

    def add_axes(self, *args, **kwargs):
        """
        Add an a axes with axes rect [left, bottom, width, height] where all
        quantities are in fractions of figure width and height.  kwargs are
        legal Axes kwargs plus "polar" which sets whether to create a polar axes

            rect = l,b,w,h
            add_axes(rect)
            add_axes(rect, frameon=False, axisbg='g')
            add_axes(rect, polar=True)
            add_axes(ax)   # add an Axes instance


        If the figure already has an axes with key *args, *kwargs then it will
        simply make that axes current and return it.  If you do not want this
        behavior, eg you want to force the creation of a new axes, you must
        use a unique set of args and kwargs.  The artist "label" attribute has
        been exposed for this purpose.  Eg, if you want two axes that are
        otherwise identical to be added to the figure, make sure you give them
        unique labels:

            add_axes(rect, label='axes1')
            add_axes(rect, label='axes2')

        The Axes instance will be returned

        The following kwargs are supported:
        %(Axes)s
        """

        key = self._make_key(*args, **kwargs)

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return
        if isinstance(args[0], Axes):
            a = args[0]
            assert(a.get_figure() is self)
        else:
            rect = args[0]
            ispolar = kwargs.pop('polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)


        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    add_axes.__doc__ = dedent(add_axes.__doc__) % artist.kwdocd

    def add_subplot(self, *args, **kwargs):
        """
        Add a subplot.  Examples

            add_subplot(111)
            add_subplot(212, axisbg='r')  # add subplot with red background
            add_subplot(111, polar=True)  # add a polar subplot
            add_subplot(sub)              # add Subplot instance sub

        kwargs are legal Axes kwargs plus"polar" which sets whether to create a
        polar axes.  The Axes instance will be returned.

        If the figure already has a subplot with key *args, *kwargs then it will
        simply make that subplot current and return it

        The following kwargs are supported:
        %(Axes)s
        """

        key = self._make_key(*args, **kwargs)
        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax


        if not len(args): return

        if isinstance(args[0], Subplot) or isinstance(args[0], PolarSubplot):
            a = args[0]
            assert(a.get_figure() is self)
        else:
            ispolar = kwargs.pop('polar', False)
            if ispolar:
                a = PolarSubplot(self, *args, **kwargs)
            else:
                a = Subplot(self, *args, **kwargs)


        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a
    add_subplot.__doc__ = dedent(add_subplot.__doc__) % artist.kwdocd

    def clf(self):
        """
        Clear the figure
        """
        for ax in tuple(self.axes):  # Iterate over the copy.
            ax.cla()
            self.delaxes(ax)         # removes ax from self.axes

        toolbar = getattr(self.canvas, 'toolbar', None)
        if toolbar is not None:
            toolbar.update()
        self._axstack.clear()
        self._seen = {}
        self.lines = []
        self.patches = []
        self.texts=[]
        self.images = []
        self.legends = []
        self._axobservers = []

    def clear(self):
        """
        Clear the figure
        """
        self.clf()

    def draw(self, renderer):
        """
        Render the figure using Renderer instance renderer
        """
        # draw the figure bounding box, perhaps none for white figure
        #print 'figure draw'
        if not self.get_visible(): return
        renderer.open_group('figure')
        self.transFigure.freeze()  # eval the lazy objects

        if self.frameon: self.figurePatch.draw(renderer)

        for p in self.patches: p.draw(renderer)
        for l in self.lines: l.draw(renderer)

        if len(self.images)<=1 or renderer.option_image_nocomposite() or not allequal([im.origin for im in self.images]):
            for im in self.images:
                im.draw(renderer)
        else:
            # make a composite image blending alpha
            # list of (_image.Image, ox, oy)

            mag = renderer.get_image_magnification()
            ims = [(im.make_image(mag), im.ox*mag, im.oy*mag)
                   for im in self.images]
            im = _image.from_images(self.bbox.height()*mag,
                                    self.bbox.width()*mag,
                                    ims)
            im.is_grayscale = False
            l, b, w, h = self.bbox.get_bounds()
            renderer.draw_image(l, b, im, self.bbox)


        # render the axes
        for a in self.axes: a.draw(renderer)

        # render the figure text
        for t in self.texts: t.draw(renderer)

        for legend in self.legends:
            legend.draw(renderer)

        self.transFigure.thaw()  # release the lazy objects
        renderer.close_group('figure')

        self._cachedRenderer = renderer

        self.canvas.draw_event(renderer)

    def draw_artist(self, a):
        'draw artist only -- this is available only after the figure is drawn'
        assert self._cachedRenderer is not None
        a.draw(self._cachedRenderer)

    def get_axes(self):
        return self.axes

    def legend(self, handles, labels, *args, **kwargs):
        """
        Place a legend in the figure.  Labels are a sequence of
        strings, handles is a sequence of line or patch instances, and
        loc can be a string or an integer specifying the legend
        location

        USAGE:
          legend( (line1, line2, line3),
                  ('label1', 'label2', 'label3'),
                  'upper right')

        The LOC location codes are

          'best' : 0,          (currently not supported for figure legends)
          'upper right'  : 1,
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,

        loc can also be an (x,y) tuple in figure coords, which
        specifies the lower left of the legend box.  figure coords are
        (0,0) is the left, bottom of the figure and 1,1 is the right,
        top.

        The legend instance is returned.  The following kwargs are supported:

        loc = "upper right" #
        numpoints = 4         # the number of points in the legend line
        prop = FontProperties(size='smaller')  # the font property
        pad = 0.2             # the fractional whitespace inside the legend border
        markerscale = 0.6     # the relative size of legend markers vs. original
        shadow                # if True, draw a shadow behind legend
        labelsep = 0.005     # the vertical space between the legend entries
        handlelen = 0.05     # the length of the legend lines
        handletextsep = 0.02 # the space between the legend line and legend text
        axespad = 0.02       # the border between the axes and legend edge

        """


        handles = flatten(handles)
        l = Legend(self, handles, labels, *args, **kwargs)
        self._set_artist_props(l)
        self.legends.append(l)
        return l

    def text(self, x, y, s, *args, **kwargs):
        """
        Add text to figure at location x,y (relative 0-1 coords) See
        the help for Axis text for the meaning of the other arguments

        kwargs control the Text properties:
        %(Text)s
        """

        override = _process_text_args({}, *args, **kwargs)
        t = Text(
            x=x, y=y, text=s,
            )

        t.update(override)
        self._set_artist_props(t)
        self.texts.append(t)
        return t
    text.__doc__ = dedent(text.__doc__) % artist.kwdocd

    def _set_artist_props(self, a):
        if a!= self:
            a.set_figure(self)
        a.set_transform(self.transFigure)

    def gca(self, **kwargs):
        """
        Return the current axes, creating one if necessary

        The following kwargs are supported
        %(Axes)s
        """
        ax = self._axstack()
        if ax is not None: return ax
        return self.add_subplot(111, **kwargs)
    gca.__doc__ = dedent(gca.__doc__) % artist.kwdocd

    def sca(self, a):
        'Set the current axes to be a and return a'
        self._axstack.bubble(a)
        for func in self._axobservers: func(self)
        return a

    def add_axobserver(self, func):
        'whenever the axes state change, func(self) will be called'
        self._axobservers.append(func)


    def savefig(self, *args, **kwargs):
        """
        SAVEFIG(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None):

        Save the current figure.

        fname - the filename to save the current figure to.  The
                output formats supported depend on the backend being
                used.  and are deduced by the extension to fname.
                Possibilities are eps, jpeg, pdf, png, ps, svg.  fname
                can also be a file or file-like object - cairo backend
                only.

        dpi - is the resolution in dots per inch.  If
              None it will default to the value savefig.dpi in the
              matplotlibrc file

        facecolor and edgecolor are the colors of the figure rectangle

        orientation is either 'landscape' or 'portrait' - not supported on
        all backends; currently only on postscript output

        papertype is is one of 'letter', 'legal', 'executive', 'ledger', 'a0'
        through 'a10', or 'b0' through 'b10' - only supported for postscript
        output

        format - one of the file extensions supported by the active backend.
        """

        for key in ('dpi', 'facecolor', 'edgecolor'):
            if not kwargs.has_key(key):
                kwargs[key] = rcParams['savefig.%s'%key]

        self.canvas.print_figure(*args, **kwargs)

    def colorbar(self, mappable, cax=None, ax=None, **kw):
        if ax is None:
            ax = self.gca()
        if cax is None:
            cax, kw = cbar.make_axes(ax, **kw)
        cb = cbar.Colorbar(cax, mappable, **kw)
        mappable.add_observer(cb)
        mappable.set_colorbar(cb, cax)
        self.sca(ax)
        return cb
    colorbar.__doc__ =  '''
        Create a colorbar for a ScalarMappable instance.

        Documentation for the pylab thin wrapper: %s
        '''% cbar.colorbar_doc

    def subplots_adjust(self, *args, **kwargs):
        """
        subplots_adjust(self, left=None, bottom=None, right=None, top=None,
                        wspace=None, hspace=None)
        fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None):
        Update the SubplotParams with kwargs (defaulting to rc where
        None) and update the subplot locations
        """
        self.subplotpars.update(*args, **kwargs)
        import matplotlib.axes
        for ax in self.axes:
            if not isinstance(ax, matplotlib.axes.Subplot):
                # Check if sharing a subplots axis
                if ax._sharex is not None and isinstance(ax._sharex, matplotlib.axes.Subplot):
                    ax._sharex.update_params()
                    ax.set_position([ax._sharex.figLeft, ax._sharex.figBottom, ax._sharex.figW, ax._sharex.figH])
                elif ax._sharey is not None and isinstance(ax._sharey, matplotlib.axes.Subplot):
                    ax._sharey.update_params()
                    ax.set_position([ax._sharey.figLeft, ax._sharey.figBottom, ax._sharey.figW, ax._sharey.figH])
            else:
                ax.update_params()
                ax.set_position([ax.figLeft, ax.figBottom, ax.figW, ax.figH])
Esempio n. 49
0
def get_path_collection_extents(*args):
    from transforms import Bbox
    if len(args[1]) == 0:
        raise ValueError("No paths provided")
    return Bbox.from_extents(*_get_path_collection_extents(*args))
Esempio n. 50
0
class Figure(Artist):
    
    def __init__(self,
                 figsize   = None,  # defaults to rc figure.figsize
                 dpi       = None,  # defaults to rc figure.dpi
                 facecolor = None,  # defaults to rc figure.facecolor
                 edgecolor = None,  # defaults to rc figure.edgecolor
                 linewidth = 1.0,   # the default linewidth of the frame
                 frameon = True,
                 ):
        """
        paper size is a w,h tuple in inches
        DPI is dots per inch 
        """
        Artist.__init__(self)
        #self.set_figure(self)

        if figsize is None  : figsize   = rcParams['figure.figsize']
        if dpi is None      : dpi       = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']
        
        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point( Value(0), Value(0) )
        self.ur = Point( self.figwidth*self.dpi,
                         self.figheight*self.dpi )
        self.bbox = Bbox(self.ll, self.ur)
        self.frameon = frameon
        
        self.transFigure = get_bbox_transform( unit_bbox(), self.bbox) 


        
        self.figurePatch = Rectangle(
            xy=(0,0), width=1, height=1,
            facecolor=facecolor, edgecolor=edgecolor,
            linewidth=linewidth,
            )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.clf()

        
    def hold(self, b=None):
        """
        Set the hold state.  If hold is None (default), toggle the
        hold state.  Else set the hold state to boolean value b.

        Eg
        hold()      # toggle hold
        hold(True)  # hold is on
        hold(False) # hold is off
        """
        if b is None: self._hold = not self._hold
        else: self._hold = b

    def figimage(self, X,
                 xo=0,
                 yo=0,
                 alpha=1.0,
                 norm=None,
                 cmap=None, 
                 vmin=None,
                 vmax=None,
                 origin=None):
        """\
FIGIMAGE(X) # add non-resampled array to figure

FIGIMAGE(X, xo, yo) # with pixel offsets

FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc

Add a nonresampled figure to the figure from array X.  xo and yo are
offsets in pixels

X must be a float array

    If X is MxN, assume luminance (grayscale)
    If X is MxNx3, assume RGB
    If X is MxNx4, assume RGBA

The following kwargs are allowed: 

  * cmap is a cm colormap instance, eg cm.jet.  If None, default to
    the rc image.cmap valuex

  * norm is a matplotlib.colors.normalize instance; default is
    normalization().  This scales luminance -> 0-1

  * vmin and vmax are used to scale a luminance image to 0-1.  If
    either is None, the min and max of the luminance values will be
    used.  Note if you pass a norm instance, the settings for vmin and
    vmax will be ignored.

  * alpha = 1.0 : the alpha blending value

  * origin is either 'upper' or 'lower', which indicates where the [0,0]
    index of the array is in the upper left or lower left corner of
    the axes.  Defaults to the rc image.origin value

This complements the axes image which will be resampled to fit the
current axes.  If you want a resampled image to fill the entire
figure, you can define an Axes with size [0,1,0,1].

A image.FigureImage instance is returned.
"""        

        if not self._hold: self.clf()

        im = FigureImage(self, cmap, norm, xo, yo, origin)
        im.set_array(X)
        im.set_alpha(alpha)
        if norm is None:
            im.set_clim(vmin, vmax)
        self.images.append(im )
        return im

        
    def set_figsize_inches(self, w, h):
        'set the figure size in inches'
        self.figwidth.set(w)
        self.figheight.set(h)

    def get_size_inches(self):
        return self.figwidth.get(), self.figheight.get()

    def get_edgecolor(self):
        'Get the edge color of the Figure rectangle' # 
        return self.figurePatch.get_edgecolor()

    def get_facecolor(self):
        'Get the face color of the Figure rectangle'
        return self.figurePatch.get_facecolor()

    def set_edgecolor(self, color):
        'Set the edge color of the Figure rectangle'
        self.figurePatch.set_edgecolor(color)

    def set_facecolor(self, color):
        'Set the face color of the Figure rectangle'
        self.figurePatch.set_facecolor(color)

    def add_axis(self, *args, **kwargs):
        raise SystemExit("""\
matplotlib changed its axes creation API in 0.54.
Please see http://matplotlib.sourceforge.net/API_CHANGES for
instructions on how to port your code.
""")

        
    def add_axes(self, rect, axisbg=None, frameon=True, **kwargs):
        """
        Add an a axes with axes rect [left, bottom, width, height]
        where all quantities are in fractions of figure width and
        height.

        The Axes instance will be returned
        """
        if axisbg is None: axisbg=rcParams['axes.facecolor']
        ispolar = kwargs.get('polar', False)
        if ispolar:
            a = PolarAxes(self, rect, axisbg, frameon)
        else:
            a = Axes(self, rect, axisbg, frameon)            
        self.axes.append(a)
        return a

    def add_subplot(self, *args, **kwargs):
        """
        Add an a subplot, eg
        add_subplot(111) or add_subplot(212, axisbg='r')

        The Axes instance will be returned
        """
        ispolar = kwargs.get('polar', False)
        dict_delall(kwargs, ('polar', ) )
        if ispolar:
            a = PolarSubplot(self, *args, **kwargs)
        else:
            a = Subplot(self, *args, **kwargs)
        
        self.axes.append(a)

        return a
    
    def clf(self):
        """
        Clear the figure
        """
        self.axes = []
        self.lines = []
        self.patches = []
        self.texts=[]
        self.images = []
        self.legends = []

    def clear(self):
        """
        Clear the figure
        """
        self.clf()
        
    def draw(self, renderer):
        """
        Render the figure using RendererGD instance renderer
        """
        # draw the figure bounding box, perhaps none for white figure

        renderer.open_group('figure')
        self.transFigure.freeze()  # eval the lazy objects
        if self.frameon: self.figurePatch.draw(renderer)

        for p in self.patches: p.draw(renderer)
        for l in self.lines: l.draw(renderer)

        if len(self.images)==1:
            im = self.images[0]
            im.draw(renderer)
        elif len(self.images)>1:
            # make a composite image blending alpha
            # list of (_image.Image, ox, oy)
            if not allequal([im.origin for im in self.images]):
                raise ValueError('Composite images with different origins not supported')
            else:
                origin = self.images[0].origin

            ims = [(im.make_image(), im.ox, im.oy) for im in self.images]
            im = _image.from_images(self.bbox.height(), self.bbox.width(), ims)
            im.is_grayscale = False
            l, b, w, h = self.bbox.get_bounds()
            renderer.draw_image(0, 0, im, origin, self.bbox)



        # render the axes
        for a in self.axes: a.draw(renderer)

        # render the figure text
        for t in self.texts: t.draw(renderer)

        for legend in self.legends:
            legend.draw(renderer)

        self.transFigure.thaw()  # release the lazy objects
        renderer.close_group('figure')

    def get_axes(self):
        return self.axes

    def legend(self, handles, labels, loc, **kwargs):
        """
        Place a legend in the figure.  Labels are a sequence of
        strings, handles is a sequence of line or patch instances, and
        loc can be a string or an integer specifying the legend
        location

        USAGE: 
          legend( (line1, line2, line3),
                  ('label1', 'label2', 'label3'),
                  'upper right')

        The LOC location codes are

          'best' : 0,          (currently not supported, defaults to upper right)
          'upper right'  : 1,  (default)
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,

        The legend instance is returned
        """


        handles = flatten(handles)
        l = Legend(self, handles, labels, loc, isaxes=False, **kwargs)
        self._set_artist_props(l)
        self.legends.append(l)
        return l
    
    def text(self, x, y, s, *args, **kwargs):
        """
        Add text to figure at location x,y (relative 0-1 coords) See
        the help for Axis text for the meaning of the other arguments
        """

        override = _process_text_args({}, *args, **kwargs)
        t = Text(
            x=x, y=y, text=s,
            )

        t.update(override)
        self._set_artist_props(t)
        self.texts.append(t)
        return t

    def _set_artist_props(self, a):
        if a!= self:
            a.set_figure(self)
        a.set_transform(self.transFigure)

    def get_width_height(self):
        'return the figure width and height in pixels'
        w = self.bbox.width()
        h = self.bbox.height()
        return w, h
Esempio n. 51
0
    def __init__(
            self,
            figsize=None,  # defaults to rc figure.figsize
            dpi=None,  # defaults to rc figure.dpi
            facecolor=None,  # defaults to rc figure.facecolor
            edgecolor=None,  # defaults to rc figure.edgecolor
            linewidth=0.0,  # the default linewidth of the frame
            frameon=True,  # whether or not to draw the figure frame
            subplotpars=None,  # default to rc
    ):
        """
        *figsize*
            w,h tuple in inches
        *dpi*
            dots per inch
        *facecolor*
            the figure patch facecolor; defaults to rc ``figure.facecolor``
        *edgecolor*
            the figure patch edge color; defaults to rc ``figure.edgecolor``
        *linewidth*
            the figure patch edge linewidth; the default linewidth of the frame
        *frameon*
            if ``False``, suppress drawing the figure frame
        *subplotpars*
            a :class:`SubplotParams` instance, defaults to rc
        """
        Artist.__init__(self)

        self.callbacks = cbook.CallbackRegistry()

        if figsize is None: figsize = rcParams['figure.figsize']
        if dpi is None: dpi = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self.dpi_scale_trans = Affine2D()
        self.dpi = dpi
        self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
        self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)

        self.frameon = frameon

        self.transFigure = BboxTransformTo(self.bbox)

        # the figurePatch name is deprecated
        self.patch = self.figurePatch = Rectangle(
            xy=(0, 0),
            width=1,
            height=1,
            facecolor=facecolor,
            edgecolor=edgecolor,
            linewidth=linewidth,
        )
        self._set_artist_props(self.patch)
        self.patch.set_aa(False)

        self._hold = rcParams['axes.hold']
        self.canvas = None

        if subplotpars is None:
            subplotpars = SubplotParams()

        self.subplotpars = subplotpars

        self._axstack = AxesStack()  # track all figure axes and current axes
        self.clf()
        self._cachedRenderer = None
Esempio n. 52
0
    def _get_layout(self, renderer):
        key = self.get_prop_tup()
        if self.cached.has_key(key): return self.cached[key]

        horizLayout = []

        thisx, thisy  = 0.0, 0.0
        xmin, ymin    = 0.0, 0.0
        width, height = 0.0, 0.0
        lines = self._text.split('\n')

        whs = npy.zeros((len(lines), 2))
        horizLayout = npy.zeros((len(lines), 4))

        # Find full vertical extent of font,
        # including ascenders and descenders:
        tmp, heightt, bl = renderer.get_text_width_height_descent(
                'lp', self._fontproperties, ismath=False)
        offsety = heightt * self._linespacing

        baseline = None
        for i, line in enumerate(lines):
            w, h, d = renderer.get_text_width_height_descent(
                line, self._fontproperties, ismath=self.is_math_text(line))
            if baseline is None:
                baseline = h - d
            whs[i] = w, h
            horizLayout[i] = thisx, thisy, w, h
            thisy -= offsety
            width = max(width, w)

        ymin = horizLayout[-1][1]
        ymax = horizLayout[0][1] + horizLayout[0][3]
        height = ymax-ymin
        xmax = xmin + width

        # get the rotation matrix
        M = Affine2D().rotate_deg(self.get_rotation())

        offsetLayout = npy.zeros((len(lines), 2))
        offsetLayout[:] = horizLayout[:, 0:2]
        # now offset the individual text lines within the box
        if len(lines)>1: # do the multiline aligment
            malign = self._get_multialignment()
            if malign == 'center':
                offsetLayout[:, 0] += width/2.0 - horizLayout[:, 2] / 2.0
            elif malign == 'right':
                offsetLayout[:, 0] += width - horizLayout[:, 2]

        # the corners of the unrotated bounding box
        cornersHoriz = npy.array(
	    [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)],
	    npy.float_)
        # now rotate the bbox
        cornersRotated = M.transform(cornersHoriz)

        txs = cornersRotated[:, 0]
        tys = cornersRotated[:, 1]

        # compute the bounds of the rotated box
        xmin, xmax = txs.min(), txs.max()
        ymin, ymax = tys.min(), tys.max()
        width  = xmax - xmin
        height = ymax - ymin

        # Now move the box to the targe position offset the display bbox by alignment
        halign = self._horizontalalignment
        valign = self._verticalalignment

        # compute the text location in display coords and the offsets
        # necessary to align the bbox with that location
        if halign=='center':  offsetx = (xmin + width/2.0)
        elif halign=='right': offsetx = (xmin + width)
        else: offsetx = xmin

        if valign=='center': offsety = (ymin + height/2.0)
        elif valign=='top': offsety  = (ymin + height)
        elif valign=='baseline': offsety = (ymin + height) + baseline
        else: offsety = ymin

        xmin -= offsetx
        ymin -= offsety

        bbox = Bbox.from_bounds(xmin, ymin, width, height)

        # now rotate the positions around the first x,y position
        xys = M.transform(offsetLayout)
        xys -= (offsetx, offsety)

        xs, ys = xys[:, 0], xys[:, 1]

        ret = bbox, zip(lines, whs, xs, ys)
        self.cached[key] = ret
        return ret
Esempio n. 53
0
def get_path_collection_extents(*args):
    from transforms import Bbox
    if len(args[1]) == 0:
        raise ValueError("No paths provided")
    return Bbox.from_extents(*_get_path_collection_extents(*args))
Esempio n. 54
0
class Figure(Artist):
    def __init__(
            self,
            figsize=None,  # defaults to rc figure.figsize
            dpi=None,  # defaults to rc figure.dpi
            facecolor=None,  # defaults to rc figure.facecolor
            edgecolor=None,  # defaults to rc figure.edgecolor
            linewidth=1.0,  # the default linewidth of the frame
            frameon=True,  # whether or not to draw the figure frame
            subplotpars=None,  # default to rc
    ):
        """
        figsize is a w,h tuple in inches
        dpi is dots per inch
        subplotpars is a SubplotParams instance, defaults to rc
        """
        Artist.__init__(self)
        #self.set_figure(self)
        self._axstack = Stack()  # maintain the current axes
        self._axobservers = []
        self._seen = {}  # axes args we've seen

        if figsize is None: figsize = rcParams['figure.figsize']
        if dpi is None: dpi = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']

        self._unit_conversions = {}

        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point(Value(0), Value(0))
        self.ur = Point(self.figwidth * self.dpi, self.figheight * self.dpi)
        self.bbox = Bbox(self.ll, self.ur)

        self.frameon = frameon

        self.transFigure = get_bbox_transform(unit_bbox(), self.bbox)

        self.figurePatch = Rectangle(
            xy=(0, 0),
            width=1,
            height=1,
            facecolor=facecolor,
            edgecolor=edgecolor,
            linewidth=linewidth,
        )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.canvas = None

        if subplotpars is None:
            subplotpars = SubplotParams()

        self.subplotpars = subplotpars

        self.clf()

        self._cachedRenderer = None

    def get_window_extent(self, *args, **kwargs):
        'get the figure bounding box in display space'
        return self.bbox

    def set_canvas(self, canvas):
        """
        Set the canvas the contains the figure

        ACCEPTS: a FigureCanvas instance
        """
        self.canvas = canvas

    def _get_unit_conversion(self, python_type):
        """
        Get a unit conversion corresponding to a python type
        """
        maps = [self._unit_conversions, Figure._default_unit_conversions]

        for m in maps:
            classes = [python_type]
            for current in classes:
                if (current in m):
                    # found it!
                    #print 'Found unit conversion for %s!' % (`python_type`)
                    return m[current]
        return None

    def register_unit_conversion(self, python_type, conversion):
        """
        Register a unit conversion class

        ACCEPTS: a Unit instance
        """
        self._unit_conversions[python_type] = conversion

    def unregister_unit_conversion(self, python_type):
        """
        Unregister a unit conversion class

        ACCEPTS: any Python type
        """
        self._unit_conversions.remove(python_type)

    def _register_default_unit_conversion(python_type, conversion):
        """
        Register a unit conversion class

        ACCEPTS: a Unit instance
        """
        Figure._default_unit_conversions[python_type] = conversion

    _default_unit_conversions = {}
    register_default_unit_conversion = \
        staticmethod(_register_default_unit_conversion)

    def _unregister_default_unit_conversion(python_type):
        """
        Unregister a unit conversion class

        ACCEPTS: any Python type
        """
        Figure._default_unit_conversions.remove(python_type)

    unregister_default_unit_conversion = \
        staticmethod(_unregister_default_unit_conversion)

    def hold(self, b=None):
        """
        Set the hold state.  If hold is None (default), toggle the
        hold state.  Else set the hold state to boolean value b.

        Eg
        hold()      # toggle hold
        hold(True)  # hold is on
        hold(False) # hold is off
        """
        if b is None: self._hold = not self._hold
        else: self._hold = b

    def figimage(self,
                 X,
                 xo=0,
                 yo=0,
                 alpha=1.0,
                 norm=None,
                 cmap=None,
                 vmin=None,
                 vmax=None,
                 origin=None):
        """
        FIGIMAGE(X) # add non-resampled array to figure

        FIGIMAGE(X, xo, yo) # with pixel offsets

        FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc

        Add a nonresampled figure to the figure from array X.  xo and yo are
        offsets in pixels

        X must be a float array

            If X is MxN, assume luminance (grayscale)
            If X is MxNx3, assume RGB
            If X is MxNx4, assume RGBA

        The following kwargs are allowed:

          * cmap is a cm colormap instance, eg cm.jet.  If None, default to
            the rc image.cmap valuex

          * norm is a matplotlib.colors.normalize instance; default is
            normalization().  This scales luminance -> 0-1

          * vmin and vmax are used to scale a luminance image to 0-1.  If
            either is None, the min and max of the luminance values will be
            used.  Note if you pass a norm instance, the settings for vmin and
            vmax will be ignored.

          * alpha = 1.0 : the alpha blending value

          * origin is either 'upper' or 'lower', which indicates where the [0,0]
            index of the array is in the upper left or lower left corner of
            the axes.  Defaults to the rc image.origin value

        This complements the axes image (Axes.imshow) which will be resampled
        to fit the current axes.  If you want a resampled image to fill the
        entire figure, you can define an Axes with size [0,1,0,1].

        A image.FigureImage instance is returned.
        """

        if not self._hold: self.clf()

        im = FigureImage(self, cmap, norm, xo, yo, origin)
        im.set_array(X)
        im.set_alpha(alpha)
        if norm is None:
            im.set_clim(vmin, vmax)
        self.images.append(im)
        return im

    def set_figsize_inches(self, *args, **kwargs):
        import warnings
        warnings.warn('Use set_size_inches instead!', DeprecationWarning)
        self.set_size_inches(*args, **kwargs)

    def set_size_inches(self, *args, **kwargs):
        """
        set_size_inches(w,h, forward=False)

        Set the figure size in inches

        Usage: set_size_inches(self, w,h)  OR
               set_size_inches(self, (w,h) )

        optional kwarg forward=True will cause the canvas size to be
        automatically updated; eg you can resize the figure window
        from the shell

        WARNING: forward=True is broken on all backends except GTK*

        ACCEPTS: a w,h tuple with w,h in inches
        """

        forward = kwargs.get('forward', False)
        if len(args) == 1:
            w, h = args[0]
        else:
            w, h = args
        self.figwidth.set(w)
        self.figheight.set(h)

        if forward:
            dpival = self.dpi.get()
            canvasw = w * dpival
            canvash = h * dpival
            manager = getattr(self.canvas, 'manager', None)
            if manager is not None:
                manager.resize(int(canvasw), int(canvash))

    def get_size_inches(self):
        return self.figwidth.get(), self.figheight.get()

    def get_edgecolor(self):
        'Get the edge color of the Figure rectangle'
        return self.figurePatch.get_edgecolor()

    def get_facecolor(self):
        'Get the face color of the Figure rectangle'
        return self.figurePatch.get_facecolor()

    def get_figwidth(self):
        'Return the figwidth as a float'
        return self.figwidth.get()

    def get_figheight(self):
        'Return the figheight as a float'
        return self.figheight.get()

    def get_dpi(self):
        'Return the dpi as a float'
        return self.dpi.get()

    def get_frameon(self):
        'get the boolean indicating frameon'
        return self.frameon

    def set_edgecolor(self, color):
        """
        Set the edge color of the Figure rectangle

        ACCEPTS: any matplotlib color - see help(colors)
        """
        self.figurePatch.set_edgecolor(color)

    def set_facecolor(self, color):
        """
        Set the face color of the Figure rectangle

        ACCEPTS: any matplotlib color - see help(colors)
        """
        self.figurePatch.set_facecolor(color)

    def set_dpi(self, val):
        """
        Set the dots-per-inch of the figure

        ACCEPTS: float
        """
        self.dpi.set(val)

    def set_figwidth(self, val):
        """
        Set the width of the figure in inches

        ACCEPTS: float
        """
        self.figwidth.set(val)

    def set_figheight(self, val):
        """
        Set the height of the figure in inches

        ACCEPTS: float
        """
        self.figheight.set(val)

    def set_frameon(self, b):
        """
        Set whether the figure frame (background) is displayed or invisible

        ACCEPTS: boolean
        """
        self.frameon = b

    def delaxes(self, a):
        'remove a from the figure and update the current axes'
        self.axes.remove(a)
        self._axstack.remove(a)
        keys = []
        for key, thisax in self._seen.items():
            if a == thisax: del self._seen[key]
        for func in self._axobservers:
            func(self)

    def _make_key(self, *args, **kwargs):
        'make a hashable key out of args and kwargs'

        def fixitems(items):
            #items may have arrays and lists in them, so convert them
            # to tuples for the key
            ret = []
            for k, v in items:
                if iterable(v): v = tuple(v)
                ret.append((k, v))
            return tuple(ret)

        def fixlist(args):
            ret = []
            for a in args:
                if iterable(a): a = tuple(a)
                ret.append(a)
            return tuple(ret)

        key = fixlist(args), fixitems(kwargs.items())
        return key

    def add_axes(self, *args, **kwargs):
        """
        Add an a axes with axes rect [left, bottom, width, height] where all
        quantities are in fractions of figure width and height.  kwargs are
        legal Axes kwargs plus "polar" which sets whether to create a polar axes

            rect = l,b,w,h
            add_axes(rect)
            add_axes(rect, frameon=False, axisbg='g')
            add_axes(rect, polar=True)
            add_axes(ax)   # add an Axes instance


        If the figure already has an axes with key *args, *kwargs then it will
        simply make that axes current and return it.  If you do not want this
        behavior, eg you want to force the creation of a new axes, you must
        use a unique set of args and kwargs.  The artist "label" attribute has
        been exposed for this purpose.  Eg, if you want two axes that are
        otherwise identical to be added to the figure, make sure you give them
        unique labels:

            add_axes(rect, label='axes1')
            add_axes(rect, label='axes2')

        The Axes instance will be returned
        """

        key = self._make_key(*args, **kwargs)

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return
        if isinstance(args[0], Axes):
            a = args[0]
            assert (a.get_figure() is self)
        else:
            rect = args[0]
            ispolar = popd(kwargs, 'polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    def add_subplot(self, *args, **kwargs):
        """
        Add a subplot.  Examples

            add_subplot(111)
            add_subplot(212, axisbg='r')  # add subplot with red background
            add_subplot(111, polar=True)  # add a polar subplot
            add_subplot(sub)              # add Subplot instance sub

        kwargs are legal Axes kwargs plus"polar" which sets whether to create a
        polar axes.  The Axes instance will be returned.

        If the figure already has a subplot with key *args, *kwargs then it will
        simply make that subplot current and return it
        """

        key = self._make_key(*args, **kwargs)
        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return

        if isinstance(args[0], Subplot) or isinstance(args[0], PolarSubplot):
            a = args[0]
            assert (a.get_figure() is self)
        else:
            ispolar = popd(kwargs, 'polar', False)
            if ispolar:
                a = PolarSubplot(self, *args, **kwargs)
            else:
                a = Subplot(self, *args, **kwargs)

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    def clf(self):
        """
        Clear the figure
        """
        self.axes = []
        self._axstack.clear()
        self._seen = {}
        self.lines = []
        self.patches = []
        self.texts = []
        self.images = []
        self.legends = []

    def clear(self):
        """
        Clear the figure
        """
        self.clf()

    def draw(self, renderer):
        """
        Render the figure using Renderer instance renderer
        """
        # draw the figure bounding box, perhaps none for white figure
        #print 'figure draw'
        if not self.get_visible(): return
        renderer.open_group('figure')
        self.transFigure.freeze()  # eval the lazy objects

        if self.frameon: self.figurePatch.draw(renderer)

        for p in self.patches:
            p.draw(renderer)
        for l in self.lines:
            l.draw(renderer)

        if len(self.images) == 1:
            im = self.images[0]
            im.draw(renderer)
        elif len(self.images) > 1:
            # make a composite image blending alpha
            # list of (_image.Image, ox, oy)
            if not allequal([im.origin for im in self.images]):
                raise ValueError(
                    'Composite images with different origins not supported')
            ims = [(im.make_image(), im.ox, im.oy) for im in self.images]
            im = _image.from_images(self.bbox.height(), self.bbox.width(), ims)
            im.is_grayscale = False
            l, b, w, h = self.bbox.get_bounds()
            renderer.draw_image(0, 0, im, self.bbox)

        # render the axes
        for a in self.axes:
            a.draw(renderer)

        # render the figure text
        for t in self.texts:
            t.draw(renderer)

        for legend in self.legends:
            legend.draw(renderer)

        self.transFigure.thaw()  # release the lazy objects
        renderer.close_group('figure')

        self._cachedRenderer = renderer

        self.canvas.draw_event(renderer)

    def draw_artist(self, a):
        'draw artist only -- this is available only after the figure is drawn'
        assert self._cachedRenderer is not None
        a.draw(self._cachedRenderer)

    def get_axes(self):
        return self.axes

    def legend(self, handles, labels, loc, **kwargs):
        """
        Place a legend in the figure.  Labels are a sequence of
        strings, handles is a sequence of line or patch instances, and
        loc can be a string or an integer specifying the legend
        location

        USAGE:
          legend( (line1, line2, line3),
                  ('label1', 'label2', 'label3'),
                  'upper right')

        The LOC location codes are

          'best' : 0,          (currently not supported, defaults to upper right)
          'upper right'  : 1,  (default)
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,

        loc can also be an (x,y) tuple in figure coords, which
        specifies the lower left of the legend box.  figure coords are
        (0,0) is the left, bottom of the figure and 1,1 is the right,
        top.

        The legend instance is returned
        """

        handles = flatten(handles)
        l = Legend(self, handles, labels, loc, isaxes=False, **kwargs)
        self._set_artist_props(l)
        self.legends.append(l)
        return l

    def text(self, x, y, s, *args, **kwargs):
        """
        Add text to figure at location x,y (relative 0-1 coords) See
        the help for Axis text for the meaning of the other arguments
        """

        override = _process_text_args({}, *args, **kwargs)
        t = Text(
            x=x,
            y=y,
            text=s,
        )

        t.update(override)
        self._set_artist_props(t)
        self.texts.append(t)
        return t

    def _set_artist_props(self, a):
        if a != self:
            a.set_figure(self)
        a.set_transform(self.transFigure)

    def gca(self, **kwargs):
        """
        Return the current axes, creating one if necessary
        """
        ax = self._axstack()
        if ax is not None: return ax
        return self.add_subplot(111, **kwargs)

    def sca(self, a):
        'Set the current axes to be a and return a'
        self._axstack.bubble(a)
        for func in self._axobservers:
            func(self)
        return a

    def add_axobserver(self, func):
        'whenever the axes state change, func(self) will be called'
        self._axobservers.append(func)

    def savefig(self, *args, **kwargs):
        """
        SAVEFIG(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None):

        Save the current figure.

        fname - the filename to save the current figure to.  The
                output formats supported depend on the backend being
                used.  and are deduced by the extension to fname.
                Possibilities are eps, jpeg, pdf, png, ps, svg.  fname
                can also be a file or file-like object - cairo backend
                only.  dpi - is the resolution in dots per inch.  If
                None it will default to the value savefig.dpi in the
                matplotlibrc file

        facecolor and edgecolor are the colors of the figure rectangle

        orientation is either 'landscape' or 'portrait' - not supported on
        all backends; currently only on postscript output

        papertype is is one of 'letter', 'legal', 'executive', 'ledger', 'a0'
        through 'a10', or 'b0' through 'b10' - only supported for postscript
        output

        format - one of 'pdf', 'png', 'ps', 'svg'. It is used to specify the
                 output when fname is a file or file-like object - cairo
                 backend only.
        """

        for key in ('dpi', 'facecolor', 'edgecolor'):
            if not kwargs.has_key(key):
                kwargs[key] = rcParams['savefig.%s' % key]

        self.canvas.print_figure(*args, **kwargs)

    def colorbar(self, mappable, cax=None, **kw):
        # Temporary compatibility code:
        old = ('tickfmt', 'cspacing', 'clabels', 'edgewidth', 'edgecolor')
        oldkw = [k for k in old if kw.has_key(k)]
        if oldkw:
            msg = 'Old colorbar kwargs (%s) found; using colorbar_classic.' % (
                ','.join(oldkw), )
            warnings.warn(msg, DeprecationWarning)
            self.colorbar_classic(mappable, cax, **kw)
            return cax
        # End of compatibility code block.
        orientation = kw.get('orientation', 'vertical')
        ax = self.gca()
        if cax is None:
            cax, kw = cbar.make_axes(ax, **kw)
        cb = cbar.Colorbar(cax, mappable, **kw)
        mappable.add_observer(cb)
        mappable.set_colorbar(cb, cax)
        self.sca(ax)
        return cb

    colorbar.__doc__ = '''
        Create a colorbar for a ScalarMappable instance.

        Documentation for the pylab thin wrapper: %s
        ''' % cbar.colorbar_doc

    def colorbar_classic(self,
                         mappable,
                         cax=None,
                         orientation='vertical',
                         tickfmt='%1.1f',
                         cspacing='proportional',
                         clabels=None,
                         drawedges=False,
                         edgewidth=0.5,
                         edgecolor='k'):
        """
        Create a colorbar for mappable image

        mappable is the cm.ScalarMappable instance that you want the
        colorbar to apply to, e.g. an Image as returned by imshow or a
        PatchCollection as returned by scatter or pcolor.

        tickfmt is a format string to format the colorbar ticks

        cax is a colorbar axes instance in which the colorbar will be
        placed.  If None, as default axesd will be created resizing the
        current aqxes to make room for it.  If not None, the supplied axes
        will be used and the other axes positions will be unchanged.

        orientation is the colorbar orientation: one of 'vertical' | 'horizontal'

        cspacing controls how colors are distributed on the colorbar.
        if cspacing == 'linear', each color occupies an equal area
        on the colorbar, regardless of the contour spacing.
        if cspacing == 'proportional' (Default), the area each color
        occupies on the the colorbar is proportional to the contour interval.
        Only relevant for a Contour image.

        clabels can be a sequence containing the
        contour levels to be labelled on the colorbar, or None (Default).
        If clabels is None, labels for all contour intervals are
        displayed. Only relevant for a Contour image.

        if drawedges == True, lines are drawn at the edges between
        each color on the colorbar. Default False.

        edgecolor is the line color delimiting the edges of the colors
        on the colorbar (if drawedges == True). Default black ('k')

        edgewidth is the width of the lines delimiting the edges of
        the colors on the colorbar (if drawedges == True). Default 0.5

        return value is the colorbar axes instance
        """

        if orientation not in ('horizontal', 'vertical'):
            raise ValueError('Orientation must be horizontal or vertical')

        if isinstance(mappable, FigureImage) and cax is None:
            raise TypeError(
                'Colorbars for figure images currently not supported unless you provide a colorbar axes in cax'
            )

        ax = self.gca()

        cmap = mappable.cmap

        if cax is None:
            l, b, w, h = ax.get_position()
            if orientation == 'vertical':
                neww = 0.8 * w
                ax.set_position((l, b, neww, h), 'both')
                cax = self.add_axes([l + 0.9 * w, b, 0.1 * w, h])
            else:
                newh = 0.8 * h
                ax.set_position((l, b + 0.2 * h, w, newh), 'both')
                cax = self.add_axes([l, b, w, 0.1 * h])

        else:
            if not isinstance(cax, Axes):
                raise TypeError('Expected an Axes instance for cax')

        norm = mappable.norm
        if norm.vmin is None or norm.vmax is None:
            mappable.autoscale()
        cmin = norm.vmin
        cmax = norm.vmax
        if isinstance(mappable, ContourSet):
            # mappable image is from contour or contourf
            clevs = mappable.levels
            clevs = minimum(clevs, cmax)
            clevs = maximum(clevs, cmin)
            isContourSet = True
        elif isinstance(mappable, ScalarMappable):
            # from imshow or pcolor.
            isContourSet = False
            clevs = linspace(cmin, cmax, cmap.N + 1)  # boundaries, hence N+1
        else:
            raise TypeError("don't know how to handle type %s" %
                            type(mappable))

        N = len(clevs)
        C = array([clevs, clevs])
        if cspacing == 'linear':
            X, Y = meshgrid(clevs, [0, 1])
        elif cspacing == 'proportional':
            X, Y = meshgrid(linspace(cmin, cmax, N), [0, 1])
        else:
            raise ValueError("cspacing must be 'linear' or 'proportional'")

        if orientation == 'vertical':
            args = (transpose(Y), transpose(C), transpose(X), clevs)
        else:
            args = (C, Y, X, clevs)
        #If colors were listed in the original mappable, then
        # let contour handle them the same way.
        colors = getattr(mappable, 'colors', None)
        if colors is not None:
            kw = {'colors': colors}
        else:
            kw = {'cmap': cmap, 'norm': norm}
        if isContourSet and not mappable.filled:
            CS = cax.contour(*args, **kw)
            colls = mappable.collections
            for ii in range(len(colls)):
                CS.collections[ii].set_linewidth(colls[ii].get_linewidth())
        else:
            kw['antialiased'] = False
            CS = cax.contourf(*args, **kw)
        if drawedges:
            for col in CS.collections:
                col.set_edgecolor(edgecolor)
                col.set_linewidth(edgewidth)

        mappable.add_observer(CS)
        mappable.set_colorbar(CS, cax)

        if isContourSet:
            if cspacing == 'linear':
                ticks = linspace(cmin, cmax, N)
            else:
                ticks = clevs
            if cmin == mappable.levels[0]:
                ticklevs = clevs
            else:  # We are not showing the full ends of the range.
                ticks = ticks[1:-1]
                ticklevs = clevs[1:-1]
            labs = [tickfmt % lev for lev in ticklevs]
            if clabels is not None:
                for i, lev in enumerate(ticklevs):
                    if lev not in clabels:
                        labs[i] = ''

        if orientation == 'vertical':
            cax.set_xticks([])
            cax.yaxis.tick_right()
            cax.yaxis.set_label_position('right')
            if isContourSet:
                cax.set_yticks(ticks)
                cax.set_yticklabels(labs)
            else:
                cax.yaxis.set_major_formatter(FormatStrFormatter(tickfmt))
        else:
            cax.set_yticks([])
            if isContourSet:
                cax.set_xticks(ticks)
                cax.set_xticklabels(labs)
            else:
                cax.xaxis.set_major_formatter(FormatStrFormatter(tickfmt))

        self.sca(ax)
        return cax

    def subplots_adjust(self, *args, **kwargs):
        """
        fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None):
        Update the SubplotParams with kwargs (defaulting to rc where
        None) and update the subplot locations
        """
        self.subplotpars.update(*args, **kwargs)
        import matplotlib.axes
        for ax in self.axes:
            if not isinstance(ax, matplotlib.axes.Subplot):
                # Check if sharing a subplots axis
                if ax._sharex is not None and isinstance(
                        ax._sharex, matplotlib.axes.Subplot):
                    ax._sharex.update_params()
                    ax.set_position([
                        ax._sharex.figLeft, ax._sharex.figBottom,
                        ax._sharex.figW, ax._sharex.figH
                    ])
                elif ax._sharey is not None and isinstance(
                        ax._sharey, matplotlib.axes.Subplot):
                    ax._sharey.update_params()
                    ax.set_position([
                        ax._sharey.figLeft, ax._sharey.figBottom,
                        ax._sharey.figW, ax._sharey.figH
                    ])
            else:
                ax.update_params()
                ax.set_position([ax.figLeft, ax.figBottom, ax.figW, ax.figH])
Esempio n. 55
0
class Figure(Artist):
    
    def __init__(self,
                 figsize   = None,  # defaults to rc figure.figsize
                 dpi       = None,  # defaults to rc figure.dpi
                 facecolor = None,  # defaults to rc figure.facecolor
                 edgecolor = None,  # defaults to rc figure.edgecolor
                 linewidth = 1.0,   # the default linewidth of the frame
                 frameon = True,
                 subplotpars = None, # default to rc
                 ):
        """
        paper size is a w,h tuple in inches
        DPI is dots per inch
        subplotpars is a SubplotParams instance, defaults to rc
        """
        Artist.__init__(self)
        #self.set_figure(self)
        self._axstack = Stack()  # maintain the current axes
        self._axobservers = []
        self._seen = {}          # axes args we've seen        

        if figsize is None  : figsize   = rcParams['figure.figsize']
        if dpi is None      : dpi       = rcParams['figure.dpi']
        if facecolor is None: facecolor = rcParams['figure.facecolor']
        if edgecolor is None: edgecolor = rcParams['figure.edgecolor']
        
        self.dpi = Value(dpi)
        self.figwidth = Value(figsize[0])
        self.figheight = Value(figsize[1])
        self.ll = Point( Value(0), Value(0) )
        self.ur = Point( self.figwidth*self.dpi,
                         self.figheight*self.dpi )
        self.bbox = Bbox(self.ll, self.ur)
        self.frameon = frameon
        
        self.transFigure = get_bbox_transform( unit_bbox(), self.bbox) 


        
        self.figurePatch = Rectangle(
            xy=(0,0), width=1, height=1,
            facecolor=facecolor, edgecolor=edgecolor,
            linewidth=linewidth,
            )
        self._set_artist_props(self.figurePatch)

        self._hold = rcParams['axes.hold']
        self.canvas = None

        if subplotpars is None:
            subplotpars = SubplotParams()
            
        self.subplotpars = subplotpars

        self.clf()

    def set_canvas(self, canvas):
        """\
Set the canvas the contains the figure

ACCEPTS: a FigureCanvas instance"""
        self.canvas = canvas
        
    def hold(self, b=None):
        """
        Set the hold state.  If hold is None (default), toggle the
        hold state.  Else set the hold state to boolean value b.

        Eg
        hold()      # toggle hold
        hold(True)  # hold is on
        hold(False) # hold is off
        """
        if b is None: self._hold = not self._hold
        else: self._hold = b

    def figimage(self, X,
                 xo=0,
                 yo=0,
                 alpha=1.0,
                 norm=None,
                 cmap=None, 
                 vmin=None,
                 vmax=None,
                 origin=None):
        """\
FIGIMAGE(X) # add non-resampled array to figure

FIGIMAGE(X, xo, yo) # with pixel offsets

FIGIMAGE(X, **kwargs) # control interpolation ,scaling, etc

Add a nonresampled figure to the figure from array X.  xo and yo are
offsets in pixels

X must be a float array

    If X is MxN, assume luminance (grayscale)
    If X is MxNx3, assume RGB
    If X is MxNx4, assume RGBA

The following kwargs are allowed: 

  * cmap is a cm colormap instance, eg cm.jet.  If None, default to
    the rc image.cmap valuex

  * norm is a matplotlib.colors.normalize instance; default is
    normalization().  This scales luminance -> 0-1

  * vmin and vmax are used to scale a luminance image to 0-1.  If
    either is None, the min and max of the luminance values will be
    used.  Note if you pass a norm instance, the settings for vmin and
    vmax will be ignored.

  * alpha = 1.0 : the alpha blending value

  * origin is either 'upper' or 'lower', which indicates where the [0,0]
    index of the array is in the upper left or lower left corner of
    the axes.  Defaults to the rc image.origin value

This complements the axes image (Axes.imshow) which will be resampled
to fit the current axes.  If you want a resampled image to fill the
entire figure, you can define an Axes with size [0,1,0,1].

A image.FigureImage instance is returned.
"""        

        if not self._hold: self.clf()

        im = FigureImage(self, cmap, norm, xo, yo, origin)
        im.set_array(X)
        im.set_alpha(alpha)
        if norm is None:
            im.set_clim(vmin, vmax)
        self.images.append(im)
        return im

        
    def set_figsize_inches(self, *args):
        """
Set the figure size in inches

Usage: set_figsize_inches(self, w,h)  OR
       set_figsize_inches(self, (w,h) )

ACCEPTS: a w,h tuple with w,h in inches
"""
        if len(args)==1:
            w,h = args[0]
        else:
            w,h = args
        self.figwidth.set(w)
        self.figheight.set(h)

    def get_size_inches(self):
        return self.figwidth.get(), self.figheight.get()

    def get_edgecolor(self):
        'Get the edge color of the Figure rectangle' 
        return self.figurePatch.get_edgecolor()

    def get_facecolor(self):
        'Get the face color of the Figure rectangle'
        return self.figurePatch.get_facecolor()

    def get_figwidth(self):
        'Return the figwidth as a float'
        return self.figwidth.get()

    def get_figheight(self):
        'Return the figheight as a float'
        return self.figheight.get()

    def get_dpi(self):
        'Return the dpi as a float'
        return self.dpi.get()

    def get_frameon(self):
        'get the boolean indicating frameon'
        return self.frameon

    def set_edgecolor(self, color):
        """
Set the edge color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)"""
        self.figurePatch.set_edgecolor(color)

    def set_facecolor(self, color):
        """
Set the face color of the Figure rectangle

ACCEPTS: any matplotlib color - see help(colors)"""
        self.figurePatch.set_facecolor(color)

    def set_dpi(self, val):
        """
Set the dots-per-inch of the figure

ACCEPTS: float"""
        self.dpi.set(val)

    def set_figwidth(self, val):
        """
Set the width of the figure in inches

ACCEPTS: float"""
        self.figwidth.set(val)

    def set_figheight(self, val):
        """
Set the height of the figure in inches

ACCEPTS: float"""
        self.figheight.set(val)

    def set_frameon(self, b):
        """
Set whether the figure frame (background) is displayed or invisible

ACCEPTS: boolean"""
        self.frameon = b

    def delaxes(self, a):
        'remove a from the figure and update the current axes'
        self.axes.remove(a)
        self._axstack.remove(a)
        keys = []
        for key, thisax in self._seen.items():
            if a==thisax: del self._seen[key]
        for func in self._axobservers: func(self)        
            


    def _make_key(self, *args, **kwargs):
        'make a hashable key out of args and kwargs'

        def fixitems(items):
            #items may have arrays and lists in them, so convert them
            # to tuples for the kyey
            ret = []
            for k, v in items:
                if iterable(v): v = tuple(v)                
                ret.append((k,v))
            return ret

        if iterable(args[0]):
            key = tuple(args[0]), tuple( fixitems(kwargs.items()))
        else:		
            key = args[0], tuple(fixitems( kwargs.items()))
        return key
        
    def add_axes(self, *args, **kwargs):
        """
Add an a axes with axes rect [left, bottom, width, height] where all
quantities are in fractions of figure width and height.  kwargs are
legal Axes kwargs plus"polar" which sets whether to create a polar axes

    add_axes((l,b,w,h))
    add_axes((l,b,w,h), frameon=False, axisbg='g')
    add_axes((l,b,w,h), polar=True)
    add_axes(ax)   # add an Axes instance


If the figure already has an axes with key *args, *kwargs then it will
simply make that axes current and return it.  If you do not want this
behavior, eg you want to force the creation of a new axes, you must
use a unique set of args and kwargs.  The artist "label" attribute has
been exposed for this purpose.  Eg, if you want two axes that are
otherwise identical to be added to the axes, make sure you give them
unique labels:

    add_axes((l,b,w,h), label='1')
    add_axes((l,b,w,h), label='2')

The Axes instance will be returned
        """

	key = self._make_key(*args, **kwargs)

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax

        if not len(args): return        
        if isinstance(args[0], Axes):
            a = args[0]
            a.set_figure(self)
        else:
            rect = args[0]
            ispolar = popd(kwargs, 'polar', False)

            if ispolar:
                a = PolarAxes(self, rect, **kwargs)
            else:
                a = Axes(self, rect, **kwargs)            
                

        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a

    def add_subplot(self, *args, **kwargs):
        """
Add an a subplot.  Examples

    add_subplot(111)
    add_subplot(212, axisbg='r')  # add subplot with red background
    add_subplot(111, polar=True)  # add a polar subplot
    add_subplot(sub)              # add Subplot instance sub
        
kwargs are legal Axes kwargs plus"polar" which sets whether to create a
polar axes.  The Axes instance will be returned.

If the figure already has a subplot with key *args, *kwargs then it will
simply make that subplot current and return it
        """

	key = self._make_key(*args, **kwargs)        

        if self._seen.has_key(key):
            ax = self._seen[key]
            self.sca(ax)
            return ax
        
                
        if not len(args): return        
        
        if isinstance(args[0], Subplot) or isinstance(args, PolarSubplot):
            a = args[0]
            a.set_figure(self)
        else:
            ispolar = popd(kwargs, 'polar', False)
            if ispolar:
                a = PolarSubplot(self, *args, **kwargs)
            else:
                a = Subplot(self, *args, **kwargs)

        
        self.axes.append(a)
        self._axstack.push(a)
        self.sca(a)
        self._seen[key] = a
        return a
    
    def clf(self):
        """
        Clear the figure
        """
        self.axes = []
        self._axstack.clear()
        self._seen = {}
        self.lines = []
        self.patches = []
        self.texts=[]
        self.images = []
        self.legends = []

    def clear(self):
        """
        Clear the figure
        """
        self.clf()
        
    def draw(self, renderer):
        """
        Render the figure using RendererGD instance renderer
        """
        # draw the figure bounding box, perhaps none for white figure
        #print 'figure draw'
        if not self.get_visible(): return 
        renderer.open_group('figure')
        self.transFigure.freeze()  # eval the lazy objects
        if self.frameon: self.figurePatch.draw(renderer)

        for p in self.patches: p.draw(renderer)
        for l in self.lines: l.draw(renderer)

        if len(self.images)==1:
            im = self.images[0]
            im.draw(renderer)
        elif len(self.images)>1:
            # make a composite image blending alpha
            # list of (_image.Image, ox, oy)
            if not allequal([im.origin for im in self.images]):
                raise ValueError('Composite images with different origins not supported')
            else:
                origin = self.images[0].origin

            ims = [(im.make_image(), im.ox, im.oy) for im in self.images]
            im = _image.from_images(self.bbox.height(), self.bbox.width(), ims)
            im.is_grayscale = False
            l, b, w, h = self.bbox.get_bounds()
            renderer.draw_image(0, 0, im, origin, self.bbox)



        # render the axes
        for a in self.axes: a.draw(renderer)

        # render the figure text
        for t in self.texts: t.draw(renderer)

        for legend in self.legends:
            legend.draw(renderer)

        self.transFigure.thaw()  # release the lazy objects
        renderer.close_group('figure')

    def get_axes(self):
        return self.axes

    def legend(self, handles, labels, loc, **kwargs):
        """
        Place a legend in the figure.  Labels are a sequence of
        strings, handles is a sequence of line or patch instances, and
        loc can be a string or an integer specifying the legend
        location

        USAGE: 
          legend( (line1, line2, line3),
                  ('label1', 'label2', 'label3'),
                  'upper right')

        The LOC location codes are

          'best' : 0,          (currently not supported, defaults to upper right)
          'upper right'  : 1,  (default)
          'upper left'   : 2,
          'lower left'   : 3,
          'lower right'  : 4,
          'right'        : 5,
          'center left'  : 6,
          'center right' : 7,
          'lower center' : 8,
          'upper center' : 9,
          'center'       : 10,

        loc can also be an (x,y) tuple in figure coords, which
        specifies the lower left of the legend box.  figure coords are
        (0,0) is the left, bottom of the figure and 1,1 is the right,
        top.

        The legend instance is returned
        """


        handles = flatten(handles)
        l = Legend(self, handles, labels, loc, isaxes=False, **kwargs)
        self._set_artist_props(l)
        self.legends.append(l)
        return l
    
    def text(self, x, y, s, *args, **kwargs):
        """
        Add text to figure at location x,y (relative 0-1 coords) See
        the help for Axis text for the meaning of the other arguments
        """

        override = _process_text_args({}, *args, **kwargs)
        t = Text(
            x=x, y=y, text=s,
            )

        t.update(override)
        self._set_artist_props(t)
        self.texts.append(t)
        return t

    def _set_artist_props(self, a):
        if a!= self:
            a.set_figure(self)
        a.set_transform(self.transFigure)

    def get_width_height(self):
        'return the figure width and height in pixels (as floats)'
        return self.bbox.width(), self.bbox.height()


    def gca(self, **kwargs):
        """
Return the current axes, creating one if necessary
        """
        ax = self._axstack()
        if ax is not None: return ax
        return self.add_subplot(111, **kwargs)
        
    def sca(self, a):
        'Set the current axes to be a and return a'
        self._axstack.bubble(a)
        for func in self._axobservers: func(self)
        return a

    def add_axobserver(self, func):
        'whenever the axes state change, func(self) will be called'
        self._axobservers.append(func)
        

    def savefig(self, *args, **kwargs):
        """
SAVEFIG(fname, dpi=150, facecolor='w', edgecolor='w',
orientation='portrait'):

Save the current figure to filename fname.  dpi is the resolution
in dots per inch.

Output file types currently supported are jpeg and png and will be
deduced by the extension to fname

facecolor and edgecolor are the colors os the figure rectangle

orientation is either 'landscape' or 'portrait' - not supported on
all backends; currently only on postscript output."""
    
        for key in ('dpi', 'facecolor', 'edgecolor'):
            if not kwargs.has_key(key):
                kwargs[key] = rcParams['savefig.%s'%key]

        self.canvas.print_figure(*args, **kwargs)
    

    def colorbar(self, mappable, tickfmt='%1.1f', cax=None, orientation='vertical'):
        """
        Create a colorbar for mappable image

        tickfmt is a format string to format the colorbar ticks

        cax is a colorbar axes instance in which the colorbar will be
        placed.  If None, as default axesd will be created resizing the
        current aqxes to make room for it.  If not None, the supplied axes
        will be used and the other axes positions will be unchanged.

        orientation is the colorbar orientation: one of 'vertical' | 'horizontal'
        return value is the colorbar axes instance
        """

        if orientation not in ('horizontal', 'vertical'):
            raise ValueError('Orientation must be horizontal or vertical')

        if isinstance(mappable, FigureImage) and cax is None:
            raise TypeError('Colorbars for figure images currently not supported unless you provide a colorbar axes in cax')


        ax = self.gca()

        cmap = mappable.cmap
        norm = mappable.norm

        if norm.vmin is None or norm.vmax is None:
            mappable.autoscale()
        cmin = norm.vmin
        cmax = norm.vmax

        if cax is None:
            l,b,w,h = ax.get_position()
            if orientation=='vertical':
                neww = 0.8*w
                ax.set_position((l,b,neww,h))
                cax = self.add_axes([l + 0.9*w, b, 0.1*w, h])
            else:
                newh = 0.8*h
                ax.set_position((l,b+0.2*h,w,newh))
                cax = self.add_axes([l, b, w, 0.1*h])

        else:
            if not isinstance(cax, Axes):
                raise TypeError('Expected an Axes instance for cax')

        N = cmap.N

        c = linspace(cmin, cmax, N)
        C = array([c,c])

        if orientation=='vertical':
            C = transpose(C)

        if orientation=='vertical':
            extent=(0, 1, cmin, cmax)
        else:
            extent=(cmin, cmax, 0, 1)
        coll = cax.imshow(C,
                          interpolation='nearest',
                          #interpolation='bilinear', 
                          origin='lower',
                          cmap=cmap, norm=norm,
                          extent=extent)
        mappable.add_observer(coll)
        mappable.set_colorbar(coll, cax)

        if orientation=='vertical':
            cax.set_xticks([])
            cax.yaxis.tick_right()
            cax.yaxis.set_major_formatter(FormatStrFormatter(tickfmt))
        else:
            cax.set_yticks([])
            cax.xaxis.set_major_formatter(FormatStrFormatter(tickfmt))

        self.sca(ax)
        return cax


    def subplots_adjust(self, *args, **kwargs):
        """
        fig.subplots_adjust(left=None, bottom=None, right=None, wspace=None, hspace=None):        
        Update the SubplotParams with kwargs (defaulting to rc where
        None) and update the subplot locations
        """
        self.subplotpars.update(*args, **kwargs)        
        import matplotlib.axes
        for ax in self.axes:
            if not isinstance(ax, matplotlib.axes.Subplot): continue
            ax.update_params()
            ax.set_position([ax.figLeft, ax.figBottom, ax.figW, ax.figH])
Esempio n. 56
0
 def get_window_extent(self, renderer):
     'Return the bounding box of the table in window coords'
     boxes = [c.get_window_extent(renderer) for c in self._cells]
     return Bbox.union(boxes)