Python matplotlib.transforms.Bbox() Examples

The following are 30 code examples of matplotlib.transforms.Bbox(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.transforms , or try the search function .
Example #1
Source File: _base.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def set_figure(self, fig):
        """
        Set the `.Figure` for this `.Axes`.

        Parameters
        ----------
        fig : `.Figure`
        """
        martist.Artist.set_figure(self, fig)

        self.bbox = mtransforms.TransformedBbox(self._position,
                                                fig.transFigure)
        # these will be updated later as data is added
        self.dataLim = mtransforms.Bbox.null()
        self.viewLim = mtransforms.Bbox.unit()
        self.transScale = mtransforms.TransformWrapper(
            mtransforms.IdentityTransform())

        self._set_lim_and_transforms() 
Example #2
Source File: _base.py    From ImageFusion with MIT License 6 votes vote down vote up
def relim(self, visible_only=False):
        """
        Recompute the data limits based on current artists. If you want to
        exclude invisible artists from the calculation, set
        ``visible_only=True``

        At present, :class:`~matplotlib.collections.Collection`
        instances are not supported.
        """
        # Collections are deliberately not supported (yet); see
        # the TODO note in artists.py.
        self.dataLim.ignore(True)
        self.dataLim.set_points(mtransforms.Bbox.null().get_points())
        self.ignore_existing_data_limits = True

        for line in self.lines:
            if not visible_only or line.get_visible():
                self._update_line_limits(line)

        for p in self.patches:
            if not visible_only or p.get_visible():
                self._update_patch_limits(p) 
Example #3
Source File: test_transforms.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_bbox_intersection():
    bbox_from_ext = mtransforms.Bbox.from_extents
    inter = mtransforms.Bbox.intersection

    r1 = bbox_from_ext(0, 0, 1, 1)
    r2 = bbox_from_ext(0.5, 0.5, 1.5, 1.5)
    r3 = bbox_from_ext(0.5, 0, 0.75, 0.75)
    r4 = bbox_from_ext(0.5, 1.5, 1, 2.5)
    r5 = bbox_from_ext(1, 1, 2, 2)

    # self intersection -> no change
    assert_bbox_eq(inter(r1, r1), r1)
    # simple intersection
    assert_bbox_eq(inter(r1, r2), bbox_from_ext(0.5, 0.5, 1, 1))
    # r3 contains r2
    assert_bbox_eq(inter(r1, r3), r3)
    # no intersection
    assert inter(r1, r4) is None
    # single point
    assert_bbox_eq(inter(r1, r5), bbox_from_ext(1, 1, 1, 1)) 
Example #4
Source File: collections.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def __init__(self, meshWidth, meshHeight, coordinates,
                 antialiased=True, shading='flat', **kwargs):
        Collection.__init__(self, **kwargs)
        self._meshWidth = meshWidth
        self._meshHeight = meshHeight
        self._coordinates = coordinates
        self._antialiased = antialiased
        self._shading = shading

        self._bbox = transforms.Bbox.unit()
        self._bbox.update_from_data_xy(coordinates.reshape(
            ((meshWidth + 1) * (meshHeight + 1), 2)))

        # By converting to floats now, we can avoid that on every draw.
        self._coordinates = self._coordinates.reshape(
            (meshHeight + 1, meshWidth + 1, 2))
        self._coordinates = np.array(self._coordinates, np.float_) 
Example #5
Source File: _base.py    From neural-network-animation with MIT License 6 votes vote down vote up
def relim(self, visible_only=False):
        """
        Recompute the data limits based on current artists. If you want to
        exclude invisible artists from the calculation, set
        ``visible_only=True``

        At present, :class:`~matplotlib.collections.Collection`
        instances are not supported.
        """
        # Collections are deliberately not supported (yet); see
        # the TODO note in artists.py.
        self.dataLim.ignore(True)
        self.dataLim.set_points(mtransforms.Bbox.null().get_points())
        self.ignore_existing_data_limits = True

        for line in self.lines:
            if not visible_only or line.get_visible():
                self._update_line_limits(line)

        for p in self.patches:
            if not visible_only or p.get_visible():
                self._update_patch_limits(p) 
Example #6
Source File: imagesAsTickMarks.py    From pyrsa with GNU Lesser General Public License v3.0 6 votes vote down vote up
def imagesAsTickMarks(ax, images):
    TICKYPOS = -.6
    lowerCorner = ax.transData.transform((.8,TICKYPOS-.2))
    upperCorner = ax.transData.transform((1.2,TICKYPOS+.2))
    print(lowerCorner)
    print(upperCorner)
    bbox_image = BboxImage(Bbox([lowerCorner[0],
                                 lowerCorner[1],
                                 upperCorner[0],
                                 upperCorner[1],
                                 ]),
                           norm = None,
                           origin=None,
                           clip_on=False,
                           )

    image = imread(images[0])
    print('img loaded')
    bbox_image.set_data(image)
    ax.add_artist(bbox_image) 
Example #7
Source File: test_image.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #8
Source File: _base.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def set_figure(self, fig):
        """
        Set the `.Figure` for this `.Axes`.

        Parameters
        ----------
        fig : `.Figure`
        """
        martist.Artist.set_figure(self, fig)

        self.bbox = mtransforms.TransformedBbox(self._position,
                                                fig.transFigure)
        # these will be updated later as data is added
        self.dataLim = mtransforms.Bbox.null()
        self.viewLim = mtransforms.Bbox.unit()
        self.transScale = mtransforms.TransformWrapper(
            mtransforms.IdentityTransform())

        self._set_lim_and_transforms() 
Example #9
Source File: _base.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def set_position(self, pos, which='both'):
        """
        Set the axes position.

        Axes have two position attributes. The 'original' position is the
        position allocated for the Axes. The 'active' position is the
        position the Axes is actually drawn at. These positions are usually
        the same unless a fixed aspect is set to the Axes. See `.set_aspect`
        for details.

        Parameters
        ----------
        pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox`
            The new position of the in `.Figure` coordinates.

        which : {'both', 'active', 'original'}, optional
            Determines which position variables to change.

        """
        self._set_position(pos, which='both')
        # because this is being called externally to the library we
        # zero the constrained layout parts.
        self._layoutbox = None
        self._poslayoutbox = None 
Example #10
Source File: _base.py    From ImageFusion with MIT License 6 votes vote down vote up
def set_figure(self, fig):
        """
        Set the class:`~matplotlib.axes.Axes` figure

        accepts a class:`~matplotlib.figure.Figure` instance
        """
        martist.Artist.set_figure(self, fig)

        self.bbox = mtransforms.TransformedBbox(self._position,
                                                fig.transFigure)
        # these will be updated later as data is added
        self.dataLim = mtransforms.Bbox.null()
        self.viewLim = mtransforms.Bbox.unit()
        self.transScale = mtransforms.TransformWrapper(
            mtransforms.IdentityTransform())

        self._set_lim_and_transforms() 
Example #11
Source File: _base.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def get_position(self, original=False):
        """
        Get a copy of the axes rectangle as a `.Bbox`.

        Parameters
        ----------
        original : bool
            If ``True``, return the original position. Otherwise return the
            active position. For an explanation of the positions see
            `.set_position`.

        Returns
        -------
        pos : `.Bbox`

        """
        if original:
            return self._originalPosition.frozen()
        else:
            locator = self.get_axes_locator()
            if not locator:
                self.apply_aspect()
            return self._position.frozen() 
Example #12
Source File: _base.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def set_figure(self, fig):
        """
        Set the `.Figure` for this `.Axes`.

        Parameters
        ----------
        fig : `.Figure`
        """
        martist.Artist.set_figure(self, fig)

        self.bbox = mtransforms.TransformedBbox(self._position,
                                                fig.transFigure)
        # these will be updated later as data is added
        self.dataLim = mtransforms.Bbox.null()
        self.viewLim = mtransforms.Bbox.unit()
        self.transScale = mtransforms.TransformWrapper(
            mtransforms.IdentityTransform())

        self._set_lim_and_transforms() 
Example #13
Source File: _base.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def set_position(self, pos, which='both'):
        """
        Set the axes position.

        Axes have two position attributes. The 'original' position is the
        position allocated for the Axes. The 'active' position is the
        position the Axes is actually drawn at. These positions are usually
        the same unless a fixed aspect is set to the Axes. See `.set_aspect`
        for details.

        Parameters
        ----------
        pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox`
            The new position of the in `.Figure` coordinates.

        which : {'both', 'active', 'original'}, optional
            Determines which position variables to change.

        """
        self._set_position(pos, which=which)
        # because this is being called externally to the library we
        # zero the constrained layout parts.
        self._layoutbox = None
        self._poslayoutbox = None 
Example #14
Source File: _base.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_position(self, pos, which='both'):
        """
        Set the axes position.

        Axes have two position attributes. The 'original' position is the
        position allocated for the Axes. The 'active' position is the
        position the Axes is actually drawn at. These positions are usually
        the same unless a fixed aspect is set to the Axes. See `.set_aspect`
        for details.

        Parameters
        ----------
        pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox`
            The new position of the in `.Figure` coordinates.

        which : {'both', 'active', 'original'}, optional
            Determines which position variables to change.

        """
        self._set_position(pos, which=which)
        # because this is being called externally to the library we
        # zero the constrained layout parts.
        self._layoutbox = None
        self._poslayoutbox = None 
Example #15
Source File: _base.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_figure(self, fig):
        """
        Set the `.Figure` for this `.Axes`.

        Parameters
        ----------
        fig : `.Figure`
        """
        martist.Artist.set_figure(self, fig)

        self.bbox = mtransforms.TransformedBbox(self._position,
                                                fig.transFigure)
        # these will be updated later as data is added
        self.dataLim = mtransforms.Bbox.null()
        self.viewLim = mtransforms.Bbox.unit()
        self.transScale = mtransforms.TransformWrapper(
            mtransforms.IdentityTransform())

        self._set_lim_and_transforms() 
Example #16
Source File: _base.py    From neural-network-animation with MIT License 6 votes vote down vote up
def set_figure(self, fig):
        """
        Set the class:`~matplotlib.axes.Axes` figure

        accepts a class:`~matplotlib.figure.Figure` instance
        """
        martist.Artist.set_figure(self, fig)

        self.bbox = mtransforms.TransformedBbox(self._position,
                                                fig.transFigure)
        # these will be updated later as data is added
        self.dataLim = mtransforms.Bbox.null()
        self.viewLim = mtransforms.Bbox.unit()
        self.transScale = mtransforms.TransformWrapper(
            mtransforms.IdentityTransform())

        self._set_lim_and_transforms() 
Example #17
Source File: test_transforms.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def test_bbox_intersection():
    bbox_from_ext = mtransforms.Bbox.from_extents
    inter = mtransforms.Bbox.intersection

    r1 = bbox_from_ext(0, 0, 1, 1)
    r2 = bbox_from_ext(0.5, 0.5, 1.5, 1.5)
    r3 = bbox_from_ext(0.5, 0, 0.75, 0.75)
    r4 = bbox_from_ext(0.5, 1.5, 1, 2.5)
    r5 = bbox_from_ext(1, 1, 2, 2)

    # self intersection -> no change
    assert_bbox_eq(inter(r1, r1), r1)
    # simple intersection
    assert_bbox_eq(inter(r1, r2), bbox_from_ext(0.5, 0.5, 1, 1))
    # r3 contains r2
    assert_bbox_eq(inter(r1, r3), r3)
    # no intersection
    assert inter(r1, r4) is None
    # single point
    assert_bbox_eq(inter(r1, r5), bbox_from_ext(1, 1, 1, 1)) 
Example #18
Source File: collections.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, meshWidth, meshHeight, coordinates,
                 antialiased=True, shading='flat', **kwargs):
        Collection.__init__(self, **kwargs)
        self._meshWidth = meshWidth
        self._meshHeight = meshHeight
        self._coordinates = coordinates
        self._antialiased = antialiased
        self._shading = shading

        self._bbox = transforms.Bbox.unit()
        self._bbox.update_from_data_xy(coordinates.reshape(
            ((meshWidth + 1) * (meshHeight + 1), 2)))

        # By converting to floats now, we can avoid that on every draw.
        self._coordinates = self._coordinates.reshape(
            (meshHeight + 1, meshWidth + 1, 2))
        self._coordinates = np.array(self._coordinates, np.float_) 
Example #19
Source File: _base.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def get_window_extent(self, *args, **kwargs):
        """
        get the axes bounding box in display space; *args* and
        *kwargs* are empty
        """
        bbox = self.bbox
        x_pad = 0
        if self.axison and self.xaxis.get_visible():
            x_pad = self.xaxis.get_tick_padding()
        y_pad = 0
        if self.axison and self.yaxis.get_visible():
            y_pad = self.yaxis.get_tick_padding()
        return mtransforms.Bbox([[bbox.x0 - x_pad, bbox.y0 - y_pad],
                                 [bbox.x1 + x_pad, bbox.y1 + y_pad]]) 
Example #20
Source File: test_transforms.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_lockable_bbox(locked_element):
    other_elements = ['x0', 'y0', 'x1', 'y1']
    other_elements.remove(locked_element)

    orig = mtransforms.Bbox.unit()
    locked = mtransforms.LockableBbox(orig, **{locked_element: 2})

    # LockableBbox should keep its locked element as specified in __init__.
    assert getattr(locked, locked_element) == 2
    assert getattr(locked, 'locked_' + locked_element) == 2
    for elem in other_elements:
        assert getattr(locked, elem) == getattr(orig, elem)

    # Changing underlying Bbox should update everything but locked element.
    orig.set_points(orig.get_points() + 10)
    assert getattr(locked, locked_element) == 2
    assert getattr(locked, 'locked_' + locked_element) == 2
    for elem in other_elements:
        assert getattr(locked, elem) == getattr(orig, elem)

    # Unlocking element should revert values back to the underlying Bbox.
    setattr(locked, 'locked_' + locked_element, None)
    assert getattr(locked, 'locked_' + locked_element) is None
    assert np.all(orig.get_points() == locked.get_points())

    # Relocking an element should change its value, but not others.
    setattr(locked, 'locked_' + locked_element, 3)
    assert getattr(locked, locked_element) == 3
    assert getattr(locked, 'locked_' + locked_element) == 3
    for elem in other_elements:
        assert getattr(locked, elem) == getattr(orig, elem) 
Example #21
Source File: _base.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def set_axes_locator(self, locator):
        """
        Set the axes locator.

        Parameters
        ----------
        locator : Callable[[Axes, Renderer], Bbox]
        """
        self._axes_locator = locator
        self.stale = True 
Example #22
Source File: _base.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def _set_position(self, pos, which='both'):
        """
        private version of set_position.  Call this internally
        to get the same functionality of `get_position`, but not
        to take the axis out of the constrained_layout
        hierarchy.
        """
        if not isinstance(pos, mtransforms.BboxBase):
            pos = mtransforms.Bbox.from_bounds(*pos)
        for ax in self._twinned_axes.get_siblings(self):
            if which in ('both', 'active'):
                ax._position.set(pos)
            if which in ('both', 'original'):
                ax._originalPosition.set(pos)
        self.stale = True 
Example #23
Source File: _base.py    From ImageFusion with MIT License 5 votes vote down vote up
def set_position(self, pos, which='both'):
        """
        Set the axes position with::

          pos = [left, bottom, width, height]

        in relative 0,1 coords, or *pos* can be a
        :class:`~matplotlib.transforms.Bbox`

        There are two position variables: one which is ultimately
        used, but which may be modified by :meth:`apply_aspect`, and a
        second which is the starting point for :meth:`apply_aspect`.


        Optional keyword arguments:
          *which*

            ==========   ====================
            value        description
            ==========   ====================
            'active'     to change the first
            'original'   to change the second
            'both'       to change both
            ==========   ====================

        """
        if not isinstance(pos, mtransforms.BboxBase):
            pos = mtransforms.Bbox.from_bounds(*pos)
        if which in ('both', 'active'):
            self._position.set(pos)
        if which in ('both', 'original'):
            self._originalPosition.set(pos) 
Example #24
Source File: test_transforms.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_nan_overlap():
    a = mtransforms.Bbox([[0, 0], [1, 1]])
    b = mtransforms.Bbox([[0, 0], [1, np.nan]])
    assert not a.overlaps(b) 
Example #25
Source File: test_transforms.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_bbox_as_strings():
    b = mtransforms.Bbox([[.5, 0], [.75, .75]])
    assert_bbox_eq(b, eval(repr(b), {'Bbox': mtransforms.Bbox}))
    asdict = eval(str(b), {'Bbox': dict})
    for k, v in asdict.items():
        assert getattr(b, k) == v
    fmt = '.1f'
    asdict = eval(format(b, fmt), {'Bbox': dict})
    for k, v in asdict.items():
        assert eval(format(getattr(b, k), fmt)) == v 
Example #26
Source File: _base.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def relim(self, visible_only=False):
        """
        Recompute the data limits based on current artists. If you want to
        exclude invisible artists from the calculation, set
        ``visible_only=True``

        At present, :class:`~matplotlib.collections.Collection`
        instances are not supported.
        """
        # Collections are deliberately not supported (yet); see
        # the TODO note in artists.py.
        self.dataLim.ignore(True)
        self.dataLim.set_points(mtransforms.Bbox.null().get_points())
        self.ignore_existing_data_limits = True

        for line in self.lines:
            if not visible_only or line.get_visible():
                self._update_line_limits(line)

        for p in self.patches:
            if not visible_only or p.get_visible():
                self._update_patch_limits(p)

        for image in self.images:
            if not visible_only or image.get_visible():
                self._update_image_limits(image) 
Example #27
Source File: _base.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_axes_locator(self, locator):
        """
        Set the axes locator.

        Parameters
        ----------
        locator : Callable[[Axes, Renderer], Bbox]
        """
        self._axes_locator = locator
        self.stale = True 
Example #28
Source File: _base.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _set_position(self, pos, which='both'):
        """
        private version of set_position.  Call this internally
        to get the same functionality of `get_position`, but not
        to take the axis out of the constrained_layout
        hierarchy.
        """
        if not isinstance(pos, mtransforms.BboxBase):
            pos = mtransforms.Bbox.from_bounds(*pos)
        for ax in self._twinned_axes.get_siblings(self):
            if which in ('both', 'active'):
                ax._position.set(pos)
            if which in ('both', 'original'):
                ax._originalPosition.set(pos)
        self.stale = True 
Example #29
Source File: _base.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_window_extent(self, *args, **kwargs):
        """
        get the axes bounding box in display space; *args* and
        *kwargs* are empty
        """
        bbox = self.bbox
        x_pad = 0
        if self.axison and self.xaxis.get_visible():
            x_pad = self.xaxis.get_tick_padding()
        y_pad = 0
        if self.axison and self.yaxis.get_visible():
            y_pad = self.yaxis.get_tick_padding()
        return mtransforms.Bbox([[bbox.x0 - x_pad, bbox.y0 - y_pad],
                                 [bbox.x1 + x_pad, bbox.y1 + y_pad]]) 
Example #30
Source File: backend_gtk3agg.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def on_draw_event(self, widget, ctx):
        """GtkDrawable draw event, like expose_event in GTK 2.X.
        """
        allocation = self.get_allocation()
        w, h = allocation.width, allocation.height

        if not len(self._bbox_queue):
            self._render_figure(w, h)
            Gtk.render_background(
                self.get_style_context(), ctx,
                allocation.x, allocation.y,
                allocation.width, allocation.height)
            bbox_queue = [transforms.Bbox([[0, 0], [w, h]])]
        else:
            bbox_queue = self._bbox_queue

        ctx = backend_cairo._to_context(ctx)

        for bbox in bbox_queue:
            x = int(bbox.x0)
            y = h - int(bbox.y1)
            width = int(bbox.x1) - int(bbox.x0)
            height = int(bbox.y1) - int(bbox.y0)

            buf = cbook._unmultiplied_rgba8888_to_premultiplied_argb32(
                np.asarray(self.copy_from_bbox(bbox)))
            image = cairo.ImageSurface.create_for_data(
                buf.ravel().data, cairo.FORMAT_ARGB32, width, height)
            ctx.set_source_surface(image, x, y)
            ctx.paint()

        if len(self._bbox_queue):
            self._bbox_queue = []

        return False