Python matplotlib.patches.FancyBboxPatch() Examples

The following are code examples for showing how to use matplotlib.patches.FancyBboxPatch(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: python3_ios   Author: holzschu   File: fancybox_demo.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test1(ax):

    # a fancy box with round corners. pad=0.1
    p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
                             abs(bb.width), abs(bb.height),
                             boxstyle="round,pad=0.1",
                             fc=(1., .8, 1.),
                             ec=(1., 0.5, 1.))

    ax.add_patch(p_fancy)

    ax.text(0.1, 0.8,
            r' boxstyle="round,pad=0.1"',
            size=10, transform=ax.transAxes)

    # draws control points for the fancy box.
    # l = p_fancy.get_path().vertices
    # ax.plot(l[:,0], l[:,1], ".")

    # draw the original bbox in black
    draw_bbox(ax, bb) 
Example 2
Project: python3_ios   Author: holzschu   File: fancybox_demo.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test3(ax):

    # mutation_scale determine overall scale of the mutation,
    # i.e. both pad and rounding_size is scaled according to this
    # value.
    p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
                             abs(bb.width), abs(bb.height),
                             boxstyle="round,pad=0.1",
                             mutation_scale=2.,
                             fc=(1., .8, 1.),
                             ec=(1., 0.5, 1.))

    ax.add_patch(p_fancy)

    ax.text(0.1, 0.8,
            ' boxstyle="round,pad=0.1"\n mutation_scale=2',
            size=10, transform=ax.transAxes)

    # draws control points for the fancy box.
    # l = p_fancy.get_path().vertices
    # ax.plot(l[:,0], l[:,1], ".")

    draw_bbox(ax, bb) 
Example 3
Project: LaserTOF   Author: kyleuckert   File: offsetbox.py    MIT License 5 votes vote down vote up
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
        """
        *pad* : boundary pad

        .. note::
          *pad* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """

        super(PaddedBox, self).__init__()

        self.pad = pad
        self._children = [child]

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=1,  # self.prop.get_size_in_points(),
            snap=True
            )

        self.patch.set_boxstyle("square", pad=0)

        if patch_attrs is not None:
            self.patch.update(patch_attrs)

        self._drawFrame = draw_frame 
Example 4
Project: LaserTOF   Author: kyleuckert   File: text.py    MIT License 5 votes vote down vote up
def get_bbox_patch(self):
        """
        Return the bbox Patch object. Returns None if the
        FancyBboxPatch is not made.
        """
        return self._bbox_patch 
Example 5
Project: LaserTOF   Author: kyleuckert   File: text.py    MIT License 5 votes vote down vote up
def _draw_bbox(self, renderer, posx, posy):

        """ Update the location and the size of the bbox
        (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 = 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 6
Project: ble5-nrf52-mac   Author: tomasero   File: offsetbox.py    MIT License 5 votes vote down vote up
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
        """
        *pad* : boundary pad

        .. note::
          *pad* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """

        super().__init__()

        self.pad = pad
        self._children = [child]

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=1,  # self.prop.get_size_in_points(),
            snap=True
            )

        self.patch.set_boxstyle("square", pad=0)

        if patch_attrs is not None:
            self.patch.update(patch_attrs)

        self._drawFrame = draw_frame 
Example 7
Project: Computable   Author: ktraunmueller   File: offsetbox.py    MIT License 5 votes vote down vote up
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
        """
        *pad* : boundary pad

        .. note::
          *pad* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """

        super(PaddedBox, self).__init__()

        self.pad = pad
        self._children = [child]

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=1,  # self.prop.get_size_in_points(),
            snap=True
            )

        self.patch.set_boxstyle("square", pad=0)

        if patch_attrs is not None:
            self.patch.update(patch_attrs)

        self._drawFrame = draw_frame 
Example 8
Project: Computable   Author: ktraunmueller   File: text.py    MIT License 5 votes vote down vote up
def set_bbox(self, rectprops):
        """
        Draw a bounding box around self.  rectprops are any settable
        properties for a rectangle, eg facecolor='red', alpha=0.5.

          t.set_bbox(dict(facecolor='red', alpha=0.5))

        If rectprops has "boxstyle" key. A FancyBboxPatch
        is initialized with rectprops and will be drawn. The mutation
        scale of the FancyBboxPath is set to the fontsize.

        ACCEPTS: rectangle prop dict
        """

        # The self._bbox_patch object is created only if rectprops has
        # boxstyle key. Otherwise, self._bbox will be set to the
        # rectprops and the bbox will be drawn using bbox_artist
        # function. This is to keep the backward compatibility.

        if rectprops is not None and "boxstyle" in rectprops:
            props = rectprops.copy()
            boxstyle = props.pop("boxstyle")
            bbox_transmuter = props.pop("bbox_transmuter", None)

            self._bbox_patch = FancyBboxPatch(
                                    (0., 0.),
                                    1., 1.,
                                    boxstyle=boxstyle,
                                    bbox_transmuter=bbox_transmuter,
                                    transform=mtransforms.IdentityTransform(),
                                    **props)
            self._bbox = None
        else:
            self._bbox_patch = None
            self._bbox = rectprops 
Example 9
Project: Computable   Author: ktraunmueller   File: text.py    MIT License 5 votes vote down vote up
def get_bbox_patch(self):
        """
        Return the bbox Patch object. Returns None if the the
        FancyBboxPatch is not made.
        """
        return self._bbox_patch 
Example 10
Project: viznet   Author: GiggleLiu   File: edgenode.py    MIT License 5 votes vote down vote up
def height(self):
        shape = self.brush.style[1]
        if isinstance(self.obj, plt.Circle):
            return self.obj.radius * 2
        elif isinstance(self.obj, plt.Rectangle):
            return self.obj.get_height()
        elif isinstance(self.obj, patches.FancyBboxPatch):
            return self.obj.get_height() + 2*self.obj.get_boxstyle().pad
        elif isinstance(self.obj, (plt.Polygon, patches.PathPatch)):
            y = self.path[:,1]
            return y.max() - y.min()
        else:
            raise 
Example 11
Project: viznet   Author: GiggleLiu   File: edgenode.py    MIT License 5 votes vote down vote up
def width(self):
        shape = self.brush.style[1]
        if isinstance(self.obj, plt.Circle):
            return self.obj.radius * 2
        elif isinstance(self.obj, plt.Rectangle):
            return self.obj.get_width()
        elif isinstance(self.obj, patches.FancyBboxPatch):
            return self.obj.get_width() + 2*self.obj.get_boxstyle().pad
        elif isinstance(self.obj, (plt.Polygon, patches.PathPatch)):
            x = self.path[:,0]
            return x.max() - x.min()
        else:
            raise 
Example 12
Project: viznet   Author: GiggleLiu   File: shapes.py    MIT License 5 votes vote down vote up
def rectangle(xy, size, angle, roundness, **kwargs):
    '''width is relative width with respect to height.'''
    if np.ndim(size) == 0:
        size = (size, size)
    width, height = 2*size[0], 2*size[1]
    xy_ = xy[0] - width / 2., xy[1] - height / 2.
    if roundness!=0:
        pad = roundness
        c = patches.FancyBboxPatch(xy_+np.array([pad,pad]), width-pad*2, height-pad*2,
                          boxstyle=patches.BoxStyle("Round", pad=pad), **_fix(kwargs))
    else:
        c = patches.Rectangle(xy_, width, height, **_fix(kwargs))
    return [c]

##########################  Derived types  ############################# 
Example 13
Project: ms_deisotope   Author: mobiusklein   File: map_viz.py    Apache License 2.0 5 votes vote down vote up
def draw_features(features, ax=None, alpha=0.65, width=2e-5, **kwargs):
    if ax is None:
        fig, ax = plt.subplots(1)

    ellipses = []
    kwargs.setdefault("lw", 0.05)
    lw = kwargs.get("linewidth", kwargs.get("lw"))
    for feat in features:
        if feat is None:
            continue
        center = (feat.end_time + feat.start_time) / 2.
        height = feat.end_time - feat.start_time

        center_mz = feat.mz
        mz_width = center_mz * width

        ellipses.append(
            FancyBboxPatch((feat.mz - mz_width / 4., center - height / 2.), width=mz_width / 2., height=height,
                           boxstyle=mpatches.BoxStyle.Round(pad=mz_width / 2.)))

    for ell in ellipses:
        ell.set_alpha(alpha)
        ell.set_facecolor("blue")
        ell.set_edgecolor("blue")
        ell.set_linewidth(lw)
        ax.add_artist(ell)

    ax.set_xlim(
        min(features, key=lambda x: x.mz if x is not None else float('inf')).mz - 1,
        max(features, key=lambda x: x.mz if x is not None else -float('inf')).mz + 1)
    ax.set_ylim(
        min(features, key=lambda x: x.start_time if x is not None else float('inf')).start_time - 1,
        max(features, key=lambda x: x.end_time if x is not None else -float('inf')).end_time + 1)
    return ax 
Example 14
Project: neural-network-animation   Author: miloharper   File: offsetbox.py    MIT License 5 votes vote down vote up
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
        """
        *pad* : boundary pad

        .. note::
          *pad* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """

        super(PaddedBox, self).__init__()

        self.pad = pad
        self._children = [child]

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=1,  # self.prop.get_size_in_points(),
            snap=True
            )

        self.patch.set_boxstyle("square", pad=0)

        if patch_attrs is not None:
            self.patch.update(patch_attrs)

        self._drawFrame = draw_frame 
Example 15
Project: neural-network-animation   Author: miloharper   File: text.py    MIT License 5 votes vote down vote up
def set_bbox(self, rectprops):
        """
        Draw a bounding box around self.  rectprops are any settable
        properties for a rectangle, e.g., facecolor='red', alpha=0.5.

          t.set_bbox(dict(facecolor='red', alpha=0.5))

        If rectprops has "boxstyle" key. A FancyBboxPatch
        is initialized with rectprops and will be drawn. The mutation
        scale of the FancyBboxPath is set to the fontsize.

        ACCEPTS: rectangle prop dict
        """

        # The self._bbox_patch object is created only if rectprops has
        # boxstyle key. Otherwise, self._bbox will be set to the
        # rectprops and the bbox will be drawn using bbox_artist
        # function. This is to keep the backward compatibility.

        if rectprops is not None and "boxstyle" in rectprops:
            props = rectprops.copy()
            boxstyle = props.pop("boxstyle")
            bbox_transmuter = props.pop("bbox_transmuter", None)

            self._bbox_patch = FancyBboxPatch(
                                    (0., 0.),
                                    1., 1.,
                                    boxstyle=boxstyle,
                                    bbox_transmuter=bbox_transmuter,
                                    transform=mtransforms.IdentityTransform(),
                                    **props)
            self._bbox = None
        else:
            self._bbox_patch = None
            self._bbox = rectprops

        self._update_clip_properties() 
Example 16
Project: neural-network-animation   Author: miloharper   File: text.py    MIT License 5 votes vote down vote up
def get_bbox_patch(self):
        """
        Return the bbox Patch object. Returns None if the the
        FancyBboxPatch is not made.
        """
        return self._bbox_patch 
Example 17
Project: GraphicDesignPatternByPython   Author: Relph1119   File: offsetbox.py    MIT License 5 votes vote down vote up
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
        """
        *pad* : boundary pad

        .. note::
          *pad* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """

        super().__init__()

        self.pad = pad
        self._children = [child]

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=1,  # self.prop.get_size_in_points(),
            snap=True
            )

        self.patch.set_boxstyle("square", pad=0)

        if patch_attrs is not None:
            self.patch.update(patch_attrs)

        self._drawFrame = draw_frame 
Example 18
Project: python3_ios   Author: holzschu   File: fancybox_demo.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw_bbox(ax, bb):
    # boxstyle=square with pad=0, i.e. bbox itself.
    p_bbox = FancyBboxPatch((bb.xmin, bb.ymin),
                            abs(bb.width), abs(bb.height),
                            boxstyle="square,pad=0.",
                            ec="k", fc="none", zorder=10.,
                            )
    ax.add_patch(p_bbox) 
Example 19
Project: python3_ios   Author: holzschu   File: fancybox_demo.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test2(ax):

    # bbox=round has two optional argument. pad and rounding_size.
    # They can be set during the initialization.
    p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
                             abs(bb.width), abs(bb.height),
                             boxstyle="round,pad=0.1",
                             fc=(1., .8, 1.),
                             ec=(1., 0.5, 1.))

    ax.add_patch(p_fancy)

    # boxstyle and its argument can be later modified with
    # set_boxstyle method. Note that the old attributes are simply
    # forgotten even if the boxstyle name is same.

    p_fancy.set_boxstyle("round,pad=0.1, rounding_size=0.2")
    # or
    # p_fancy.set_boxstyle("round", pad=0.1, rounding_size=0.2)

    ax.text(0.1, 0.8,
            ' boxstyle="round,pad=0.1\n rounding_size=0.2"',
            size=10, transform=ax.transAxes)

    # draws control points for the fancy box.
    # l = p_fancy.get_path().vertices
    # ax.plot(l[:,0], l[:,1], ".")

    draw_bbox(ax, bb) 
Example 20
Project: python3_ios   Author: holzschu   File: fancybox_demo.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test4(ax):

    # When the aspect ratio of the axes is not 1, the fancy box may
    # not be what you expected (green)

    p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
                             abs(bb.width), abs(bb.height),
                             boxstyle="round,pad=0.2",
                             fc="none",
                             ec=(0., .5, 0.), zorder=4)

    ax.add_patch(p_fancy)

    # You can compensate this by setting the mutation_aspect (pink).
    p_fancy = FancyBboxPatch((bb.xmin, bb.ymin),
                             abs(bb.width), abs(bb.height),
                             boxstyle="round,pad=0.3",
                             mutation_aspect=.5,
                             fc=(1., 0.8, 1.),
                             ec=(1., 0.5, 1.))

    ax.add_patch(p_fancy)

    ax.text(0.1, 0.8,
            ' boxstyle="round,pad=0.3"\n mutation_aspect=.5',
            size=10, transform=ax.transAxes)

    draw_bbox(ax, bb) 
Example 21
Project: Programming-for-Non-Technical-Roles-   Author: PacktPublishing   File: offsetbox.py    MIT License 5 votes vote down vote up
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
        """
        *pad* : boundary pad

        .. note::
          *pad* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """

        super(PaddedBox, self).__init__()

        self.pad = pad
        self._children = [child]

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=1,  # self.prop.get_size_in_points(),
            snap=True
            )

        self.patch.set_boxstyle("square", pad=0)

        if patch_attrs is not None:
            self.patch.update(patch_attrs)

        self._drawFrame = draw_frame 
Example 22
Project: linear_neuron   Author: uglyboxer   File: offsetbox.py    MIT License 5 votes vote down vote up
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
        """
        *pad* : boundary pad

        .. note::
          *pad* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """

        super(PaddedBox, self).__init__()

        self.pad = pad
        self._children = [child]

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=1,  # self.prop.get_size_in_points(),
            snap=True
            )

        self.patch.set_boxstyle("square", pad=0)

        if patch_attrs is not None:
            self.patch.update(patch_attrs)

        self._drawFrame = draw_frame 
Example 23
Project: linear_neuron   Author: uglyboxer   File: text.py    MIT License 5 votes vote down vote up
def set_bbox(self, rectprops):
        """
        Draw a bounding box around self.  rectprops are any settable
        properties for a rectangle, e.g., facecolor='red', alpha=0.5.

          t.set_bbox(dict(facecolor='red', alpha=0.5))

        If rectprops has "boxstyle" key. A FancyBboxPatch
        is initialized with rectprops and will be drawn. The mutation
        scale of the FancyBboxPath is set to the fontsize.

        ACCEPTS: rectangle prop dict
        """

        # The self._bbox_patch object is created only if rectprops has
        # boxstyle key. Otherwise, self._bbox will be set to the
        # rectprops and the bbox will be drawn using bbox_artist
        # function. This is to keep the backward compatibility.

        if rectprops is not None and "boxstyle" in rectprops:
            props = rectprops.copy()
            boxstyle = props.pop("boxstyle")
            bbox_transmuter = props.pop("bbox_transmuter", None)

            self._bbox_patch = FancyBboxPatch(
                                    (0., 0.),
                                    1., 1.,
                                    boxstyle=boxstyle,
                                    bbox_transmuter=bbox_transmuter,
                                    transform=mtransforms.IdentityTransform(),
                                    **props)
            self._bbox = None
        else:
            self._bbox_patch = None
            self._bbox = rectprops

        self._update_clip_properties() 
Example 24
Project: linear_neuron   Author: uglyboxer   File: text.py    MIT License 5 votes vote down vote up
def get_bbox_patch(self):
        """
        Return the bbox Patch object. Returns None if the the
        FancyBboxPatch is not made.
        """
        return self._bbox_patch 
Example 25
Project: ImageFusion   Author: pfchai   File: offsetbox.py    MIT License 5 votes vote down vote up
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
        """
        *pad* : boundary pad

        .. note::
          *pad* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """

        super(PaddedBox, self).__init__()

        self.pad = pad
        self._children = [child]

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=1,  # self.prop.get_size_in_points(),
            snap=True
            )

        self.patch.set_boxstyle("square", pad=0)

        if patch_attrs is not None:
            self.patch.update(patch_attrs)

        self._drawFrame = draw_frame 
Example 26
Project: ImageFusion   Author: pfchai   File: text.py    MIT License 5 votes vote down vote up
def set_bbox(self, rectprops):
        """
        Draw a bounding box around self.  rectprops are any settable
        properties for a rectangle, e.g., facecolor='red', alpha=0.5.

          t.set_bbox(dict(facecolor='red', alpha=0.5))

        If rectprops has "boxstyle" key. A FancyBboxPatch
        is initialized with rectprops and will be drawn. The mutation
        scale of the FancyBboxPath is set to the fontsize.

        ACCEPTS: rectangle prop dict
        """

        # The self._bbox_patch object is created only if rectprops has
        # boxstyle key. Otherwise, self._bbox will be set to the
        # rectprops and the bbox will be drawn using bbox_artist
        # function. This is to keep the backward compatibility.

        if rectprops is not None and "boxstyle" in rectprops:
            props = rectprops.copy()
            boxstyle = props.pop("boxstyle")
            bbox_transmuter = props.pop("bbox_transmuter", None)

            self._bbox_patch = FancyBboxPatch(
                                    (0., 0.),
                                    1., 1.,
                                    boxstyle=boxstyle,
                                    bbox_transmuter=bbox_transmuter,
                                    transform=mtransforms.IdentityTransform(),
                                    **props)
            self._bbox = None
        else:
            self._bbox_patch = None
            self._bbox = rectprops

        self._update_clip_properties() 
Example 27
Project: ImageFusion   Author: pfchai   File: text.py    MIT License 5 votes vote down vote up
def get_bbox_patch(self):
        """
        Return the bbox Patch object. Returns None if the the
        FancyBboxPatch is not made.
        """
        return self._bbox_patch 
Example 28
Project: Blackjack-Tracker   Author: martinabeleda   File: offsetbox.py    MIT License 5 votes vote down vote up
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
        """
        *pad* : boundary pad

        .. note::
          *pad* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """

        super(PaddedBox, self).__init__()

        self.pad = pad
        self._children = [child]

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=1,  # self.prop.get_size_in_points(),
            snap=True
            )

        self.patch.set_boxstyle("square", pad=0)

        if patch_attrs is not None:
            self.patch.update(patch_attrs)

        self._drawFrame = draw_frame 
Example 29
Project: Blackjack-Tracker   Author: martinabeleda   File: text.py    MIT License 5 votes vote down vote up
def get_bbox_patch(self):
        """
        Return the bbox Patch object. Returns None if the
        FancyBboxPatch is not made.
        """
        return self._bbox_patch 
Example 30
Project: Blackjack-Tracker   Author: martinabeleda   File: text.py    MIT License 5 votes vote down vote up
def _draw_bbox(self, renderer, posx, posy):

        """ Update the location and the size of the bbox
        (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 = 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 31
Project: cnidaria   Author: sauloal   File: offsetbox.py    MIT License 5 votes vote down vote up
def __init__(self, child, pad=None, draw_frame=False, patch_attrs=None):
        """
        *pad* : boundary pad

        .. note::
          *pad* need to given in points and will be
          scale with the renderer dpi, while *width* and *height*
          need to be in pixels.
        """

        super(PaddedBox, self).__init__()

        self.pad = pad
        self._children = [child]

        self.patch = FancyBboxPatch(
            xy=(0.0, 0.0), width=1., height=1.,
            facecolor='w', edgecolor='k',
            mutation_scale=1,  # self.prop.get_size_in_points(),
            snap=True
            )

        self.patch.set_boxstyle("square", pad=0)

        if patch_attrs is not None:
            self.patch.update(patch_attrs)

        self._drawFrame = draw_frame 
Example 32
Project: cnidaria   Author: sauloal   File: text.py    MIT License 5 votes vote down vote up
def set_bbox(self, rectprops):
        """
        Draw a bounding box around self.  rectprops are any settable
        properties for a rectangle, e.g., facecolor='red', alpha=0.5.

          t.set_bbox(dict(facecolor='red', alpha=0.5))

        If rectprops has "boxstyle" key. A FancyBboxPatch
        is initialized with rectprops and will be drawn. The mutation
        scale of the FancyBboxPath is set to the fontsize.

        ACCEPTS: rectangle prop dict
        """

        # The self._bbox_patch object is created only if rectprops has
        # boxstyle key. Otherwise, self._bbox will be set to the
        # rectprops and the bbox will be drawn using bbox_artist
        # function. This is to keep the backward compatibility.

        if rectprops is not None and "boxstyle" in rectprops:
            props = rectprops.copy()
            boxstyle = props.pop("boxstyle")
            bbox_transmuter = props.pop("bbox_transmuter", None)

            self._bbox_patch = FancyBboxPatch(
                                    (0., 0.),
                                    1., 1.,
                                    boxstyle=boxstyle,
                                    bbox_transmuter=bbox_transmuter,
                                    transform=mtransforms.IdentityTransform(),
                                    **props)
            self._bbox = None
        else:
            self._bbox_patch = None
            self._bbox = rectprops

        self._update_clip_properties() 
Example 33
Project: cnidaria   Author: sauloal   File: text.py    MIT License 5 votes vote down vote up
def get_bbox_patch(self):
        """
        Return the bbox Patch object. Returns None if the the
        FancyBboxPatch is not made.
        """
        return self._bbox_patch 
Example 34
Project: LaserTOF   Author: kyleuckert   File: text.py    MIT License 4 votes vote down vote up
def __init__(self,
                 x=0, y=0, text='',
                 color=None,           # defaults to rc params
                 verticalalignment='baseline',
                 horizontalalignment='left',
                 multialignment=None,
                 fontproperties=None,  # defaults to FontProperties()
                 rotation=None,
                 linespacing=None,
                 rotation_mode=None,
                 usetex=None,          # defaults to rcParams['text.usetex']
                 wrap=False,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.text.Text` instance at *x*, *y*
        with string *text*.

        Valid kwargs are
        %(Text)s
        """

        Artist.__init__(self)
        self._x, self._y = x, y

        if color is None:
            color = rcParams['text.color']
        if fontproperties is None:
            fontproperties = FontProperties()
        elif is_string_like(fontproperties):
            fontproperties = FontProperties(fontproperties)

        self.set_text(text)
        self.set_color(color)
        self.set_usetex(usetex)
        self.set_wrap(wrap)
        self._verticalalignment = verticalalignment
        self._horizontalalignment = horizontalalignment
        self._multialignment = multialignment
        self._rotation = rotation
        self._fontproperties = fontproperties
        self._bbox_patch = None  # a FancyBboxPatch instance
        self._renderer = None
        if linespacing is None:
            linespacing = 1.2   # Maybe use rcParam later.
        self._linespacing = linespacing
        self.set_rotation_mode(rotation_mode)
        self.update(kwargs) 
Example 35
Project: LaserTOF   Author: kyleuckert   File: text.py    MIT License 4 votes vote down vote up
def set_bbox(self, rectprops):
        """
        Draw a bounding box around self.  rectprops are any settable
        properties for a FancyBboxPatch, e.g., facecolor='red', alpha=0.5.

          t.set_bbox(dict(facecolor='red', alpha=0.5))

        The default boxstyle is 'square'. The mutation
        scale of the FancyBboxPatch is set to the fontsize.

        ACCEPTS: FancyBboxPatch prop dict
        """

        if rectprops is not None:
            props = rectprops.copy()
            boxstyle = props.pop("boxstyle", None)
            pad = props.pop("pad", None)
            if boxstyle is None:
                boxstyle = "square"
                if pad is None:
                    pad = 4  # points
                pad /= self.get_size()  # to fraction of font size
            else:
                if pad is None:
                    pad = 0.3

            # boxstyle could be a callable or a string
            if is_string_like(boxstyle) and "pad" not in boxstyle:
                boxstyle += ",pad=%0.2f" % pad

            bbox_transmuter = props.pop("bbox_transmuter", None)

            self._bbox_patch = FancyBboxPatch(
                                    (0., 0.),
                                    1., 1.,
                                    boxstyle=boxstyle,
                                    bbox_transmuter=bbox_transmuter,
                                    transform=mtransforms.IdentityTransform(),
                                    **props)
        else:
            self._bbox_patch = None

        self._update_clip_properties() 
Example 36
Project: Computable   Author: ktraunmueller   File: text.py    MIT License 4 votes vote down vote up
def __init__(self,
                 x=0, y=0, text='',
                 color=None,           # defaults to rc params
                 verticalalignment='baseline',
                 horizontalalignment='left',
                 multialignment=None,
                 fontproperties=None,  # defaults to FontProperties()
                 rotation=None,
                 linespacing=None,
                 rotation_mode=None,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.text.Text` instance at *x*, *y*
        with string *text*.

        Valid kwargs are
        %(Text)s
        """

        Artist.__init__(self)
        self._x, self._y = x, y

        if color is None:
            color = rcParams['text.color']
        if fontproperties is None:
            fontproperties = FontProperties()
        elif is_string_like(fontproperties):
            fontproperties = FontProperties(fontproperties)

        self.set_text(text)
        self.set_color(color)
        self._verticalalignment = verticalalignment
        self._horizontalalignment = horizontalalignment
        self._multialignment = multialignment
        self._rotation = rotation
        self._fontproperties = fontproperties
        self._bbox = None
        self._bbox_patch = None  # a FancyBboxPatch instance
        self._renderer = None
        if linespacing is None:
            linespacing = 1.2   # Maybe use rcParam later.
        self._linespacing = linespacing
        self.set_rotation_mode(rotation_mode)
        self.update(kwargs)
        #self.set_bbox(dict(pad=0)) 
Example 37
Project: ms_deisotope   Author: mobiusklein   File: map_viz.py    Apache License 2.0 4 votes vote down vote up
def draw_feature_sets(feature_sets, ax=None, alpha=0.65, width=2e-5, **kwargs):
    if ax is None:
        fig, ax = plt.subplots(1)

    kwargs.setdefault("lw", 0.05)
    lw = kwargs.get("linewidth", kwargs.get("lw"))

    features = []
    ellipse_sets = []
    for feature_set in feature_sets:
        ellipses = []
        for feat in feature_set:
            if feat is None:
                continue
            center = (feat.end_time + feat.start_time) / 2.
            height = feat.end_time - feat.start_time

            center_mz = feat.mz
            mz_width = center_mz * width

            ellipses.append(
                FancyBboxPatch((feat.mz - mz_width / 4., center - height / 2.),
                               width=mz_width / 2., height=height,
                               boxstyle=mpatches.BoxStyle.Round(pad=mz_width / 2.)))
            features.append(feat)
        ellipse_sets.append(ellipses)

    for ellipses in ellipse_sets:
        color = np.random.rand(3)
        for ell in ellipses:
            ell.set_alpha(alpha)
            ell.set_facecolor(color)
            ell.set_edgecolor(color)
            ell.set_linewidth(lw)
            ax.add_artist(ell)

    ax.set_xlim(
        min(features, key=lambda x: x.mz if x is not None else float('inf')).mz - 1,
        max(features, key=lambda x: x.mz if x is not None else -float('inf')).mz + 1)
    ax.set_ylim(
        min(features, key=lambda x: x.start_time if x is not None else float('inf')).start_time - 1,
        max(features, key=lambda x: x.end_time if x is not None else -float('inf')).end_time + 1)
    return ax 
Example 38
Project: neural-network-animation   Author: miloharper   File: text.py    MIT License 4 votes vote down vote up
def __init__(self,
                 x=0, y=0, text='',
                 color=None,           # defaults to rc params
                 verticalalignment='baseline',
                 horizontalalignment='left',
                 multialignment=None,
                 fontproperties=None,  # defaults to FontProperties()
                 rotation=None,
                 linespacing=None,
                 rotation_mode=None,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.text.Text` instance at *x*, *y*
        with string *text*.

        Valid kwargs are
        %(Text)s
        """

        Artist.__init__(self)
        self._x, self._y = x, y

        if color is None:
            color = rcParams['text.color']
        if fontproperties is None:
            fontproperties = FontProperties()
        elif is_string_like(fontproperties):
            fontproperties = FontProperties(fontproperties)

        self.set_text(text)
        self.set_color(color)
        self._verticalalignment = verticalalignment
        self._horizontalalignment = horizontalalignment
        self._multialignment = multialignment
        self._rotation = rotation
        self._fontproperties = fontproperties
        self._bbox = None
        self._bbox_patch = None  # a FancyBboxPatch instance
        self._renderer = None
        if linespacing is None:
            linespacing = 1.2   # Maybe use rcParam later.
        self._linespacing = linespacing
        self.set_rotation_mode(rotation_mode)
        self.update(kwargs)
        #self.set_bbox(dict(pad=0)) 
Example 39
Project: linear_neuron   Author: uglyboxer   File: text.py    MIT License 4 votes vote down vote up
def __init__(self,
                 x=0, y=0, text='',
                 color=None,           # defaults to rc params
                 verticalalignment='baseline',
                 horizontalalignment='left',
                 multialignment=None,
                 fontproperties=None,  # defaults to FontProperties()
                 rotation=None,
                 linespacing=None,
                 rotation_mode=None,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.text.Text` instance at *x*, *y*
        with string *text*.

        Valid kwargs are
        %(Text)s
        """

        Artist.__init__(self)
        self._x, self._y = x, y

        if color is None:
            color = rcParams['text.color']
        if fontproperties is None:
            fontproperties = FontProperties()
        elif is_string_like(fontproperties):
            fontproperties = FontProperties(fontproperties)

        self.set_text(text)
        self.set_color(color)
        self._verticalalignment = verticalalignment
        self._horizontalalignment = horizontalalignment
        self._multialignment = multialignment
        self._rotation = rotation
        self._fontproperties = fontproperties
        self._bbox = None
        self._bbox_patch = None  # a FancyBboxPatch instance
        self._renderer = None
        if linespacing is None:
            linespacing = 1.2   # Maybe use rcParam later.
        self._linespacing = linespacing
        self.set_rotation_mode(rotation_mode)
        self.update(kwargs)
        #self.set_bbox(dict(pad=0)) 
Example 40
Project: video-tools   Author: kalleknast   File: video_player.py    GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, fname, t0=0.0, fig_h=6., dpi=85):
        """
        """
        if not os.path.isfile(fname):
            raise FileNotFoundError('No such file: %s' % fname)

        plt.ion()
        self.dp = DataPump(fname, t0=t0)
        self.data, self.data_t = self.dp.get_data(t0)
        self.data_dt = self.dp.dt
        self.data_fps = 1 / self.data_dt
        fig_w = fig_h * self.data.shape[1] / self.data.shape[0]
        self.fig = plt.figure(figsize=[fig_w, fig_h], frameon=False, dpi=dpi)
        self._win_title = '%s -- video fps: %1.1f' % (fname.split('/')[-1], self.data_fps)
        self.fig.canvas.set_window_title('%s -- playback not running, press "m" for menu' % self._win_title)
        self.ax = self.fig.add_axes([0, 0, 1, 1])
        self.ax.set_xticks([])
        self.ax.set_yticks([])
        self.text = self.ax.text(.025, .025, 't = %1.2fs' % self.data_t, fontsize=12, color='r')
        self.im = self.ax.imshow(self.data, cmap='Greys_r', extent=[0, 1, 0, 1], aspect='auto')
        self.im.figure.canvas.draw()
        #self.bg_cache = self.fig.canvas.copy_from_bbox(self.ax.bbox)
        self.cid = self.im.figure.canvas.mpl_connect('key_press_event', self)
        # menu
        #self._menu_bkg = patches.Rectangle((.5, .5), .45, .45, fc='w', alpha=0.75)
        bs = patches.BoxStyle("Round", pad=0.01)
        self._menu_bkg = patches.FancyBboxPatch((.5, .5), .45, .45, boxstyle=bs, fc='w', alpha=0.75)
        menu_text = ('- Left arrow:  decrease speed (increase negative)\n'
                     '- Right arrow: increase speed (decrease negative)\n'
                     '- Space bar:   pause/un-pause\n'
                     '- m:           show/remove this menu\n'
                     '- q:           quit player\n')
        self._menu_text = self.ax.text(.55, .85, menu_text, fontsize=14, color='g', va='top', ha='left')
        self._menu_title = self.ax.text(.725, .9, 'Menu', fontsize=23, fontweight='bold', color='g', va='bottom', ha='center')
        self.ax.add_patch(self._menu_bkg)
        self.quit = False
        self.pause = True # pause
        self.requested_fps = self.data_fps
        self.requested_dt = self.data_dt
        self.no_new_event = True
        self._show_menu = False
        self._menu_showing = False
        plt.ioff() 
Example 41
Project: plotnine   Author: has2k1   File: facet.py    GNU General Public License v2.0 4 votes vote down vote up
def draw_strip_text(self, text_lines, location, ax):
        """
        Create a background patch and put a label on it
        """
        themeable = self.figure._themeable
        dim = self.strip_dimensions(text_lines, location, ax)

        if location == 'right':
            rotation = -90
            label = '\n'.join(reversed(text_lines))
        else:
            rotation = 0
            label = '\n'.join(text_lines)

        rect = mpatch.FancyBboxPatch((dim.box_x, dim.box_y),
                                     width=dim.box_width,
                                     height=dim.box_height,
                                     facecolor='lightgrey',
                                     edgecolor='None',
                                     transform=ax.transAxes,
                                     zorder=2.2,  # > ax line & boundary
                                     boxstyle='square, pad=0',
                                     clip_on=False)

        text = mtext.Text(dim.x, dim.y, label,
                          rotation=rotation,
                          verticalalignment='center',
                          horizontalalignment='center',
                          transform=ax.transAxes,
                          zorder=3.3,  # > rect
                          clip_on=False)

        ax.add_artist(rect)
        ax.add_artist(text)

        for key in ('strip_text_x', 'strip_text_y',
                    'strip_background_x', 'strip_background_y'):
            if key not in themeable:
                themeable[key] = []

        if location == 'right':
            themeable['strip_background_y'].append(rect)
            themeable['strip_text_y'].append(text)
        else:
            themeable['strip_background_x'].append(rect)
            themeable['strip_text_x'].append(text) 
Example 42
Project: jazzElements   Author: NeuralControl   File: viz.py    MIT License 4 votes vote down vote up
def plotNotes(notes, pos=None, name='', ax=0, nbOctaves=1):
    if pos is None:
        pos = [0, 0, 100, 40]

    def plotKey(ax, x, y, w, h, keyType, status):
        lw = .5
        pad = 0.5
        # edgeColor = 'w'
        # parms = dict(
        #     black=dict(color=['skyblue', 'steelblue'], z=1),
        #     white=dict(color=['skyblue', 'steelblue'], z=0)
        # )

        edgeColor = 'k'
        parms = dict(
            black=dict(color=['k', 'skyblue'], z=1),
            white=dict(color=['w', 'skyblue'], z=0)
        )

        ax.add_patch(FancyBboxPatch((x + pad, y + pad),
                                    abs(w) - 2 * pad, abs(h) - 2 * pad,
                                    boxstyle="round,pad=" + str(pad),
                                    fc=parms[keyType]['color'][status], ec=edgeColor, zorder=parms[keyType]['z'],
                                    lw=lw))

    nb = int(np.ceil(len(notes) / (nbOctaves * 12)) * (nbOctaves * 12))
    start = 'C' if notes[0] - Note('C') < notes[0] - Note('F') else 'F'
    chromatic = Note.chrSharp * 4
    chromatic = chromatic[chromatic.index(Note(start)):]
    chromatic = chromatic[:nb]
    whites = [n for n in chromatic if n in [Note(n) for n in ['C', 'D', 'E', 'F', 'G', 'A', 'B']]]
    whiteWidth = pos[2] / len(whites)
    blackWidth = whiteWidth / 2

    if ax == 0:
        figure(figsize=(3, 1))
        ax = gca()
    axis('off')

    nWhites = 0
    for i, n in enumerate(chromatic):
        if n in whites:
            plotKey(ax, pos[0] + (nWhites) * whiteWidth, pos[1], whiteWidth, pos[3], keyType='white', status=n in notes)
            nWhites += 1
        else:
            plotKey(ax, pos[0] + (nWhites) * whiteWidth - blackWidth / 2, pos[1] + pos[3] / 3, blackWidth,
                    2 * pos[3] / 3, keyType='black', status=n in notes)
    plot(0, 0, '.w', zorder=-1)
    if name:
        text(pos[0], pos[1] + pos[3] / 2, name, ha='right', va='center', rotation=90) 
Example 43
Project: ImageFusion   Author: pfchai   File: text.py    MIT License 4 votes vote down vote up
def __init__(self,
                 x=0, y=0, text='',
                 color=None,           # defaults to rc params
                 verticalalignment='baseline',
                 horizontalalignment='left',
                 multialignment=None,
                 fontproperties=None,  # defaults to FontProperties()
                 rotation=None,
                 linespacing=None,
                 rotation_mode=None,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.text.Text` instance at *x*, *y*
        with string *text*.

        Valid kwargs are
        %(Text)s
        """

        Artist.__init__(self)
        self._x, self._y = x, y

        if color is None:
            color = rcParams['text.color']
        if fontproperties is None:
            fontproperties = FontProperties()
        elif is_string_like(fontproperties):
            fontproperties = FontProperties(fontproperties)

        self.set_text(text)
        self.set_color(color)
        self._verticalalignment = verticalalignment
        self._horizontalalignment = horizontalalignment
        self._multialignment = multialignment
        self._rotation = rotation
        self._fontproperties = fontproperties
        self._bbox = None
        self._bbox_patch = None  # a FancyBboxPatch instance
        self._renderer = None
        if linespacing is None:
            linespacing = 1.2   # Maybe use rcParam later.
        self._linespacing = linespacing
        self.set_rotation_mode(rotation_mode)
        self.update(kwargs)
        #self.set_bbox(dict(pad=0)) 
Example 44
Project: Blackjack-Tracker   Author: martinabeleda   File: text.py    MIT License 4 votes vote down vote up
def __init__(self,
                 x=0, y=0, text='',
                 color=None,           # defaults to rc params
                 verticalalignment='baseline',
                 horizontalalignment='left',
                 multialignment=None,
                 fontproperties=None,  # defaults to FontProperties()
                 rotation=None,
                 linespacing=None,
                 rotation_mode=None,
                 usetex=None,          # defaults to rcParams['text.usetex']
                 wrap=False,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.text.Text` instance at *x*, *y*
        with string *text*.

        Valid kwargs are
        %(Text)s
        """

        Artist.__init__(self)
        self._x, self._y = x, y

        if color is None:
            color = rcParams['text.color']
        if fontproperties is None:
            fontproperties = FontProperties()
        elif isinstance(fontproperties, six.string_types):
            fontproperties = FontProperties(fontproperties)

        self.set_text(text)
        self.set_color(color)
        self.set_usetex(usetex)
        self.set_wrap(wrap)
        self._verticalalignment = verticalalignment
        self._horizontalalignment = horizontalalignment
        self._multialignment = multialignment
        self._rotation = rotation
        self._fontproperties = fontproperties
        self._bbox_patch = None  # a FancyBboxPatch instance
        self._renderer = None
        if linespacing is None:
            linespacing = 1.2   # Maybe use rcParam later.
        self._linespacing = linespacing
        self.set_rotation_mode(rotation_mode)
        self.update(kwargs) 
Example 45
Project: Blackjack-Tracker   Author: martinabeleda   File: text.py    MIT License 4 votes vote down vote up
def set_bbox(self, rectprops):
        """
        Draw a bounding box around self.  rectprops are any settable
        properties for a FancyBboxPatch, e.g., facecolor='red', alpha=0.5.

          t.set_bbox(dict(facecolor='red', alpha=0.5))

        The default boxstyle is 'square'. The mutation
        scale of the FancyBboxPatch is set to the fontsize.

        ACCEPTS: FancyBboxPatch prop dict
        """

        if rectprops is not None:
            props = rectprops.copy()
            boxstyle = props.pop("boxstyle", None)
            pad = props.pop("pad", None)
            if boxstyle is None:
                boxstyle = "square"
                if pad is None:
                    pad = 4  # points
                pad /= self.get_size()  # to fraction of font size
            else:
                if pad is None:
                    pad = 0.3

            # boxstyle could be a callable or a string
            if (isinstance(boxstyle, six.string_types)
                    and "pad" not in boxstyle):
                boxstyle += ",pad=%0.2f" % pad

            bbox_transmuter = props.pop("bbox_transmuter", None)

            self._bbox_patch = FancyBboxPatch(
                                    (0., 0.),
                                    1., 1.,
                                    boxstyle=boxstyle,
                                    bbox_transmuter=bbox_transmuter,
                                    transform=mtransforms.IdentityTransform(),
                                    **props)
        else:
            self._bbox_patch = None

        self._update_clip_properties() 
Example 46
Project: cnidaria   Author: sauloal   File: text.py    MIT License 4 votes vote down vote up
def __init__(self,
                 x=0, y=0, text='',
                 color=None,           # defaults to rc params
                 verticalalignment='baseline',
                 horizontalalignment='left',
                 multialignment=None,
                 fontproperties=None,  # defaults to FontProperties()
                 rotation=None,
                 linespacing=None,
                 rotation_mode=None,
                 **kwargs
                 ):
        """
        Create a :class:`~matplotlib.text.Text` instance at *x*, *y*
        with string *text*.

        Valid kwargs are
        %(Text)s
        """

        Artist.__init__(self)
        self._x, self._y = x, y

        if color is None:
            color = rcParams['text.color']
        if fontproperties is None:
            fontproperties = FontProperties()
        elif is_string_like(fontproperties):
            fontproperties = FontProperties(fontproperties)

        self.set_text(text)
        self.set_color(color)
        self._verticalalignment = verticalalignment
        self._horizontalalignment = horizontalalignment
        self._multialignment = multialignment
        self._rotation = rotation
        self._fontproperties = fontproperties
        self._bbox = None
        self._bbox_patch = None  # a FancyBboxPatch instance
        self._renderer = None
        if linespacing is None:
            linespacing = 1.2   # Maybe use rcParam later.
        self._linespacing = linespacing
        self.set_rotation_mode(rotation_mode)
        self.update(kwargs)
        #self.set_bbox(dict(pad=0))