Exemplo n.º 1
0
        def plotImage(x, y, im):
            # TODO hard-coded size of images, breaks in some cases
            width = 1
            height = 2
            bb = Bbox.from_bounds(x, y, width, height)
            bb2 = TransformedBbox(bb, plot.transData)
            bbox_image = BboxImage(bb2, norm=None, origin=None, clip_on=False)

            bbox_image.set_data(im)
            plot.add_artist(bbox_image)
Exemplo n.º 2
0
    def make_image(self, renderer, magnification=1.0, unsampled=False):
        trans = self.get_transform()
        # image is created in the canvas coordinate.
        x1, x2, y1, y2 = self.get_extent()
        bbox = Bbox(np.array([[x1, y1], [x2, y2]]))
        transformed_bbox = TransformedBbox(bbox, trans)

        return self._make_image(
            self._A, bbox, transformed_bbox, self.axes.bbox, magnification,
            unsampled=unsampled)
Exemplo n.º 3
0
def plotImage(x, y, im, x_scale, y_scale):
    """
    Plots an image at each x and y location.
    """
    bb = Bbox.from_bounds(x, y, x_scale, y_scale)  # Change figure aspect ratio
    bb2 = TransformedBbox(bb, ax.transData)
    bbox_image = BboxImage(bb2, norm=None, origin=None, clip_on=False)

    bbox_image.set_data(im)
    ax.add_artist(bbox_image)
Exemplo n.º 4
0
def test_bbox_image_inverted():
    # This is just used to produce an image to feed to BboxImage
    image = np.arange(100).reshape((10, 10))

    fig, ax = plt.subplots()
    bbox_im = BboxImage(
        TransformedBbox(Bbox([[100, 100], [0, 0]]), ax.transData))
    bbox_im.set_data(image)
    bbox_im.set_clip_on(False)
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 100)
    ax.add_artist(bbox_im)

    image = np.identity(10)

    bbox_im = BboxImage(TransformedBbox(Bbox([[0.1, 0.2], [0.3, 0.25]]),
                                        ax.figure.transFigure))
    bbox_im.set_data(image)
    bbox_im.set_clip_on(False)
    ax.add_artist(bbox_im)
    def plot(self, img, val, act):
        x, y = random.random() - 0.5, val

        w, h = self.img_shape

        bb = Bbox.from_bounds(x, y, w, h)
        bb2 = TransformedBbox(bb, self.ax.transData)
        bbox_image = BboxImage(bb2, norm=None, origin=None, clip_on=True)

        bbox_image.set_data(img)
        self.ax.add_artist(bbox_image)
Exemplo n.º 6
0
    def get_extent(self, renderer):
        bb = TransformedBbox(self.axes.viewLim, self.parent_axes.transData)

        x, y, w, h = bb.bounds

        xd, yd = 0, 0

        fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
        pad = self.pad * fontsize

        return w * self.zoom + 2 * pad, h * self.zoom + 2 * pad, xd + pad, yd + pad
Exemplo n.º 7
0
def zoom_effect01(ax1, ax2, xmin, xmax, **kwargs):
    """
    Connect *ax1* and *ax2*. The *xmin*-to-*xmax* range in both axes will
    be marked.

    Parameters
    ----------
    ax1
        The main axes.
    ax2
        The zoomed axes.
    xmin, xmax
        The limits of the colored area in both plot axes.
    **kwargs
        Arguments passed to the patch constructor.
    """

    bbox = Bbox.from_extents(xmin, 0, xmax, 1)

    mybbox1 = TransformedBbox(bbox, ax1.get_xaxis_transform())
    mybbox2 = TransformedBbox(bbox, ax2.get_xaxis_transform())

    prop_patches = {**kwargs, "ec": "none", "alpha": 0.2}

    c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox(
        mybbox1,
        mybbox2,
        loc1a=3,
        loc2a=2,
        loc1b=4,
        loc2b=1,
        prop_lines=kwargs,
        prop_patches=prop_patches)

    ax1.add_patch(bbox_patch1)
    ax2.add_patch(bbox_patch2)
    ax2.add_patch(c1)
    ax2.add_patch(c2)
    ax2.add_patch(p)

    return c1, c2, bbox_patch1, bbox_patch2, p
Exemplo n.º 8
0
    def connect_bbox(bbox1, bbox2, loc1, loc2=None):
        """
        Helper function to obtain a Path from one bbox to another.

        Parameters
        ----------
        bbox1, bbox2 : `matplotlib.transforms.Bbox`
            Bounding boxes to connect.

        loc1 : {1, 2, 3, 4}
            Corner of *bbox1* to use. Valid values are::

                'upper right'  : 1,
                'upper left'   : 2,
                'lower left'   : 3,
                'lower right'  : 4

        loc2 : {1, 2, 3, 4}, optional
            Corner of *bbox2* to use. If None, defaults to *loc1*.
            Valid values are::

                'upper right'  : 1,
                'upper left'   : 2,
                'lower left'   : 3,
                'lower right'  : 4

        Returns
        -------
        path : `matplotlib.path.Path`
            A line segment from the *loc1* corner of *bbox1* to the *loc2*
            corner of *bbox2*.
        """
        if isinstance(bbox1, Rectangle):
            bbox1 = TransformedBbox(Bbox.unit(), bbox1.get_transform())
        if isinstance(bbox2, Rectangle):
            bbox2 = TransformedBbox(Bbox.unit(), bbox2.get_transform())
        if loc2 is None:
            loc2 = loc1
        x1, y1 = BboxConnector.get_bbox_edge_pos(bbox1, loc1)
        x2, y2 = BboxConnector.get_bbox_edge_pos(bbox2, loc2)
        return Path([[x1, y1], [x2, y2]])
Exemplo n.º 9
0
 def get_size(self):
     factor = 1.
     if self.unit == "points":
         factor = self.ax.figure.dpi / 72.
     elif self.unit[:4] == "axes":
         b = TransformedBbox(Bbox.from_bounds(0, 0, 1, 1),
                             self.ax.transAxes)
         dic = {"max": max(b.width, b.height),
                "min": min(b.width, b.height),
                "width": b.width, "height": b.height}
         factor = dic[self.unit[5:]]
     return self.size * factor
Exemplo n.º 10
0
def adjust_bbox_pdf(fig, bbox_inches):
    """
    adjust_bbox for pdf & eps format
    """

    tr = Affine2D().scale(72)

    _bbox = TransformedBbox(bbox_inches, tr)

    fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width,
                                       bbox_inches.height)
    x0, y0 = _bbox.x0, _bbox.y0
    f = 72. / fig.dpi
    w1, h1 = fig.bbox.width * f, fig.bbox.height * f
    fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1)
    fig.transFigure.invalidate()

    fig.bbox = TransformedBbox(fig.bbox_inches, tr)

    fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1,
                         fig.bbox.height / h1)
Exemplo n.º 11
0
def adjust_bbox_png(fig, bbox_inches):
    """
    adjust_bbox for png (Agg) format
    """

    tr = fig.dpi_scale_trans

    _bbox = TransformedBbox(bbox_inches, tr)
    x0, y0 = _bbox.x0, _bbox.y0
    fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width,
                                       bbox_inches.height)

    x0, y0 = _bbox.x0, _bbox.y0
    w1, h1 = fig.bbox.width, fig.bbox.height
    fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1)
    fig.transFigure.invalidate()

    fig.bbox = TransformedBbox(fig.bbox_inches, tr)

    fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1,
                         fig.bbox.height / h1)
Exemplo n.º 12
0
 def get_bbox_to_anchor(self):
     """
     return the bbox that the legend will be anchored
     """
     if self._bbox_to_anchor is None:
         return self.axes.bbox
     else:
         transform = self._bbox_to_anchor_transform
         if transform is None:
             return self._bbox_to_anchor
         else:
             return TransformedBbox(self._bbox_to_anchor, transform)
Exemplo n.º 13
0
def zoom_effect01(ax1, ax2, xmin, xmax, ymin, ymax, **kwargs):
    """
    ax1 : the main axes
    ax1 : the zoomed axes
    (xmin,xmax) : the limits of the colored area in both plot axes.

    connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will
    be marked.  The keywords parameters will be used ti create
    patches.

    """

    trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)
    trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)

    bbox1 = Bbox.from_extents(xmin, ymin, xmax, ymax)
    bbox2 = Bbox.from_extents(xmin, 0, xmax, 1)

    mybbox1 = TransformedBbox(bbox1, trans1)
    mybbox2 = TransformedBbox(bbox2, trans2)

    prop_patches = kwargs.copy()
    prop_patches["ec"] = "none"
    prop_patches["fc"] = "grey"
    prop_patches["alpha"] = 0.2

    c1, c2, bbox_patch1, bbox_patch2, p = \
        connect_bbox(
                     mybbox1,
                     mybbox2,
                     loc1a=4, loc2a=3, loc1b=1, loc2b=2,
                     prop_lines=kwargs, prop_patches=prop_patches)

    ax1.add_patch(bbox_patch1)
    ax2.add_patch(bbox_patch2)
    ax2.add_patch(c1)
    ax2.add_patch(c2)
    ax2.add_patch(p)

    return c1, c2, bbox_patch1, bbox_patch2, p
Exemplo n.º 14
0
    def make_artists(self, axes, show_intruder):
        'make self.artists_dict'

        assert self.vec_list
        self.img = get_airplane_img()

        posa_list = [(v[0], v[1], v[2]) for v in self.vec_list]
        posb_list = [(v[3], v[4], v[5]) for v in self.vec_list]

        pos_lists = [posa_list, posb_list]

        if show_intruder:
            pos_lists.append(posb_list)

        for i, pos_list in enumerate(pos_lists):
            x, y, theta = pos_list[0]

            l = axes.plot(*zip(*pos_list), f'c-', lw=0, zorder=1)[0]
            l.set_visible(False)
            self.artists_dict[f'line{i}'] = l

            if i == 0:
                lc = LineCollection([], lw=2, animated=True, color='k', zorder=1)
                axes.add_collection(lc)
                self.artists_dict[f'lc{i}'] = lc

                int_lc = LineCollection([], lw=2, animated=True, color='k', zorder=1)
                axes.add_collection(int_lc)
                self.artists_dict[f'int_lc{i}'] = int_lc

            # only sim_index = 0 gets intruder aircraft
            if i == 0 or (i == 1 and show_intruder):
                size = State.plane_size
                box = Bbox.from_bounds(x - size/2, y - size/2, size, size)
                tbox = TransformedBbox(box, axes.transData)
                box_image = BboxImage(tbox, zorder=2)

                theta_deg = (theta - np.pi / 2) / np.pi * 180 # original image is facing up, not right
                img_rotated = ndimage.rotate(self.img, theta_deg, order=1)

                box_image.set_data(img_rotated)
                axes.add_artist(box_image)
                self.artists_dict[f'plane{i}'] = box_image

            if i == 0:
                dot = axes.plot([x], [y], 'k.', markersize=6.0, zorder=2)[0]
                self.artists_dict[f'dot{i}'] = dot

                rad = 1500
                c = patches.Ellipse((x, y), rad, rad, color='k', lw=3.0, fill=False)
                axes.add_patch(c)
                self.artists_dict[f'circle{i}'] = c
Exemplo n.º 15
0
def draw_from_point_to_bbox(parent_axes: Axes,
                            insert_axes: Axes,
                            point: Sequence,
                            loc=1,
                            **kwargs):
    """ add a box connector from a point to an axes """
    from mpl_toolkits.axes_grid1.inset_locator import TransformedBbox, BboxConnector, Bbox
    rect = TransformedBbox(Bbox([point, point]), parent_axes.transData)
    # rect = TransformedBbox(Bbox([[1, 0], [1, 0]]), parent_axes.transData)
    p1 = BboxConnector(rect, insert_axes.bbox, loc, **kwargs)
    parent_axes.add_patch(p1)
    p1.set_clip_on(False)
    return p1
Exemplo n.º 16
0
    def make_image(self, renderer, magnification=1.0, unsampled=True):
        """
        Normalize, rescale, and colormap this image's data for rendering using
        *renderer*, with the given *magnification*.

        If *unsampled* is True, the image will not be scaled, but an
        appropriate affine transformation will be returned instead.

        Returns
        -------
        image : (M, N, 4) uint8 array
            The RGBA image, resampled unless *unsampled* is True.
        x, y : float
            The upper left corner where the image should be drawn, in pixel
            space.
        trans : Affine2D
            The affine transformation from image to pixel space.
        """
        x1, x2, y1, y2 = self.get_extent()
        bbox = Bbox(np.array([[x1, y1], [x2, y2]]))
        trans = self.get_transform()
        transformed_bbox = TransformedBbox(bbox, trans)
        if (self.plot_width is not None or self.plot_height is not None
                or self.width_scale != 1.0 or self.height_scale != 1.0):
            unsampled = False

        # Aggregate
        binned = self.aggregate([x1, x2], [y1, y2])
        if self.agg_hook is not None:
            binned = self.agg_hook(binned)

        self.set_ds_data(binned)

        # Normalize and color to make an RGBA array
        rgba = self.shade(binned)
        if self.shade_hook is not None:
            img = to_ds_image(binned, rgba)
            img = self.shade_hook(img)
            rgba = uint32_to_uint8(img.data)

        self.set_array(rgba)

        return self._make_image(
            rgba,
            bbox,
            transformed_bbox,
            self.axes.bbox,
            magnification=magnification,
            unsampled=unsampled,
        )
Exemplo n.º 17
0
def plotImagesInWeightSpace( fig, wspace, orig_images, img_dims, margin_percent = 0.03, img_ratio = 0.035 ):
    # Author: C. Howard
    # function to robustly plot images in the weight space
    #
    # fig: Figure handle for plotting
    # wspace        : The lower dimensional features such that wspace = W*X where W maps
    #                 the input data X into lower dim data
    # orig_images   : This is basically X where each column is a vectorized image
    # img_dims      : This is the rectangular dimensions of each image in the data set
    # margin_percent: What percent of the data span we want to add margin in the plot
    # img_ratio     : What ratio we use to decide image sizes to be plotted,  relative to the data span


    # get number of original images
    (d,num_images) = orig_images.shape

    # get max dims of data
    x1max = np.max(wspace[0, :])
    x1min = np.min(wspace[0, :])
    x2max = np.max(wspace[1, :])
    x2min = np.min(wspace[1, :])

    # get the center
    x1c = 0.5 * (x1max + x1min)
    x2c = 0.5 * (x2max + x2min)

    # get width and height
    w = x1max - x1min
    h = x2max - x2min

    # compute how much to scale the width/height from the
    # center of the data to set the xlimits/ylimits
    scale = 0.5 + margin_percent

    # plot the images in the weight space
    ax = fig.add_subplot(111)

    for k in range(0, num_images):
        bb          = Bbox.from_bounds(wspace[0, k], wspace[1, k], w * img_ratio, h * img_ratio)
        bb2         = TransformedBbox(bb, ax.transData)
        bbox_img    = BboxImage(bb2, norm=None, origin=None, clip_on=False)
        bbox_img.set_data(orig_images[:, k].reshape(img_dims[0], img_dims[0]))
        ax.add_artist(bbox_img)

    # set the axis limits
    ax.set_xlim(x1c - scale * w, x1c + scale * w)
    ax.set_ylim(x2c - scale * h, x2c + scale * h)

    # return the fig handle and axis handle
    return (fig,ax)
Exemplo n.º 18
0
def zoom_effect(ax1, ax2, xmin, xmax, **kwargs):
    trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)
    trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)

    bbox = Bbox.from_extents(xmin, 0, xmax, 1)

    mybbox1 = TransformedBbox(bbox, trans1)
    mybbox2 = TransformedBbox(bbox, trans2)

    prop_patches = {**kwargs, "ec": "none", "alpha": 0.1}

    c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox(
        mybbox1, mybbox2,
        loc1a=3, loc2a=2, loc1b=4, loc2b=1,
        prop_lines=kwargs, prop_patches=prop_patches)

    ax1.add_patch(bbox_patch1)
    ax2.add_patch(bbox_patch2)
    ax2.add_patch(c1)
    ax2.add_patch(c2)
    ax2.add_patch(p)

    return c1, c2, bbox_patch1, bbox_patch2, p
Exemplo n.º 19
0
    def __call__(self, ax, renderer):
        self.axes = ax

        fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
        self._update_offset_func(renderer, fontsize)

        width, height, xdescent, ydescent = self.get_extent(renderer)

        px, py = self.get_offset(width, height, 0, 0, renderer)
        bbox_canvas = Bbox.from_bounds(px, py, width, height)
        tr = ax.figure.transFigure.inverted()
        bb = TransformedBbox(bbox_canvas, tr)

        return bb
Exemplo n.º 20
0
def mark_inset(parent_axes, inset_axes, loc1, loc2, **kwargs):
    """
    Draw a box to mark the location of an area represented by an inset axes.

    This function draws a box in *parent_axes* at the bounding box of
    *inset_axes*, and shows a connection with the inset axes by drawing lines
    at the corners, giving a "zoomed in" effect.

    Parameters
    ----------
    parent_axes : `matplotlib.axes.Axes`
        Axes which contains the area of the inset axes.

    inset_axes : `matplotlib.axes.Axes`
        The inset axes.

    loc1, loc2 : {1, 2, 3, 4}
        Corners to use for connecting the inset axes and the area in the
        parent axes.

    **kwargs
        Patch properties for the lines and box drawn:

        %(Patch:kwdoc)s

    Returns
    -------
    pp : `matplotlib.patches.Patch`
        The patch drawn to represent the area of the inset axes.

    p1, p2 : `matplotlib.patches.Patch`
        The patches connecting two corners of the inset axes and its area.
    """
    rect = TransformedBbox(inset_axes.viewLim, parent_axes.transData)

    if 'fill' in kwargs:
        pp = BboxPatch(rect, **kwargs)
    else:
        fill = bool({'fc', 'facecolor', 'color'}.intersection(kwargs))
        pp = BboxPatch(rect, fill=fill, **kwargs)
    parent_axes.add_patch(pp)

    p1 = BboxConnector(inset_axes.bbox, rect, loc1=loc1, **kwargs)
    inset_axes.add_patch(p1)
    p1.set_clip_on(False)
    p2 = BboxConnector(inset_axes.bbox, rect, loc1=loc2, **kwargs)
    inset_axes.add_patch(p2)
    p2.set_clip_on(False)

    return pp, p1, p2
Exemplo n.º 21
0
def mark_inset(parent_axes, inset_axes, loc1, loc2, **kwargs):
   rect = TransformedBbox(inset_axes.viewLim, parent_axes.transData)

   pp = BboxPatch(rect, **kwargs)
   parent_axes.add_patch(pp)

   p1 = BboxConnector(inset_axes.bbox, rect, loc1=loc1, **kwargs)
   inset_axes.add_patch(p1)
   p1.set_clip_on(False)
   p2 = BboxConnector(inset_axes.bbox, rect, loc1=loc2, **kwargs)
   inset_axes.add_patch(p2)
   p2.set_clip_on(False)

   return pp, p1, p2
Exemplo n.º 22
0
    def connect_bbox(bbox1, bbox2, loc1, loc2=None):
       if isinstance(bbox1, Rectangle):
          transform = bbox1.get_transfrom()
          bbox1 = Bbox.from_bounds(0, 0, 1, 1)
          bbox1 = TransformedBbox(bbox1, transform)

       if isinstance(bbox2, Rectangle):
          transform = bbox2.get_transform()
          bbox2 = Bbox.from_bounds(0, 0, 1, 1)
          bbox2 = TransformedBbox(bbox2, transform)

       if loc2 is None:
          loc2 = loc1

       x1, y1 = BboxConnector.get_bbox_edge_pos(bbox1, loc1)
       x2, y2 = BboxConnector.get_bbox_edge_pos(bbox2, loc2)

       verts = [[x1, y1], [x2,y2]]
       #Path()

       codes = [Path.MOVETO, Path.LINETO]

       return Path(verts, codes)
Exemplo n.º 23
0
    def update_artists(self, axes):
        '''update artists in self.artists_dict to be consistant with self.vec, returns a list of artists'''

        assert self.artists_dict
        rv = []

        x1, y1, theta1, x2, y2, theta2, _ = self.vec

        for i, x, y, theta in zip([0, 1], [x1, x2], [y1, y2], [theta1, theta2]):
            key = f'plane{i}'

            if key in self.artists_dict:
                plane = self.artists_dict[key]
                rv.append(plane)

                if plane.get_visible():
                    theta_deg = (theta - np.pi / 2) / np.pi * 180 # original image is facing up, not right
                    original_size = list(self.img.shape)
                    img_rotated = ndimage.rotate(self.img, theta_deg, order=1)
                    rotated_size = list(img_rotated.shape)
                    ratios = [r / o for r, o in zip(rotated_size, original_size)]
                    plane.set_data(img_rotated)

                    size = State.plane_size
                    width = size * ratios[0]
                    height = size * ratios[1]
                    box = Bbox.from_bounds(x - width/2, y - height/2, width, height)
                    tbox = TransformedBbox(box, axes.transData)
                    plane.bbox = tbox

            key = f'dot{i}'
            if key in self.artists_dict:
                dot = self.artists_dict[f'dot{i}']
                cir = self.artists_dict[f'circle{i}']
                rv += [dot, cir]

                dot.set_data([x], [y])
                cir.set_center((x, y))

        # line collection
        lc = self.artists_dict['lc0']
        rv.append(lc)

        int_lc = self.artists_dict['int_lc0']
        rv.append(int_lc)

        self.update_lc_artists(lc, int_lc)

        return rv
Exemplo n.º 24
0
    def create_artists(self, legend, orig_handle,
                       xdescent, ydescent, width, height, fontsize, trans):
        scale = 1.5
        bb = Bbox.from_bounds(
            xdescent + self.offset,
            ydescent,
            height * self.image_data.shape[1] / self.image_data.shape[0] * scale,
            height * scale)

        tbb = TransformedBbox(bb, trans)
        image = BboxImage(tbb)
        image.set_data(self.image_data)

        self.update_prop(image, orig_handle, legend)
        return [image]
Exemplo n.º 25
0
    def show(data, eps=0.0):
        # Make box slightly larger
        box_extent = data.space.partition.extent * (1.0 + eps)
        box_min = data.space.min_pt - data.space.partition.extent * eps / 2.0

        bbox0 = Bbox.from_bounds(*box_min, *box_extent)
        bbox = TransformedBbox(bbox0, ax.transData)
        # TODO: adapt interpolation
        bbox_image = BboxImage(bbox,
                               norm=normalization,
                               cmap='bone',
                               interpolation='nearest',
                               origin=False)
        bbox_image.set_data(np.asarray(data).T)
        ax.add_artist(bbox_image)
Exemplo n.º 26
0
    def _compute_bbox(self, fig, kw):
        """
        Compute the tight bounding box for each figure once, reducing
        number of required canvas draw calls from N*2 to N+1 as a
        function of the number of frames.

        Tight bounding box computing code here mirrors:
        matplotlib.backend_bases.FigureCanvasBase.print_figure
        as it hasn't been factored out as a function.
        """
        fig_id = id(fig)
        if kw['bbox_inches'] == 'tight':
            if not fig_id in MPLRenderer.drawn:
                fig.set_dpi(self.dpi)
                fig.canvas.draw()
                renderer = fig._cachedRenderer
                bbox_inches = fig.get_tightbbox(renderer)
                bbox_artists = kw.pop("bbox_extra_artists", [])
                bbox_artists += fig.get_default_bbox_extra_artists()
                bbox_filtered = []
                for a in bbox_artists:
                    bbox = a.get_window_extent(renderer)
                    if isinstance(bbox, tuple):
                        continue
                    if a.get_clip_on():
                        clip_box = a.get_clip_box()
                        if clip_box is not None:
                            bbox = Bbox.intersection(bbox, clip_box)
                        clip_path = a.get_clip_path()
                        if clip_path is not None and bbox is not None:
                            clip_path = clip_path.get_fully_transformed_path()
                            bbox = Bbox.intersection(bbox,
                                                     clip_path.get_extents())
                    if bbox is not None and (bbox.width != 0
                                             or bbox.height != 0):
                        bbox_filtered.append(bbox)
                if bbox_filtered:
                    _bbox = Bbox.union(bbox_filtered)
                    trans = Affine2D().scale(1.0 / self.dpi)
                    bbox_extra = TransformedBbox(_bbox, trans)
                    bbox_inches = Bbox.union([bbox_inches, bbox_extra])
                pad = plt.rcParams['savefig.pad_inches']
                bbox_inches = bbox_inches.padded(pad)
                MPLRenderer.drawn[fig_id] = bbox_inches
                kw['bbox_inches'] = bbox_inches
            else:
                kw['bbox_inches'] = MPLRenderer.drawn[fig_id]
        return kw
Exemplo n.º 27
0
Arquivo: ui.py Projeto: jiejohn/paddle
    def adjust_tight_bbox(self, pad=0.1, extra_artists=None):
        bbox_inches = self.figure.get_tightbbox(self.renderer)
        bbox_artists = self.figure.get_default_bbox_extra_artists()

        if extra_artists is None:
            extra_artists = []
            extra_artists.extend([ax.get_legend() for ax in self.figure.axes if ax.get_legend()])

        bbox_artists.extend(extra_artists)
        bbox_filtered = []
        for a in bbox_artists:
            bbox = a.get_window_extent(self.renderer)
            if a.get_clip_on():
                clip_box = a.get_clip_box()
                if clip_box is not None:
                    bbox = Bbox.intersection(bbox, clip_box)
                clip_path = a.get_clip_path()
                if clip_path is not None and bbox is not None:
                    clip_path = clip_path.get_fully_transformed_path()
                    bbox = Bbox.intersection(bbox,
                                             clip_path.get_extents())
            if bbox is not None and (bbox.width != 0 or
                                     bbox.height != 0):
                bbox_filtered.append(bbox)

        if bbox_filtered:
            _bbox = Bbox.union(bbox_filtered)
            trans = Affine2D().scale(1.0 / self.figure.dpi)
            bbox_extra = TransformedBbox(_bbox, trans)
            bbox_inches = Bbox.union([bbox_inches, bbox_extra])

        if pad:
            bbox_inches = bbox_inches.padded(pad)

        rect = (np.array(bbox_inches.bounds).reshape(-1,2) / self.figure.get_size_inches()).flatten()

        # Adjust the rect; values <0 to +; + to zero
        xpad = -np.min((rect[0], (1-rect[2])))
        xpad = 0 if xpad < 0 else xpad
        ypad = -np.min((rect[1], (1-rect[3])))
        ypad = 0 if ypad < 0 else ypad
        rect = np.array([ xpad, ypad, 1-xpad, 1-ypad ])



        self.figure.tight_layout(rect=np.abs(rect))
Exemplo n.º 28
0
    def create_artists(self, legend, orig_handle, xdescent, ydescent, width,
                       height, fontsize, trans):

        # enlarge the image by these margins
        sx, sy = self.image_stretch

        # create a bounding box to house the image
        bb = Bbox.from_bounds(xdescent - sx, ydescent - sy, width + sx,
                              height + sy)

        tbb = TransformedBbox(bb, trans)
        image = BboxImage(tbb)
        image.set_data(self.image_data)

        self.update_prop(image, orig_handle, legend)

        return [image]
Exemplo n.º 29
0
    def get_transform(self):

        # If we don't override this, the transform includes LogTransforms
        # and the final image gets warped to be 'correct' in data space
        # since Matplotlib 2.x:
        #
        #   https://matplotlib.org/users/prev_whats_new/whats_new_2.0.0.html#non-linear-scales-on-image-plots
        #
        # However, we want pixels to always visually be the same size, so we
        # override the transform to not include the LogTransform components.

        xmin, xmax = self._ax.get_xlim()
        ymin, ymax = self._ax.get_ylim()

        bbox = BboxTransformFrom(TransformedBbox(Bbox([[xmin, ymin], [xmax, ymax]]),
                                                 IDENTITY))

        return bbox + self._ax.transAxes
Exemplo n.º 30
0
    def set_bbox_to_anchor(self, bbox, transform=None):
        """
        Set the bbox that the legend will be anchored to.

        Parameters
        ----------
        bbox : `~matplotlib.transforms.BboxBase` or tuple
            The bounding box can be specified in the following ways:

            - A `.BboxBase` instance
            - A tuple of ``(left, bottom, width, height)`` in the given
              transform (normalized axes coordinate if None)
            - A tuple of ``(left, bottom)`` where the width and height will be
              assumed to be zero.
            - *None*, to remove the bbox anchoring, and use the parent bbox.

        transform : `~matplotlib.transforms.Transform`, optional
            A transform to apply to the bounding box. If not specified, this
            will use a transform to the bounding box of the parent.
        """
        if bbox is None:
            self._bbox_to_anchor = None
            return
        elif isinstance(bbox, BboxBase):
            self._bbox_to_anchor = bbox
        else:
            try:
                l = len(bbox)
            except TypeError as err:
                raise ValueError("Invalid argument for bbox : %s" %
                                 str(bbox)) from err

            if l == 2:
                bbox = [bbox[0], bbox[1], 0, 0]

            self._bbox_to_anchor = Bbox.from_bounds(*bbox)

        if transform is None:
            transform = BboxTransformTo(self.parent.bbox)

        self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor,
                                               transform)
        self.stale = True