Python matplotlib.transforms.Affine2D() Examples

The following are 30 code examples of matplotlib.transforms.Affine2D(). 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: text.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def __call__(self, renderer):
        if isinstance(self._artist, Artist):
            bbox = self._artist.get_window_extent(renderer)
            l, b, w, h = bbox.bounds
            xf, yf = self._ref_coord
            x, y = l + w * xf, b + h * yf
        elif isinstance(self._artist, BboxBase):
            l, b, w, h = self._artist.bounds
            xf, yf = self._ref_coord
            x, y = l + w * xf, b + h * yf
        elif isinstance(self._artist, Transform):
            x, y = self._artist.transform_point(self._ref_coord)
        else:
            raise RuntimeError("unknown type")

        sc = self._get_scale(renderer)
        tr = Affine2D().scale(sc, sc).translate(x, y)

        return tr 
Example #2
Source File: textpath.py    From Computable with MIT License 6 votes vote down vote up
def _revalidate_path(self):
        """
        update the path if necessary.

        The path for the text is initially create with the font size
        of FONT_SCALE, and this path is rescaled to other size when
        necessary.

        """
        if (self._invalid or
            (self._cached_vertices is None)):
            tr = Affine2D().scale(
                    self._size / text_to_path.FONT_SCALE,
                    self._size / text_to_path.FONT_SCALE).translate(*self._xy)
            self._cached_vertices = tr.transform(self._vertices)
            self._invalid = False 
Example #3
Source File: patches.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def __init__(self, x, y, dx, dy, width=1.0, **kwargs):
        """
        Draws an arrow, starting at (*x*, *y*), direction and length
        given by (*dx*, *dy*) the width of the arrow is scaled by *width*.

        Valid kwargs are:
        %(Patch)s
        """
        Patch.__init__(self, **kwargs)
        L = np.sqrt(dx ** 2 + dy ** 2) or 1  # account for div by zero
        cx = float(dx) / L
        sx = float(dy) / L

        trans1 = transforms.Affine2D().scale(L, width)
        trans2 = transforms.Affine2D.from_values(cx, sx, -sx, cx, 0.0, 0.0)
        trans3 = transforms.Affine2D().translate(x, y)
        trans = trans1 + trans2 + trans3
        self._patch_transform = trans.frozen() 
Example #4
Source File: patches.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def __init__(self, patch, ox, oy, props=None, **kwargs):
        """
        Create a shadow of the given *patch* offset by *ox*, *oy*.
        *props*, if not *None*, is a patch property update dictionary.
        If *None*, the shadow will have have the same color as the face,
        but darkened.

        kwargs are
        %(Patch)s
        """
        Patch.__init__(self)
        self.patch = patch
        self.props = props
        self._ox, self._oy = ox, oy
        self._shadow_transform = transforms.Affine2D()
        self._update() 
Example #5
Source File: text.py    From Computable with MIT License 6 votes vote down vote up
def update_bbox_position_size(self, renderer):
        """
        Update the location and the size of the bbox. This method
        should be used when the position and size of the bbox needs to
        be updated before actually drawing the bbox.
        """

        # For arrow_patch, use textbox as patchA by default.

        if not isinstance(self.arrow_patch, FancyArrowPatch):
            return

        if self._bbox_patch:
            posx, posy = self._x, self._y

            x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
            self._bbox_patch.set_bounds(0., 0., w_box, h_box)
            theta = np.deg2rad(self.get_rotation())
            tr = mtransforms.Affine2D().rotate(theta)
            tr = tr.translate(posx + x_box, posy + y_box)
            self._bbox_patch.set_transform(tr)
            fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
            self._bbox_patch.set_mutation_scale(fontsize_in_pixel) 
Example #6
Source File: text.py    From Computable with MIT License 6 votes vote down vote up
def __call__(self, renderer):
        if isinstance(self._artist, Artist):
            bbox = self._artist.get_window_extent(renderer)
            l, b, w, h = bbox.bounds
            xf, yf = self._ref_coord
            x, y = l + w * xf, b + h * yf
        elif isinstance(self._artist, BboxBase):
            l, b, w, h = self._artist.bounds
            xf, yf = self._ref_coord
            x, y = l + w * xf, b + h * yf
        elif isinstance(self._artist, Transform):
            x, y = self._artist.transform_point(self._ref_coord)
        else:
            raise RuntimeError("unknown type")

        sc = self._get_scale(renderer)
        tr = Affine2D().scale(sc, sc).translate(x, y)

        return tr 
Example #7
Source File: offsetbox.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def __init__(self, width, height, xdescent=0.,
                 ydescent=0., clip=True):
        """
        *width*, *height* : width and height of the container box.
        *xdescent*, *ydescent* : descent of the box in x- and y-direction.
        """

        super(DrawingArea, self).__init__()

        self.width = width
        self.height = height
        self.xdescent = xdescent
        self.ydescent = ydescent

        self.offset_transform = mtransforms.Affine2D()
        self.offset_transform.clear()
        self.offset_transform.translate(0, 0)

        self.dpi_transform = mtransforms.Affine2D() 
Example #8
Source File: shapes.py    From viznet with MIT License 6 votes vote down vote up
def affine(pp, offset=(0,0), scale=1, angle=0):
    '''rotate path/patch by angle'''
    if isinstance(pp, (np.ndarray, list, tuple)):
        return rotate(pp, angle)*scale + offset
    
    # define the transformation
    _affine = transforms.Affine2D()
    if angle!=0: _affine.rotate(angle)
    if scale!=1: _affine.scale(scale)
    if not np.allclose(offset, 0): _affine.translate(*offset)

    if hasattr(pp, 'vertices'):
        # for path
        pp = pp.transformed(_affine)
    else:
        # for patch
        pp.set_transform(_affine+plt.gca().transData)
    return pp 
Example #9
Source File: text.py    From matplotlib-4-abaqus with MIT License 6 votes vote down vote up
def update_bbox_position_size(self, renderer):
        """
        Update the location and the size of the bbox. This method
        should be used when the position and size of the bbox needs to
        be updated before actually drawing the bbox.
        """

        # For arrow_patch, use textbox as patchA by default.

        if not isinstance(self.arrow_patch, FancyArrowPatch):
            return

        if self._bbox_patch:
            posx, posy = self._x, self._y

            x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
            self._bbox_patch.set_bounds(0., 0., w_box, h_box)
            theta = np.deg2rad(self.get_rotation())
            tr = mtransforms.Affine2D().rotate(theta)
            tr = tr.translate(posx + x_box, posy + y_box)
            self._bbox_patch.set_transform(tr)
            fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
            self._bbox_patch.set_mutation_scale(fontsize_in_pixel) 
Example #10
Source File: patches.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, x, y, dx, dy, width=1.0, **kwargs):
        """
        Draws an arrow, starting at (*x*, *y*), direction and length
        given by (*dx*, *dy*) the width of the arrow is scaled by *width*.

        Valid kwargs are:
        %(Patch)s
        """
        Patch.__init__(self, **kwargs)
        L = np.sqrt(dx ** 2 + dy ** 2) or 1  # account for div by zero
        cx = float(dx) / L
        sx = float(dy) / L

        trans1 = transforms.Affine2D().scale(L, width)
        trans2 = transforms.Affine2D.from_values(cx, sx, -sx, cx, 0.0, 0.0)
        trans3 = transforms.Affine2D().translate(x, y)
        trans = trans1 + trans2 + trans3
        self._patch_transform = trans.frozen() 
Example #11
Source File: offsetbox.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def __init__(self, width, height, xdescent=0.,
                 ydescent=0., clip=False):
        """
        *width*, *height* : width and height of the container box.
        *xdescent*, *ydescent* : descent of the box in x- and y-direction.
        *clip* : Whether to clip the children
        """

        super().__init__()

        self.width = width
        self.height = height
        self.xdescent = xdescent
        self.ydescent = ydescent
        self._clip_children = clip

        self.offset_transform = mtransforms.Affine2D()
        self.offset_transform.clear()
        self.offset_transform.translate(0, 0)

        self.dpi_transform = mtransforms.Affine2D() 
Example #12
Source File: patches.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, patch, ox, oy, props=None, **kwargs):
        """
        Create a shadow of the given *patch* offset by *ox*, *oy*.
        *props*, if not *None*, is a patch property update dictionary.
        If *None*, the shadow will have have the same color as the face,
        but darkened.

        kwargs are
        %(Patch)s
        """
        Patch.__init__(self)
        self.patch = patch
        self.props = props
        self._ox, self._oy = ox, oy
        self._shadow_transform = transforms.Affine2D()
        self._update() 
Example #13
Source File: offsetbox.py    From Computable with MIT License 6 votes vote down vote up
def __init__(self, width, height, xdescent=0.,
                 ydescent=0., clip=True):
        """
        *width*, *height* : width and height of the container box.
        *xdescent*, *ydescent* : descent of the box in x- and y-direction.
        """

        super(DrawingArea, self).__init__()

        self.width = width
        self.height = height
        self.xdescent = xdescent
        self.ydescent = ydescent

        self.offset_transform = mtransforms.Affine2D()
        self.offset_transform.clear()
        self.offset_transform.translate(0, 0)

        self.dpi_transform = mtransforms.Affine2D() 
Example #14
Source File: backend_svg.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _make_flip_transform(self, transform):
        return (transform +
                Affine2D()
                .scale(1.0, -1.0)
                .translate(0.0, self.height)) 
Example #15
Source File: collections.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def draw(self, renderer):
        self._transforms = [
            transforms.Affine2D().rotate(-self._rotation).scale(
                (np.sqrt(x) * self.figure.dpi / 72.0) / np.sqrt(np.pi))
            for x in self._sizes]
        return Collection.draw(self, renderer) 
Example #16
Source File: backend_ps.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def create_hatch(self, hatch):
        sidelen = 72
        if hatch in self._hatches:
            return self._hatches[hatch]
        name = 'H%d' % len(self._hatches)
        linewidth = rcParams['hatch.linewidth']
        pageheight = self.height * 72
        self._pswriter.write("""\
  << /PatternType 1
     /PaintType 2
     /TilingType 2
     /BBox[0 0 %(sidelen)d %(sidelen)d]
     /XStep %(sidelen)d
     /YStep %(sidelen)d

     /PaintProc {
        pop
        %(linewidth)f setlinewidth
""" % locals())
        self._pswriter.write(
            self._convert_path(Path.hatch(hatch), Affine2D().scale(sidelen),
                               simplify=False))
        self._pswriter.write("""\
        fill
        stroke
     } bind
   >>
   matrix
   0.0 %(pageheight)f translate
   makepattern
   /%(name)s exch def
""" % locals())
        self._hatches[hatch] = name
        return name 
Example #17
Source File: text.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def _draw_bbox(self, renderer, posx, posy):

        """ Update the location and the size of the bbox
        (FancyBoxPatch), and draw
        """

        x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
        self._bbox_patch.set_bounds(0., 0., w_box, h_box)
        theta = np.deg2rad(self.get_rotation())
        tr = mtransforms.Affine2D().rotate(theta)
        tr = tr.translate(posx + x_box, posy + y_box)
        self._bbox_patch.set_transform(tr)
        fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
        self._bbox_patch.set_mutation_scale(fontsize_in_pixel)
        self._bbox_patch.draw(renderer) 
Example #18
Source File: backend_pdf.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def writeHatches(self):
        hatchDict = dict()
        sidelen = 72.0
        for hatch_style, name in self.hatchPatterns.items():
            ob = self.reserveObject('hatch pattern')
            hatchDict[name] = ob
            res = {'Procsets':
                   [Name(x) for x in "PDF Text ImageB ImageC ImageI".split()]}
            self.beginStream(
                ob.id, None,
                {'Type': Name('Pattern'),
                 'PatternType': 1, 'PaintType': 1, 'TilingType': 1,
                 'BBox': [0, 0, sidelen, sidelen],
                 'XStep': sidelen, 'YStep': sidelen,
                 'Resources': res,
                 # Change origin to match Agg at top-left.
                 'Matrix': [1, 0, 0, 1, 0, self.height * 72]})

            stroke_rgb, fill_rgb, path = hatch_style
            self.output(stroke_rgb[0], stroke_rgb[1], stroke_rgb[2],
                        Op.setrgb_stroke)
            if fill_rgb is not None:
                self.output(fill_rgb[0], fill_rgb[1], fill_rgb[2],
                            Op.setrgb_nonstroke,
                            0, 0, sidelen, sidelen, Op.rectangle,
                            Op.fill)

            self.output(rcParams['hatch.linewidth'], Op.setlinewidth)

            self.output(*self.pathOperations(
                Path.hatch(path),
                Affine2D().scale(sidelen),
                simplify=False))
            self.output(Op.fill_stroke)

            self.endStream()
        self.writeObject(self.hatchObject, hatchDict) 
Example #19
Source File: backend_cairo.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def set_clip_path(self, path):
        if not path:
            return
        tpath, affine = path.get_transformed_path_and_affine()
        ctx = self.ctx
        ctx.new_path()
        affine = (affine
                  + Affine2D().scale(1, -1).translate(0, self.renderer.height))
        _append_path(ctx, tpath, affine)
        ctx.clip() 
Example #20
Source File: collections.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def draw(self, renderer):
        if self._sizes is not None:
            self._transforms = [
                transforms.Affine2D().scale(
                    (np.sqrt(x) * self.figure.dpi / 72.0))
                for x in self._sizes]
        return Collection.draw(self, renderer) 
Example #21
Source File: backend_bases.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _get_text_path_transform(self, x, y, s, prop, angle, ismath):
        """
        Return the text path and transform.

        Parameters
        ----------
        prop : `matplotlib.font_manager.FontProperties`
            The font property.
        s : str
            The text to be converted.
        ismath : bool or "TeX"
            If True, use mathtext parser. If "TeX", use *usetex* mode.
        """

        text2path = self._text2path
        fontsize = self.points_to_pixels(prop.get_size_in_points())
        verts, codes = text2path.get_text_path(prop, s, ismath=ismath)

        path = Path(verts, codes)
        angle = np.deg2rad(angle)
        if self.flipy():
            transform = Affine2D().scale(fontsize / text2path.FONT_SCALE,
                                         fontsize / text2path.FONT_SCALE)
            transform = transform.rotate(angle).translate(x, self.height - y)
        else:
            transform = Affine2D().scale(fontsize / text2path.FONT_SCALE,
                                         fontsize / text2path.FONT_SCALE)
            transform = transform.rotate(angle).translate(x, y)

        return path, transform 
Example #22
Source File: backend_cairo.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def draw_path(self, gc, path, transform, rgbFace=None):
        # docstring inherited
        ctx = gc.ctx
        # Clip the path to the actual rendering extents if it isn't filled.
        clip = (ctx.clip_extents()
                if rgbFace is None and gc.get_hatch() is None
                else None)
        transform = (transform
                     + Affine2D().scale(1, -1).translate(0, self.height))
        ctx.new_path()
        _append_path(ctx, path, transform, clip)
        self._fill_and_stroke(
            ctx, rgbFace, gc.get_alpha(), gc.get_forced_alpha()) 
Example #23
Source File: text.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def __call__(self, renderer):
        '''
        Return the offset transform.

        Parameters
        ----------
        renderer : `RendererBase`
            The renderer to use to compute the offset

        Returns
        -------
        transform : `Transform`
            Maps (x, y) in pixel or point units to screen units
            relative to the given artist.
        '''
        if isinstance(self._artist, Artist):
            bbox = self._artist.get_window_extent(renderer)
            l, b, w, h = bbox.bounds
            xf, yf = self._ref_coord
            x, y = l + w * xf, b + h * yf
        elif isinstance(self._artist, BboxBase):
            l, b, w, h = self._artist.bounds
            xf, yf = self._ref_coord
            x, y = l + w * xf, b + h * yf
        elif isinstance(self._artist, Transform):
            x, y = self._artist.transform_point(self._ref_coord)
        else:
            raise RuntimeError("unknown type")

        sc = self._get_scale(renderer)
        tr = Affine2D().scale(sc, sc).translate(x, y)

        return tr 
Example #24
Source File: text.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _draw_bbox(self, renderer, posx, posy):
        """
        Update the location and size of the bbox (`.patches.FancyBboxPatch`),
        and draw.
        """

        x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
        self._bbox_patch.set_bounds(0., 0., w_box, h_box)
        theta = np.deg2rad(self.get_rotation())
        tr = Affine2D().rotate(theta)
        tr = tr.translate(posx + x_box, posy + y_box)
        self._bbox_patch.set_transform(tr)
        fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
        self._bbox_patch.set_mutation_scale(fontsize_in_pixel)
        self._bbox_patch.draw(renderer) 
Example #25
Source File: text.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def update_bbox_position_size(self, renderer):
        """
        Update the location and the size of the bbox.

        This method should be used when the position and size of the bbox needs
        to be updated before actually drawing the bbox.
        """

        if self._bbox_patch:

            trans = self.get_transform()

            # don't use self.get_unitless_position here, which refers to text
            # position in Text, and dash position in TextWithDash:
            posx = float(self.convert_xunits(self._x))
            posy = float(self.convert_yunits(self._y))

            posx, posy = trans.transform_point((posx, posy))

            x_box, y_box, w_box, h_box = _get_textbox(self, renderer)
            self._bbox_patch.set_bounds(0., 0., w_box, h_box)
            theta = np.deg2rad(self.get_rotation())
            tr = Affine2D().rotate(theta)
            tr = tr.translate(posx + x_box, posy + y_box)
            self._bbox_patch.set_transform(tr)
            fontsize_in_pixel = renderer.points_to_pixels(self.get_size())
            self._bbox_patch.set_mutation_scale(fontsize_in_pixel) 
Example #26
Source File: text.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _get_textbox(text, renderer):
    """
    Calculate the bounding box of the text. Unlike
    :meth:`matplotlib.text.Text.get_extents` method, The bbox size of
    the text before the rotation is calculated.
    """
    # TODO : This function may move into the Text class as a method. As a
    # matter of fact, The information from the _get_textbox function
    # should be available during the Text._get_layout() call, which is
    # called within the _get_textbox. So, it would better to move this
    # function as a method with some refactoring of _get_layout method.

    projected_xs = []
    projected_ys = []

    theta = np.deg2rad(text.get_rotation())
    tr = Affine2D().rotate(-theta)

    _, parts, d = text._get_layout(renderer)

    for t, wh, x, y in parts:
        w, h = wh

        xt1, yt1 = tr.transform_point((x, y))
        yt1 -= d
        xt2, yt2 = xt1 + w, yt1 + h

        projected_xs.extend([xt1, xt2])
        projected_ys.extend([yt1, yt2])

    xt_box, yt_box = min(projected_xs), min(projected_ys)
    w_box, h_box = max(projected_xs) - xt_box, max(projected_ys) - yt_box

    x_box, y_box = Affine2D().rotate(theta).transform_point((xt_box, yt_box))

    return x_box, y_box, w_box, h_box 
Example #27
Source File: polar.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_matrix(self):
        # docstring inherited
        if self._invalid:
            limits_scaled = self._limits.transformed(self._scale_transform)
            yscale = limits_scaled.ymax - limits_scaled.ymin
            affine = mtransforms.Affine2D() \
                .scale(0.5 / yscale) \
                .translate(0.5, 0.5)
            self._mtx = affine.get_matrix()
            self._inverted = None
            self._invalid = 0
        return self._mtx 
Example #28
Source File: geo.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _get_affine_transform(self):
        return Affine2D() \
            .scale(0.25) \
            .translate(0.5, 0.5) 
Example #29
Source File: geo.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _get_affine_transform(self):
        transform = self._get_core_transform(1)
        xscale, _ = transform.transform_point((np.pi, 0))
        _, yscale = transform.transform_point((0, np.pi / 2))
        return Affine2D() \
            .scale(0.5 / xscale, 0.5 / yscale) \
            .translate(0.5, 0.5) 
Example #30
Source File: backend_kivy.py    From garden.matplotlib with MIT License 5 votes vote down vote up
def draw_markers(self, gc, marker_path, marker_trans, path,
        trans, rgbFace=None):
        '''Markers graphics instructions are stored on a dictionary and
           hashed through graphics context and rgbFace values. If a marker_path
           with the corresponding graphics context exist then the instructions
           are pulled from the markers dictionary.
        '''
        if not len(path.vertices):
            return
        # get a string representation of the path
        path_data = self._convert_path(
            marker_path,
            marker_trans + Affine2D().scale(1.0, -1.0),
            simplify=False)
        # get a string representation of the graphics context and rgbFace.
        style = str(gc._get_style_dict(rgbFace))
        dictkey = (path_data, str(style))
        # check whether this marker has been created before.
        list_instructions = self._markers.get(dictkey)
        # creating a list of instructions for the specific marker.
        if list_instructions is None:
            if _mpl_ge_2_0:
                polygons = marker_path.to_polygons(marker_trans, closed_only=False)
            else:
                polygons = marker_path.to_polygons(marker_trans)
            self._markers[dictkey] = self.get_path_instructions(gc,
                                        polygons, rgbFace=rgbFace)
        # Traversing all the positions where a marker should be rendered
        for vertices, codes in path.iter_segments(trans, simplify=False):
            if len(vertices):
                x, y = vertices[-2:]
                for widget, instructions in self._markers[dictkey]:
                    widget.canvas.add(PushMatrix())
                    widget.canvas.add(Translate(x, y))
                    widget.canvas.add(instructions)
                    widget.canvas.add(PopMatrix())