Python matplotlib.patches.FancyArrowPatch() Examples

The following are code examples for showing how to use matplotlib.patches.FancyArrowPatch(). 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: DataHack2018   Author: InnovizTech   File: math_utils.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def draw(self, ax, color, line_width=1, fillcolor=None, name=None, arrow=True, alpha=0.2, scale=50):
        ax.add_patch(PolygonPatch(self.contour, alpha=alpha, fc=fillcolor, ec=color, linewidth=line_width))

        vertices = np.array(self.contour.exterior.coords)[1:]

        if arrow:
            arrow_center = np.mean(vertices, axis=0)
            arrow_direction = (vertices[2] - vertices[1]) / 1.5
            arrow_tail = arrow_center - arrow_direction / 2
            arrow_head = arrow_center + arrow_direction / 2
            style = plt_patches.ArrowStyle.Simple(head_length=.4, head_width=.6, tail_width=.1)
            x = np.array(ax.axis())
            scale_factor = np.sqrt(np.prod(np.abs(x[::2] - x[1::2])) / (60 * 60))
            arrow_patch = plt_patches.FancyArrowPatch(posA=arrow_tail, posB=arrow_head, arrowstyle=style,
                                                      color='w', mutation_scale= scale / scale_factor, alpha=0.4)
            ax.add_patch(arrow_patch)
        elif name is None:
            name = 'front'

        if name is not None:
            text_location = np.mean(vertices[[0, -1]], axis=0)
            ax.text(text_location[0], text_location[1], name, ha='center', va='top', color='w') 
Example 2
Project: LaserTOF   Author: kyleuckert   File: text.py    MIT License 6 votes vote down vote up
def draw(self, renderer):
        """
        Draw the :class:`Annotation` object to the given *renderer*.
        """

        if renderer is not None:
            self._renderer = renderer
        if not self.get_visible():
            return

        xy_pixel = self._get_position_xy(renderer)
        if not self._check_xy(renderer, xy_pixel):
            return

        self._update_position_xytext(renderer, xy_pixel)
        self.update_bbox_position_size(renderer)

        if self.arrow_patch is not None:   # FancyArrowPatch
            if self.arrow_patch.figure is None and self.figure is not None:
                self.arrow_patch.figure = self.figure
            self.arrow_patch.draw(renderer)

        # Draw text, including FancyBboxPatch, after FancyArrowPatch.
        # Otherwise, a wedge arrowstyle can land partly on top of the Bbox.
        Text.draw(self, renderer) 
Example 3
Project: ble5-nrf52-mac   Author: tomasero   File: test_arrow_patches.py    MIT License 6 votes vote down vote up
def __prepare_fancyarrow_dpi_cor_test():
    """
    Convenience function that prepares and returns a FancyArrowPatch. It aims
    at being used to test that the size of the arrow head does not depend on
    the DPI value of the exported picture.

    NB: this function *is not* a test in itself!
    """
    fig2 = plt.figure("fancyarrow_dpi_cor_test", figsize=(4, 3), dpi=50)
    ax = fig2.add_subplot(111)
    ax.set_xlim([0, 1])
    ax.set_ylim([0, 1])
    ax.add_patch(mpatches.FancyArrowPatch(posA=(0.3, 0.4), posB=(0.8, 0.6),
                                          lw=3, arrowstyle='->',
                                          mutation_scale=100))
    return fig2 
Example 4
Project: ble5-nrf52-mac   Author: tomasero   File: test_arrow_patches.py    MIT License 6 votes vote down vote up
def test_fancyarrow_dash():
    from matplotlib.patches import FancyArrowPatch
    fig, ax = plt.subplots()

    e = FancyArrowPatch((0, 0), (0.5, 0.5),
                        arrowstyle='-|>',
                        connectionstyle='angle3,angleA=0,angleB=90',
                        mutation_scale=10.0,
                        linewidth=2,
                        linestyle='dashed',
                        color='k')

    e2 = FancyArrowPatch((0, 0), (0.5, 0.5),
                         arrowstyle='-|>',
                         connectionstyle='angle3',
                         mutation_scale=10.0,
                         linewidth=2,
                         linestyle='dotted',
                         color='k')
    ax.add_patch(e)
    ax.add_patch(e2) 
Example 5
Project: Computable   Author: ktraunmueller   File: text.py    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
Project: neural-network-animation   Author: miloharper   File: text.py    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 7
Project: python3_ios   Author: holzschu   File: test_arrow_patches.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __prepare_fancyarrow_dpi_cor_test():
    """
    Convenience function that prepares and returns a FancyArrowPatch. It aims
    at being used to test that the size of the arrow head does not depend on
    the DPI value of the exported picture.

    NB: this function *is not* a test in itself!
    """
    fig2 = plt.figure("fancyarrow_dpi_cor_test", figsize=(4, 3), dpi=50)
    ax = fig2.add_subplot(111)
    ax.set_xlim([0, 1])
    ax.set_ylim([0, 1])
    ax.add_patch(mpatches.FancyArrowPatch(posA=(0.3, 0.4), posB=(0.8, 0.6),
                                          lw=3, arrowstyle='->',
                                          mutation_scale=100))
    return fig2 
Example 8
Project: python3_ios   Author: holzschu   File: test_arrow_patches.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_fancyarrow_dash():
    from matplotlib.patches import FancyArrowPatch
    fig, ax = plt.subplots()

    e = FancyArrowPatch((0, 0), (0.5, 0.5),
                        arrowstyle='-|>',
                        connectionstyle='angle3,angleA=0,angleB=90',
                        mutation_scale=10.0,
                        linewidth=2,
                        linestyle='dashed',
                        color='k')

    e2 = FancyArrowPatch((0, 0), (0.5, 0.5),
                         arrowstyle='-|>',
                         connectionstyle='angle3',
                         mutation_scale=10.0,
                         linewidth=2,
                         linestyle='dotted',
                         color='k')
    ax.add_patch(e)
    ax.add_patch(e2) 
Example 9
Project: linear_neuron   Author: uglyboxer   File: text.py    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
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_arrow_patches.py    MIT License 6 votes vote down vote up
def __prepare_fancyarrow_dpi_cor_test():
    """
    Convenience function that prepares and returns a FancyArrowPatch. It aims
    at being used to test that the size of the arrow head does not depend on
    the DPI value of the exported picture.

    NB: this function *is not* a test in itself!
    """
    fig2 = plt.figure("fancyarrow_dpi_cor_test", figsize=(4, 3), dpi=50)
    ax = fig2.add_subplot(111)
    ax.set_xlim([0, 1])
    ax.set_ylim([0, 1])
    ax.add_patch(mpatches.FancyArrowPatch(posA=(0.3, 0.4), posB=(0.8, 0.6),
                                          lw=3, arrowstyle='->',
                                          mutation_scale=100))
    return fig2 
Example 11
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_arrow_patches.py    MIT License 6 votes vote down vote up
def test_fancyarrow_dash():
    from matplotlib.patches import FancyArrowPatch
    fig, ax = plt.subplots()

    e = FancyArrowPatch((0, 0), (0.5, 0.5),
                        arrowstyle='-|>',
                        connectionstyle='angle3,angleA=0,angleB=90',
                        mutation_scale=10.0,
                        linewidth=2,
                        linestyle='dashed',
                        color='k')

    e2 = FancyArrowPatch((0, 0), (0.5, 0.5),
                         arrowstyle='-|>',
                         connectionstyle='angle3',
                         mutation_scale=10.0,
                         linewidth=2,
                         linestyle='dotted',
                         color='k')
    ax.add_patch(e)
    ax.add_patch(e2) 
Example 12
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_arrow_patches.py    MIT License 6 votes vote down vote up
def __prepare_fancyarrow_dpi_cor_test():
    """
    Convenience function that prepares and returns a FancyArrowPatch. It aims
    at being used to test that the size of the arrow head does not depend on
    the DPI value of the exported picture.

    NB: this function *is not* a test in itself!
    """
    fig2 = plt.figure("fancyarrow_dpi_cor_test", figsize=(4, 3), dpi=50)
    ax = fig2.add_subplot(111)
    ax.set_xlim([0, 1])
    ax.set_ylim([0, 1])
    ax.add_patch(mpatches.FancyArrowPatch(posA=(0.3, 0.4), posB=(0.8, 0.6),
                                          lw=3, arrowstyle='->',
                                          mutation_scale=100))
    return fig2 
Example 13
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_arrow_patches.py    MIT License 6 votes vote down vote up
def test_fancyarrow_dash():
    from matplotlib.patches import FancyArrowPatch
    fig, ax = plt.subplots()

    e = FancyArrowPatch((0, 0), (0.5, 0.5),
                        arrowstyle='-|>',
                        connectionstyle='angle3,angleA=0,angleB=90',
                        mutation_scale=10.0,
                        linewidth=2,
                        linestyle='dashed',
                        color='k')

    e2 = FancyArrowPatch((0, 0), (0.5, 0.5),
                         arrowstyle='-|>',
                         connectionstyle='angle3',
                         mutation_scale=10.0,
                         linewidth=2,
                         linestyle='dotted',
                         color='k')
    ax.add_patch(e)
    ax.add_patch(e2) 
Example 14
Project: ImageFusion   Author: pfchai   File: text.py    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 15
Project: Blackjack-Tracker   Author: martinabeleda   File: text.py    MIT License 6 votes vote down vote up
def draw(self, renderer):
        """
        Draw the :class:`Annotation` object to the given *renderer*.
        """

        if renderer is not None:
            self._renderer = renderer
        if not self.get_visible():
            return

        xy_pixel = self._get_position_xy(renderer)
        if not self._check_xy(renderer, xy_pixel):
            return

        self._update_position_xytext(renderer, xy_pixel)
        self.update_bbox_position_size(renderer)

        if self.arrow_patch is not None:   # FancyArrowPatch
            if self.arrow_patch.figure is None and self.figure is not None:
                self.arrow_patch.figure = self.figure
            self.arrow_patch.draw(renderer)

        # Draw text, including FancyBboxPatch, after FancyArrowPatch.
        # Otherwise, a wedge arrowstyle can land partly on top of the Bbox.
        Text.draw(self, renderer) 
Example 16
Project: Blackjack-Tracker   Author: martinabeleda   File: test_arrow_patches.py    MIT License 6 votes vote down vote up
def __prepare_fancyarrow_dpi_cor_test():
    """
    Convenience function that prepares and returns a FancyArrowPatch. It aims
    at being used to test that the size of the arrow head does not depend on
    the DPI value of the exported picture.

    NB: this function *is not* a test in itself!
    """
    fig2 = plt.figure("fancyarrow_dpi_cor_test", figsize=(4, 3), dpi=50)
    ax = fig2.add_subplot(111)
    ax.set_xlim([0, 1])
    ax.set_ylim([0, 1])
    ax.add_patch(mpatches.FancyArrowPatch(posA=(0.3, 0.4), posB=(0.8, 0.6),
                                          lw=3, arrowstyle=u'->',
                                          mutation_scale=100))
    return fig2 
Example 17
Project: Blackjack-Tracker   Author: martinabeleda   File: test_arrow_patches.py    MIT License 6 votes vote down vote up
def test_fancyarrow_dash():
    from matplotlib.patches import FancyArrowPatch
    fig, ax = plt.subplots()

    e = FancyArrowPatch((0, 0), (0.5, 0.5),
                        arrowstyle='-|>',
                        connectionstyle='angle3,angleA=0,angleB=90',
                        mutation_scale=10.0,
                        linewidth=2,
                        linestyle='dashed',
                        color='k')

    e2 = FancyArrowPatch((0, 0), (0.5, 0.5),
                         arrowstyle='-|>',
                         connectionstyle='angle3',
                         mutation_scale=10.0,
                         linewidth=2,
                         linestyle='dotted',
                         color='k')
    ax.add_patch(e)
    ax.add_patch(e2) 
Example 18
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_arrow_patches.py    GNU General Public License v3.0 6 votes vote down vote up
def __prepare_fancyarrow_dpi_cor_test():
    """
    Convenience function that prepares and returns a FancyArrowPatch. It aims
    at being used to test that the size of the arrow head does not depend on
    the DPI value of the exported picture.

    NB: this function *is not* a test in itself!
    """
    fig2 = plt.figure("fancyarrow_dpi_cor_test", figsize=(4, 3), dpi=50)
    ax = fig2.add_subplot(111)
    ax.set_xlim([0, 1])
    ax.set_ylim([0, 1])
    ax.add_patch(mpatches.FancyArrowPatch(posA=(0.3, 0.4), posB=(0.8, 0.6),
                                          lw=3, arrowstyle='->',
                                          mutation_scale=100))
    return fig2 
Example 19
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_arrow_patches.py    GNU General Public License v3.0 6 votes vote down vote up
def test_fancyarrow_dash():
    from matplotlib.patches import FancyArrowPatch
    fig, ax = plt.subplots()

    e = FancyArrowPatch((0, 0), (0.5, 0.5),
                        arrowstyle='-|>',
                        connectionstyle='angle3,angleA=0,angleB=90',
                        mutation_scale=10.0,
                        linewidth=2,
                        linestyle='dashed',
                        color='k')

    e2 = FancyArrowPatch((0, 0), (0.5, 0.5),
                         arrowstyle='-|>',
                         connectionstyle='angle3',
                         mutation_scale=10.0,
                         linewidth=2,
                         linestyle='dotted',
                         color='k')
    ax.add_patch(e)
    ax.add_patch(e2) 
Example 20
Project: cnidaria   Author: sauloal   File: text.py    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 21
Project: tr   Author: xuanqing94   File: plot_illustrate.py    MIT License 5 votes vote down vote up
def plot_SGD_TR_SGD():
    x = np.arange(-1.6, 1.0, 0.01)
    y = np.array([fn(x_) for x_ in x])
    fd = { 'weight': 'bold', 'size': 12 }
    plt.axis('off')

    plt.plot(-1.6, fn(-1.6), 'ko')
    plt.plot(-1.3, fn(-1.3), 'ko')
    plt.plot(-1.0, fn(-1.0), 'ko')
    plt.plot(-0.3, fn(-0.3), 'ko')
    plt.plot(0.0, fn(0.0), 'ko')

    style="Simple,tail_width=0.5,head_width=4,head_length=8"
    kw1 = dict(arrowstyle=style, color="k", linestyle='--', linewidth=.5)
    kw2 = dict(arrowstyle=style, color="k", linestyle='--', linewidth=.5)

    a0 = patches.FancyArrowPatch((-1.6, fn(-1.6)), (-1.3, fn(-1.3)), connectionstyle="arc3", **kw1)
    a1 = patches.FancyArrowPatch((-1.3, fn(-1.3)), (-1.0, fn(-1.0)), connectionstyle="arc3", **kw1)
    a2 = patches.FancyArrowPatch((-1.0, fn(-1.0)), (-0.3, fn(-0.3)), connectionstyle="arc3", **kw1)
    a3 = patches.FancyArrowPatch((-0.3, fn(-0.3)), (0.0, fn(0.0)), connectionstyle="arc3", **kw1)

    for p in [a0, a1, a2, a3]:
        plt.gca().add_patch(p)
    plt.text(-1.5, fn(-1.5), "SGD", fontdict=fd)
    plt.text(-1.2, fn(-1.1), "TR", fontdict=fd)
    plt.text(-0.8, fn(-0.8), "TR", fontdict=fd)
    plt.text(-0.2, fn(-0.2), "SGD", fontdict=fd)
    plt.plot(x, y, color='b', linewidth=2)
    plt.show() 
Example 22
Project: tr   Author: xuanqing94   File: plot_illustrate.py    MIT License 5 votes vote down vote up
def plot_TR_SGD_TR():
    x = np.arange(-1.6, 1.0, 0.01)
    y = np.array([fn(x_) for x_ in x])
    fd = { 'weight': 'bold', 'size': 12 }
    plt.axis('off')

    plt.plot(1.0, fn(1.0), 'ko')
    plt.plot(0.3, fn(0.3), 'ko')
    plt.plot(0.0, fn(0.0), 'ko')
    plt.plot(-0.3, fn(-0.3), 'ko')

    style="Simple,tail_width=0.5,head_width=4,head_length=8"
    kw1 = dict(arrowstyle=style, color="k", linestyle='--', linewidth=.5)
    kw2 = dict(arrowstyle=style, color="k", linestyle='--', linewidth=.5)

    a0 = patches.FancyArrowPatch((1.0, fn(1.0)), (0.3, fn(0.3)), connectionstyle="arc3", **kw1)
    a1 = patches.FancyArrowPatch((0.3, fn(0.3)), (0.0, fn(0.0)), connectionstyle="arc3", **kw1)
    a2 = patches.FancyArrowPatch((0.0, fn(0.0)), (-0.3, fn(-0.3)), connectionstyle="arc3", **kw1)

    for p in [a0, a1, a2]:
        plt.gca().add_patch(p)
    plt.text(0.5, fn(0.5)+0.1, "TR", fontdict=fd)
    plt.text(0.07, fn(0.15), "SGD", fontdict=fd)
    plt.text(-0.15, fn(0.15), "TR", fontdict=fd)
    plt.plot(x, y, color='b', linewidth=2)
    plt.show() 
Example 23
Project: ble5-nrf52-mac   Author: tomasero   File: test_arrow_patches.py    MIT License 5 votes vote down vote up
def test_fancyarrow_dpi_cor_100dpi():
    """
    Check the export of a FancyArrowPatch @ 100 DPI. FancyArrowPatch is
    instantiated through a dedicated function because another similar test
    checks a similar export but with a different DPI value.

    Remark: test only a rasterized format.
    """

    __prepare_fancyarrow_dpi_cor_test() 
Example 24
Project: ble5-nrf52-mac   Author: tomasero   File: test_arrow_patches.py    MIT License 5 votes vote down vote up
def test_arrow_styles():
    styles = mpatches.ArrowStyle.get_styles()

    n = len(styles)
    fig, ax = plt.subplots(figsize=(6, 10))
    ax.set_xlim(0, 1)
    ax.set_ylim(-1, n)

    for i, stylename in enumerate(sorted(styles)):
        patch = mpatches.FancyArrowPatch((0.1, i), (0.8, i),
                                         arrowstyle=stylename,
                                         mutation_scale=25)
        ax.add_patch(patch) 
Example 25
Project: ble5-nrf52-mac   Author: tomasero   File: test_arrow_patches.py    MIT License 5 votes vote down vote up
def test_invalid_intersection():
    conn_style_1 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=200)
    p1 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),
                                  connectionstyle=conn_style_1)
    with pytest.raises(ValueError):
        plt.gca().add_patch(p1)

    conn_style_2 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=199.9)
    p2 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),
                                  connectionstyle=conn_style_2)
    plt.gca().add_patch(p2) 
Example 26
Project: python3_ios   Author: holzschu   File: test_arrow_patches.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fancyarrow_dpi_cor_100dpi():
    """
    Check the export of a FancyArrowPatch @ 100 DPI. FancyArrowPatch is
    instantiated through a dedicated function because another similar test
    checks a similar export but with a different DPI value.

    Remark: test only a rasterized format.
    """

    __prepare_fancyarrow_dpi_cor_test() 
Example 27
Project: python3_ios   Author: holzschu   File: test_arrow_patches.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_arrow_styles():
    styles = mpatches.ArrowStyle.get_styles()

    n = len(styles)
    fig, ax = plt.subplots(figsize=(6, 10))
    ax.set_xlim(0, 1)
    ax.set_ylim(-1, n)

    for i, stylename in enumerate(sorted(styles)):
        patch = mpatches.FancyArrowPatch((0.1, i), (0.8, i),
                                         arrowstyle=stylename,
                                         mutation_scale=25)
        ax.add_patch(patch) 
Example 28
Project: python3_ios   Author: holzschu   File: test_arrow_patches.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_invalid_intersection():
    conn_style_1 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=200)
    p1 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),
                                  connectionstyle=conn_style_1)
    with pytest.raises(ValueError):
        plt.gca().add_patch(p1)

    conn_style_2 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=199.9)
    p2 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),
                                  connectionstyle=conn_style_2)
    plt.gca().add_patch(p2) 
Example 29
Project: MuMoT   Author: DiODeProject   File: views.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, xs, ys, zs, *args, **kwargs):
        mpatch.FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
        self._verts3d = xs, ys, zs 
Example 30
Project: MuMoT   Author: DiODeProject   File: views.py    GNU General Public License v3.0 5 votes vote down vote up
def draw(self, renderer) -> None:
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
        mpatch.FancyArrowPatch.draw(self, renderer) 
Example 31
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_patches.py    MIT License 5 votes vote down vote up
def test_fancyarrow_units():
    from datetime import datetime
    # Smoke test to check that FancyArrowPatch works with units
    dtime = datetime(2000, 1, 1)
    fig, ax = plt.subplots()
    arrow = FancyArrowPatch((0, dtime), (0.01, dtime))
    ax.add_patch(arrow) 
Example 32
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_arrow_patches.py    MIT License 5 votes vote down vote up
def test_fancyarrow_dpi_cor_100dpi():
    """
    Check the export of a FancyArrowPatch @ 100 DPI. FancyArrowPatch is
    instantiated through a dedicated function because another similar test
    checks a similar export but with a different DPI value.

    Remark: test only a rasterized format.
    """

    __prepare_fancyarrow_dpi_cor_test() 
Example 33
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_arrow_patches.py    MIT License 5 votes vote down vote up
def test_connection_styles():
    styles = mpatches.ConnectionStyle.get_styles()

    n = len(styles)
    fig, ax = plt.subplots(figsize=(6, 10))
    ax.set_xlim(0, 1)
    ax.set_ylim(-1, n)

    for i, stylename in enumerate(sorted(styles)):
        patch = mpatches.FancyArrowPatch((0.1, i), (0.8, i + 0.5),
                                         arrowstyle="->",
                                         connectionstyle=stylename,
                                         mutation_scale=25)
        ax.add_patch(patch) 
Example 34
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_arrow_patches.py    MIT License 5 votes vote down vote up
def test_invalid_intersection():
    conn_style_1 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=200)
    p1 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),
                                  connectionstyle=conn_style_1)
    with pytest.raises(ValueError):
        plt.gca().add_patch(p1)

    conn_style_2 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=199.9)
    p2 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),
                                  connectionstyle=conn_style_2)
    plt.gca().add_patch(p2) 
Example 35
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_path.py    MIT License 5 votes vote down vote up
def test_arrow_contains_point():
    # fix bug (#8384)
    fig, ax = plt.subplots()
    ax.set_xlim((0, 2))
    ax.set_ylim((0, 2))

    # create an arrow with Curve style
    arrow = patches.FancyArrowPatch((0.5, 0.25), (1.5, 0.75),
                                    arrowstyle='->',
                                    mutation_scale=40)
    ax.add_patch(arrow)
    # create an arrow with Bracket style
    arrow1 = patches.FancyArrowPatch((0.5, 1), (1.5, 1.25),
                                     arrowstyle=']-[',
                                     mutation_scale=40)
    ax.add_patch(arrow1)
    # create an arrow with other arrow style
    arrow2 = patches.FancyArrowPatch((0.5, 1.5), (1.5, 1.75),
                                     arrowstyle='fancy',
                                     fill=False,
                                     mutation_scale=40)
    ax.add_patch(arrow2)
    patches_list = [arrow, arrow1, arrow2]

    # generate some points
    X, Y = np.meshgrid(np.arange(0, 2, 0.1),
                       np.arange(0, 2, 0.1))
    for k, (x, y) in enumerate(zip(X.ravel(), Y.ravel())):
        xdisp, ydisp = ax.transData.transform_point([x, y])
        event = MouseEvent('button_press_event', fig.canvas, xdisp, ydisp)
        for m, patch in enumerate(patches_list):
            # set the points to red only if the arrow contains the point
            inside, res = patch.contains(event)
            if inside:
                ax.scatter(x, y, s=5, c="r") 
Example 36
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_patches.py    MIT License 5 votes vote down vote up
def test_fancyarrow_units():
    from datetime import datetime
    # Smoke test to check that FancyArrowPatch works with units
    dtime = datetime(2000, 1, 1)
    fig, ax = plt.subplots()
    arrow = FancyArrowPatch((0, dtime), (0.01, dtime))
    ax.add_patch(arrow) 
Example 37
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_arrow_patches.py    MIT License 5 votes vote down vote up
def test_fancyarrow_dpi_cor_100dpi():
    """
    Check the export of a FancyArrowPatch @ 100 DPI. FancyArrowPatch is
    instantiated through a dedicated function because another similar test
    checks a similar export but with a different DPI value.

    Remark: test only a rasterized format.
    """

    __prepare_fancyarrow_dpi_cor_test() 
Example 38
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_arrow_patches.py    MIT License 5 votes vote down vote up
def test_connection_styles():
    styles = mpatches.ConnectionStyle.get_styles()

    n = len(styles)
    fig, ax = plt.subplots(figsize=(6, 10))
    ax.set_xlim(0, 1)
    ax.set_ylim(-1, n)

    for i, stylename in enumerate(sorted(styles)):
        patch = mpatches.FancyArrowPatch((0.1, i), (0.8, i + 0.5),
                                         arrowstyle="->",
                                         connectionstyle=stylename,
                                         mutation_scale=25)
        ax.add_patch(patch) 
Example 39
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_arrow_patches.py    MIT License 5 votes vote down vote up
def test_invalid_intersection():
    conn_style_1 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=200)
    p1 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),
                                  connectionstyle=conn_style_1)
    with pytest.raises(ValueError):
        plt.gca().add_patch(p1)

    conn_style_2 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=199.9)
    p2 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),
                                  connectionstyle=conn_style_2)
    plt.gca().add_patch(p2) 
Example 40
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_path.py    MIT License 5 votes vote down vote up
def test_arrow_contains_point():
    # fix bug (#8384)
    fig, ax = plt.subplots()
    ax.set_xlim((0, 2))
    ax.set_ylim((0, 2))

    # create an arrow with Curve style
    arrow = patches.FancyArrowPatch((0.5, 0.25), (1.5, 0.75),
                                    arrowstyle='->',
                                    mutation_scale=40)
    ax.add_patch(arrow)
    # create an arrow with Bracket style
    arrow1 = patches.FancyArrowPatch((0.5, 1), (1.5, 1.25),
                                     arrowstyle=']-[',
                                     mutation_scale=40)
    ax.add_patch(arrow1)
    # create an arrow with other arrow style
    arrow2 = patches.FancyArrowPatch((0.5, 1.5), (1.5, 1.75),
                                     arrowstyle='fancy',
                                     fill=False,
                                     mutation_scale=40)
    ax.add_patch(arrow2)
    patches_list = [arrow, arrow1, arrow2]

    # generate some points
    X, Y = np.meshgrid(np.arange(0, 2, 0.1),
                       np.arange(0, 2, 0.1))
    for k, (x, y) in enumerate(zip(X.ravel(), Y.ravel())):
        xdisp, ydisp = ax.transData.transform_point([x, y])
        event = MouseEvent('button_press_event', fig.canvas, xdisp, ydisp)
        for m, patch in enumerate(patches_list):
            # set the points to red only if the arrow contains the point
            inside, res = patch.contains(event)
            if inside:
                ax.scatter(x, y, s=5, c="r") 
Example 41
Project: Blackjack-Tracker   Author: martinabeleda   File: test_arrow_patches.py    MIT License 5 votes vote down vote up
def test_fancyarrow_dpi_cor_100dpi():
    """
    Check the export of a FancyArrowPatch @ 100 DPI. FancyArrowPatch is
    instantiated through a dedicated function because another similar test
    checks a similar export but with a different DPI value.

    Remark: test only a rasterized format.
    """

    __prepare_fancyarrow_dpi_cor_test() 
Example 42
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_patches.py    GNU General Public License v3.0 5 votes vote down vote up
def test_fancyarrow_units():
    from datetime import datetime
    # Smoke test to check that FancyArrowPatch works with units
    dtime = datetime(2000, 1, 1)
    fig, ax = plt.subplots()
    arrow = FancyArrowPatch((0, dtime), (0.01, dtime))
    ax.add_patch(arrow) 
Example 43
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_arrow_patches.py    GNU General Public License v3.0 5 votes vote down vote up
def test_fancyarrow_dpi_cor_100dpi():
    """
    Check the export of a FancyArrowPatch @ 100 DPI. FancyArrowPatch is
    instantiated through a dedicated function because another similar test
    checks a similar export but with a different DPI value.

    Remark: test only a rasterized format.
    """

    __prepare_fancyarrow_dpi_cor_test() 
Example 44
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_arrow_patches.py    GNU General Public License v3.0 5 votes vote down vote up
def test_connection_styles():
    styles = mpatches.ConnectionStyle.get_styles()

    n = len(styles)
    fig, ax = plt.subplots(figsize=(6, 10))
    ax.set_xlim(0, 1)
    ax.set_ylim(-1, n)

    for i, stylename in enumerate(sorted(styles)):
        patch = mpatches.FancyArrowPatch((0.1, i), (0.8, i + 0.5),
                                         arrowstyle="->",
                                         connectionstyle=stylename,
                                         mutation_scale=25)
        ax.add_patch(patch) 
Example 45
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_arrow_patches.py    GNU General Public License v3.0 5 votes vote down vote up
def test_invalid_intersection():
    conn_style_1 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=200)
    p1 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),
                                  connectionstyle=conn_style_1)
    with pytest.raises(ValueError):
        plt.gca().add_patch(p1)

    conn_style_2 = mpatches.ConnectionStyle.Angle3(angleA=20, angleB=199.9)
    p2 = mpatches.FancyArrowPatch((.2, .2), (.5, .5),
                                  connectionstyle=conn_style_2)
    plt.gca().add_patch(p2) 
Example 46
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_path.py    GNU General Public License v3.0 5 votes vote down vote up
def test_arrow_contains_point():
    # fix bug (#8384)
    fig, ax = plt.subplots()
    ax.set_xlim((0, 2))
    ax.set_ylim((0, 2))

    # create an arrow with Curve style
    arrow = patches.FancyArrowPatch((0.5, 0.25), (1.5, 0.75),
                                    arrowstyle='->',
                                    mutation_scale=40)
    ax.add_patch(arrow)
    # create an arrow with Bracket style
    arrow1 = patches.FancyArrowPatch((0.5, 1), (1.5, 1.25),
                                     arrowstyle=']-[',
                                     mutation_scale=40)
    ax.add_patch(arrow1)
    # create an arrow with other arrow style
    arrow2 = patches.FancyArrowPatch((0.5, 1.5), (1.5, 1.75),
                                     arrowstyle='fancy',
                                     fill=False,
                                     mutation_scale=40)
    ax.add_patch(arrow2)
    patches_list = [arrow, arrow1, arrow2]

    # generate some points
    X, Y = np.meshgrid(np.arange(0, 2, 0.1),
                       np.arange(0, 2, 0.1))
    for k, (x, y) in enumerate(zip(X.ravel(), Y.ravel())):
        xdisp, ydisp = ax.transData.transform_point([x, y])
        event = MouseEvent('button_press_event', fig.canvas, xdisp, ydisp)
        for m, patch in enumerate(patches_list):
            # set the points to red only if the arrow contains the point
            inside, res = patch.contains(event)
            if inside:
                ax.scatter(x, y, s=5, c="r") 
Example 47
Project: LaserTOF   Author: kyleuckert   File: offsetbox.py    MIT License 4 votes vote down vote up
def _update_position_xybox(self, renderer, xy_pixel):
        """
        Update the pixel positions of the annotation text and the arrow
        patch.
        """

        x, y = self.xybox
        if isinstance(self.boxcoords, tuple):
            xcoord, ycoord = self.boxcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrinked by shirnkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA) 
Example 48
Project: jr-tools   Author: kingjr   File: graphs.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def draw_curve_network(G, pos, edge_color=None, width=None, ax=None,
                       self_edge=None, edge_alpha=None, arrowstyle='-'):
    from matplotlib.patches import FancyArrowPatch
    seen = {}

    objects = list()
    for edge, (ii, jj) in enumerate(G.edges()):
        # default alpha: .5
        try:
            # find out whether it's directional or not
            color = G.edge[ii][jj][0]['color'] if edge_color is None\
                else edge_color[edge]
            width_ = G.edge[ii][jj][0]['width'] if width is None\
                else width[edge]
        except Exception:
            color = G.edge[ii][jj]['color'] if edge_color is None\
                else edge_color[edge]
            width_ = G.edge[ii][jj]['width'] if width is None else width[edge]
        if edge_alpha is not None or len(color) == 3:
            alpha = edge_alpha
        # reverse angle is arrow already exists
        rad = 0.2
        if (ii, jj) in seen:
            rad = seen.get((ii, jj))
            rad = (rad + np.sign(rad) * 0.1) * -1
        seen[(ii, jj)] = rad
        # plot arrow
        if ii != jj:
            e = FancyArrowPatch(pos[ii], pos[jj],
                                arrowstyle=arrowstyle,
                                connectionstyle='arc3,rad=%s' % rad,
                                mutation_scale=10.0,
                                lw=width_, alpha=alpha, color=color)
            ax.add_patch(e)
        else:
            verts = [[self_edge / 2 + self_edge * np.cos(kk),
                      self_edge / 2 + self_edge * np.sin(kk)]
                     for kk in np.linspace(-np.pi, np.pi)]
            ax.scatter(pos[ii][0], pos[ii][1], self_edge, marker=(verts, 0),
                       facecolor='none', edgecolor=color, alpha=alpha,
                       linewidth=width_)
            # ax.add_artist(e)
        # objects.append(e)
    return objects 
Example 49
Project: dgl   Author: dmlc   File: viz.py    Apache License 2.0 4 votes vote down vote up
def draw_g(graph):
    g=graph.g.to_networkx()
    fig=plt.figure(figsize=(8,4),dpi=150)
    ax=fig.subplots()
    ax.axis('off')
    ax.set_ylim(-1,1.5)
    en_indx=graph.nids['enc'].tolist()
    de_indx=graph.nids['dec'].tolist()
    en_l={i:np.array([i,0]) for i in en_indx}
    de_l={i:np.array([i+2,1]) for i in de_indx}
    en_de_s=[]
    for i in en_indx:
        for j in de_indx:
            en_de_s.append((i,j))
            g.add_edge(i,j)
    en_s=[]
    for i in en_indx:
        for j in en_indx:
            g.add_edge(i,j)
            en_s.append((i,j))

    de_s=[]
    for idx,i in enumerate(de_indx):
        for j in de_indx[idx:]:
            g.add_edge(i,j)
            de_s.append((i,j))


    nx.draw_networkx_nodes(g, en_l, nodelist=en_indx, node_color='r', node_size=60, ax=ax)
    nx.draw_networkx_nodes(g, de_l, nodelist=de_indx, node_color='r', node_size=60, ax=ax)
    draw_networkx_edges(g,en_l,edgelist=en_s, ax=ax,connectionstyle="arc3,rad=-0.3",width=0.5)
    draw_networkx_edges(g,de_l,edgelist=de_s, ax=ax,connectionstyle="arc3,rad=-0.3",width=0.5)
    draw_networkx_edges(g,{**en_l,**de_l},edgelist=en_de_s,width=0.3, ax=ax)
    # ax.add_patch()
    ax.text(len(en_indx)+0.5,0,"Encoder", verticalalignment='center', horizontalalignment='left')

    ax.text(len(en_indx)+0.5,1,"Decoder", verticalalignment='center', horizontalalignment='right')
    delta=0.03
    for value in {**en_l,**de_l}.values():
        x,y=value
        ax.add_patch(FancyArrowPatch((x-delta,y+delta),(x-delta,y-delta),arrowstyle="->",mutation_scale=8,connectionstyle="arc3,rad=3"))
    plt.show(fig) 
Example 50
Project: ble5-nrf52-mac   Author: tomasero   File: offsetbox.py    MIT License 4 votes vote down vote up
def _update_position_xybox(self, renderer, xy_pixel):
        """
        Update the pixel positions of the annotation text and the arrow
        patch.
        """

        x, y = self.xybox
        if isinstance(self.boxcoords, tuple):
            xcoord, ycoord = self.boxcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrunk by shrinkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA) 
Example 51
Project: Computable   Author: ktraunmueller   File: offsetbox.py    MIT License 4 votes vote down vote up
def _update_position_xybox(self, renderer, xy_pixel):
        """
        Update the pixel positions of the annotation text and the arrow
        patch.
        """

        x, y = self.xytext
        if isinstance(self.textcoords, tuple):
            xcoord, ycoord = self.textcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.textcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrinked by shirnkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA) 
Example 52
Project: pylustrator   Author: rgerum   File: snap.py    GNU General Public License v3.0 4 votes vote down vote up
def get_positions(self):
        points = []
        if isinstance(self.target, Rectangle):
            points.append(self.target.get_xy())
            p2 = (self.target.get_x() + self.target.get_width(), self.target.get_y() + self.target.get_height())
            points.append(p2)
        elif isinstance(self.target, Ellipse):
            c = self.target.center
            w = self.target.width
            h = self.target.height
            points.append((c[0]-w/2, c[1]-h/2))
            points.append((c[0]+w/2, c[1]+h/2))
        elif isinstance(self.target, FancyArrowPatch):
            points.append(self.target._posA_posB[0])
            points.append(self.target._posA_posB[1])
            points.extend(self.target.get_path().vertices)
        elif isinstance(self.target, Text):
            points.append(self.target.get_position())
            if checkXLabel(self.target):
                points[0] = (points[0][0], self.label_y)
            elif checkYLabel(self.target):
                points[0] = (self.label_x, points[0][1])
            if getattr(self.target, "xy", None) is not None:
                points.append(self.target.xy)
            bbox = self.target.get_bbox_patch()
            if bbox:
                points.append(bbox.get_transform().transform((bbox.get_x(), bbox.get_y())))
                points.append(bbox.get_transform().transform((bbox.get_x()+bbox.get_width(), bbox.get_y()+bbox.get_height())))
            points[-2:] = self.transform_inverted_points(points[-2:])
        elif isinstance(self.target, Axes):
            p1, p2 = np.array(self.target.get_position())
            points.append(p1)
            points.append(p2)
        elif isinstance(self.target, Legend):
            bbox = self.target.get_frame().get_bbox()
            if isinstance(self.target._get_loc(), int):
                # if the legend doesn't have a location yet, use the left bottom corner of the bounding box
                self.target._set_loc(tuple(self.target.axes.transAxes.inverted().transform(tuple([bbox.x0, bbox.y0]))))
            points.append(self.target.axes.transAxes.transform(self.target._get_loc()))
            # add points to span bounding box around the frame
            points.append([bbox.x0, bbox.y0])
            points.append([bbox.x1, bbox.y1])
        return self.transform_points(points) 
Example 53
Project: pylustrator   Author: rgerum   File: snap.py    GNU General Public License v3.0 4 votes vote down vote up
def set_positions(self, points):
        points = self.transform_inverted_points(points)

        if isinstance(self.target, Rectangle):
            self.target.set_xy(points[0])
            self.target.set_width(points[1][0] - points[0][0])
            self.target.set_height(points[1][1] - points[0][1])
            if self.target.get_label() is None or not self.target.get_label().startswith("_rect"):
                self.figure.change_tracker.addChange(self.target, ".set_xy([%f, %f])" % tuple(self.target.get_xy()))
                self.figure.change_tracker.addChange(self.target, ".set_width(%f)" % self.target.get_width())
                self.figure.change_tracker.addChange(self.target, ".set_height(%f)" % self.target.get_height())
        elif isinstance(self.target, Ellipse):
            self.target.center = np.mean(points, axis=0)
            self.target.width = points[1][0] - points[0][0]
            self.target.height = points[1][1] - points[0][1]
            self.figure.change_tracker.addChange(self.target, ".center = (%f, %f)" % tuple(self.target.center))
            self.figure.change_tracker.addChange(self.target, ".width = %f" % self.target.width)
            self.figure.change_tracker.addChange(self.target, ".height = %f" % self.target.height)
        elif isinstance(self.target, FancyArrowPatch):
            self.target.set_positions(points[0], points[1])
            self.figure.change_tracker.addChange(self.target, ".set_positions(%s, %s)" % (tuple(points[0]), tuple(points[1])))
        elif isinstance(self.target, Text):
            if checkXLabel(self.target):
                axes = checkXLabel(self.target)
                axes.xaxis.labelpad = -(points[0][1]-self.target.pad_offset)/self.label_factor
                self.figure.change_tracker.addChange(axes,
                                                     ".xaxis.labelpad = %f" % axes.xaxis.labelpad)

                self.target.set_position(points[0])
                self.label_y = points[0][1]
            elif checkYLabel(self.target):
                axes = checkYLabel(self.target)
                axes.yaxis.labelpad = -(points[0][0]-self.target.pad_offset)/self.label_factor
                self.figure.change_tracker.addChange(axes,
                                                     ".yaxis.labelpad = %f" % axes.yaxis.labelpad)

                self.target.set_position(points[0])
                self.label_x = points[0][0]
            else:
                self.target.set_position(points[0])
                self.figure.change_tracker.addChange(self.target, ".set_position([%f, %f])" % self.target.get_position())
                if getattr(self.target, "xy", None) is not None:
                    self.target.xy = points[1]
                    self.figure.change_tracker.addChange(self.target, ".xy = (%f, %f)" % tuple(self.target.xy))
        elif isinstance(self.target, Legend):
            point = self.target.axes.transAxes.inverted().transform(self.transform_inverted_points(points)[0])
            self.target._loc = tuple(point)
            self.figure.change_tracker.addChange(self.target, "._set_loc((%f, %f))" % tuple(point))
        elif isinstance(self.target, Axes):
            position = np.array([points[0], points[1]-points[0]]).flatten()
            if self.fixed_aspect:
                position[3] = position[2]*self.target.get_position().height/self.target.get_position().width
            self.target.set_position(position)
            self.figure.change_tracker.addChange(self.target, ".set_position([%f, %f, %f, %f])" % tuple(np.array([points[0], points[1]-points[0]]).flatten())) 
Example 54
Project: neural-network-animation   Author: miloharper   File: offsetbox.py    MIT License 4 votes vote down vote up
def _update_position_xybox(self, renderer, xy_pixel):
        """
        Update the pixel positions of the annotation text and the arrow
        patch.
        """

        x, y = self.xybox
        if isinstance(self.boxcoords, tuple):
            xcoord, ycoord = self.boxcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrinked by shirnkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA) 
Example 55
Project: GraphicDesignPatternByPython   Author: Relph1119   File: offsetbox.py    MIT License 4 votes vote down vote up
def _update_position_xybox(self, renderer, xy_pixel):
        """
        Update the pixel positions of the annotation text and the arrow
        patch.
        """

        x, y = self.xybox
        if isinstance(self.boxcoords, tuple):
            xcoord, ycoord = self.boxcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrunk by shrinkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA) 
Example 56
Project: python3_ios   Author: holzschu   File: offsetbox.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _update_position_xybox(self, renderer, xy_pixel):
        """
        Update the pixel positions of the annotation text and the arrow
        patch.
        """

        x, y = self.xybox
        if isinstance(self.boxcoords, tuple):
            xcoord, ycoord = self.boxcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrunk by shrinkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA) 
Example 57
Project: Programming-for-Non-Technical-Roles-   Author: PacktPublishing   File: offsetbox.py    MIT License 4 votes vote down vote up
def _update_position_xybox(self, renderer, xy_pixel):
        """
        Update the pixel positions of the annotation text and the arrow
        patch.
        """

        x, y = self.xybox
        if isinstance(self.boxcoords, tuple):
            xcoord, ycoord = self.boxcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrunk by shrinkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA) 
Example 58
Project: linear_neuron   Author: uglyboxer   File: offsetbox.py    MIT License 4 votes vote down vote up
def _update_position_xybox(self, renderer, xy_pixel):
        """
        Update the pixel positions of the annotation text and the arrow
        patch.
        """

        x, y = self.xybox
        if isinstance(self.boxcoords, tuple):
            xcoord, ycoord = self.boxcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrinked by shirnkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA) 
Example 59
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_patches.py    MIT License 4 votes vote down vote up
def test_patch_str():
    """
    Check that patches have nice and working `str` representation.

    Note that the logic is that `__str__` is defined such that:
    str(eval(str(p))) == str(p)
    """
    p = mpatches.Circle(xy=(1, 2), radius=3)
    assert str(p) == 'Circle(xy=(1, 2), radius=3)'

    p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)
    assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'

    p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)
    expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'
    assert str(p) == expected

    p = mpatches.RegularPolygon((1, 2), 20, radius=5)
    assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)"

    p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20)
    assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)"

    p = mpatches.FancyBboxPatch((1, 2), width=3, height=4)
    assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)"

    # Further nice __str__ which cannot be `eval`uated:
    path_data = [([1, 2], mpath.Path.MOVETO), ([2, 2], mpath.Path.LINETO),
                 ([1, 2], mpath.Path.CLOSEPOLY)]
    p = mpatches.PathPatch(mpath.Path(*zip(*path_data)))
    assert str(p) == "PathPatch3((1, 2) ...)"

    data = [[1, 2], [2, 2], [1, 2]]
    p = mpatches.Polygon(data)
    assert str(p) == "Polygon3((1, 2) ...)"

    p = mpatches.FancyArrowPatch(path=mpath.Path(*zip(*path_data)))
    assert str(p)[:27] == "FancyArrowPatch(Path(array("

    p = mpatches.FancyArrowPatch((1, 2), (3, 4))
    assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))"

    p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data')
    assert str(p) == "ConnectionPatch((1, 2), (3, 4))"

    s = mpatches.Shadow(p, 1, 1)
    assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"

    with pytest.warns(MatplotlibDeprecationWarning):
        p = mpatches.YAArrow(plt.gcf(), (1, 0), (2, 1), width=0.1)
        assert str(p) == "YAArrow()"

    # Not testing Arrow, FancyArrow here
    # because they seem to exist only for historical reasons. 
Example 60
Project: paper-flowmap-code   Author: caesar0301   File: utils.py    GNU General Public License v3.0 4 votes vote down vote up
def draw_network(G, pos, ax):
    """Draw network with curved edges.

    Examples
    --------

    plt.figure(figsize=(10, 10))
    ax=plt.gca()
    pos=nx.spring_layout(G)
    draw_network(G, pos, ax)
    ax.autoscale()
    plt.axis('equal')
    plt.axis('off')
    plt.title('Curved network')

    """
    # ax=plt.gca()
    # pos=nx.spring_layout(motif)
    # draw_network(motif, pos, ax)


    for n in G:
        c = Circle(pos[n], radius=0.05, alpha=0.5)
        ax.add_patch(c)
        G.node[n]['patch'] = c
    seen={}
    for (u,v,d) in G.edges(data=True):
        n1 = G.node[u]['patch']
        n2 = G.node[v]['patch']
        rad = 0.1
        if (u,v) in seen:
            rad = seen.get((u,v))
            rad = (rad + np.sign(rad) * 0.1) * -1
        alpha = 0.5; color = 'k'
        e = FancyArrowPatch(n1.center, n2.center,
                            patchA=n1, patchB=n2,
                            arrowstyle='-|>',
                            connectionstyle='arc3,rad=%s' % rad,
                            mutation_scale=10.0,
                            lw=2, alpha=alpha, color=color)
        seen[(u, v)] = rad
        ax.add_patch(e)

    # ax.autoscale()
    # plt.axis('equal')
    # plt.axis('off')

    return e 
Example 61
Project: rpl-attacks   Author: dhondta   File: parser.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def __draw_dodag(path, logger=None):
    """
    This function draws the DODAG (to ./results) from the list of motes (from ./simulation.csc) and the list of
     edges (from ./data/relationships.log).

    :param path: path to the experiment (including [with-|without-malicious])
    :param logger: logging.Logger instance
    """
    if logger:
        logger.debug(" > Drawing DODAG to PNG...")
    pyplot.clf()
    with_malicious = (basename(normpath(path)) == 'with-malicious')
    data, results = join(path, 'data'), join(path, 'results')
    with open(join(data, 'relationships.log')) as f:
        relationships = f.read()
    # first, check if the mote relationships were recorded
    if len(relationships.strip()) == 0:
        if logger:
            logger.warn("Relationships log file is empty !")
        return
    # retrieve motes and their colors
    dodag = networkx.DiGraph()
    motes = get_motes_from_simulation(join(path, 'simulation.csc'))
    dodag.add_nodes_from(motes.keys())
    colors = []
    for n, p in motes.items():
        x, y = p
        dodag.node[n]['pos'] = motes[n] = (x, -y)
        colors.append('green' if n == 0 else ('yellow' if not with_malicious or
                                              (with_malicious and 0 < n < len(motes) - 1) else 'red'))
    # retrieve edges from relationships.log
    edges = {}
    for relationship in relationships.split('\n'):
        try:
            d = match(RELATIONSHIP_REGEX, relationship.strip()).groupdict()
            if int(d['flag']) == 0:
                continue
            mote, parent = int(d['mote_id']), int(d['parent_id'])
            edges[mote] = parent
        except AttributeError:
            continue
    # now, fill in the graph with edges
    dodag.add_edges_from(edges.items())
    # finally, draw the graph
    networkx.draw(dodag, motes, node_color=colors, with_labels=True)
    pyplot.savefig(join(results, 'dodag.png'), arrow_style=FancyArrowPatch) 
Example 62
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_patches.py    MIT License 4 votes vote down vote up
def test_patch_str():
    """
    Check that patches have nice and working `str` representation.

    Note that the logic is that `__str__` is defined such that:
    str(eval(str(p))) == str(p)
    """
    p = mpatches.Circle(xy=(1, 2), radius=3)
    assert str(p) == 'Circle(xy=(1, 2), radius=3)'

    p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)
    assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'

    p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)
    expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'
    assert str(p) == expected

    p = mpatches.RegularPolygon((1, 2), 20, radius=5)
    assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)"

    p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20)
    assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)"

    p = mpatches.FancyBboxPatch((1, 2), width=3, height=4)
    assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)"

    # Further nice __str__ which cannot be `eval`uated:
    path_data = [([1, 2], mpath.Path.MOVETO), ([2, 2], mpath.Path.LINETO),
                 ([1, 2], mpath.Path.CLOSEPOLY)]
    p = mpatches.PathPatch(mpath.Path(*zip(*path_data)))
    assert str(p) == "PathPatch3((1, 2) ...)"

    data = [[1, 2], [2, 2], [1, 2]]
    p = mpatches.Polygon(data)
    assert str(p) == "Polygon3((1, 2) ...)"

    p = mpatches.FancyArrowPatch(path=mpath.Path(*zip(*path_data)))
    assert str(p)[:27] == "FancyArrowPatch(Path(array("

    p = mpatches.FancyArrowPatch((1, 2), (3, 4))
    assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))"

    p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data')
    assert str(p) == "ConnectionPatch((1, 2), (3, 4))"

    s = mpatches.Shadow(p, 1, 1)
    assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"

    with pytest.warns(MatplotlibDeprecationWarning):
        p = mpatches.YAArrow(plt.gcf(), (1, 0), (2, 1), width=0.1)
        assert str(p) == "YAArrow()"

    # Not testing Arrow, FancyArrow here
    # because they seem to exist only for historical reasons. 
Example 63
Project: ImageFusion   Author: pfchai   File: offsetbox.py    MIT License 4 votes vote down vote up
def _update_position_xybox(self, renderer, xy_pixel):
        """
        Update the pixel positions of the annotation text and the arrow
        patch.
        """

        x, y = self.xybox
        if isinstance(self.boxcoords, tuple):
            xcoord, ycoord = self.boxcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrinked by shirnkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA) 
Example 64
Project: Blackjack-Tracker   Author: martinabeleda   File: offsetbox.py    MIT License 4 votes vote down vote up
def _update_position_xybox(self, renderer, xy_pixel):
        """
        Update the pixel positions of the annotation text and the arrow
        patch.
        """

        x, y = self.xybox
        if isinstance(self.boxcoords, tuple):
            xcoord, ycoord = self.boxcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrinked by shirnkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA) 
Example 65
Project: network_line_graph   Author: paulbrodersen   File: network_line_graph.py    GNU General Public License v3.0 4 votes vote down vote up
def _add_edge(source, target,
              node_positions,
              node_artists,
              edge_width,
              edge_color,
              arc_above,
              draw_arrows,
              ax):

    source_pos = node_positions[source]
    target_pos = node_positions[target]

    # base radius expressed as a fraction of the half-distance between nodes
    rad = 1.

    # make sure that edges going right to left are plotted on correct side of x-axis;
    # prevent bidirectional connections to be plotted on top of each other
    # by scaling them slightly differently
    if target_pos[0] - source_pos[0] > 0:
        rad *= 1.1
    else:
        rad *= -0.9

    # negative radius for clockwise curve
    if arc_above:
        rad *= -1

    if draw_arrows:
        arrowstyle = "fancy,head_length={},head_width={},tail_width={}".format(2*edge_width, 3*edge_width, edge_width)
    else: # make arrow heads really small
        arrowstyle = "fancy,head_length={},head_width={},tail_width={}".format(1e-10, 1e-10, edge_width)

    # stop edges from being plotted on top or bottom of node artists;
    if node_artists:
        patchA = node_artists[(source, 'edge')]
        patchB = node_artists[(target, 'edge')]

    arrow = FancyArrowPatch(source_pos, target_pos,
                            connectionstyle="arc3,rad={}".format(rad),
                            arrowstyle=arrowstyle,
                            patchA=patchA,
                            patchB=patchB,
                            facecolor=edge_color,
                            edgecolor='none')
    ax.add_patch(arrow)

    return arrow 
Example 66
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_patches.py    GNU General Public License v3.0 4 votes vote down vote up
def test_patch_str():
    """
    Check that patches have nice and working `str` representation.

    Note that the logic is that `__str__` is defined such that:
    str(eval(str(p))) == str(p)
    """
    p = mpatches.Circle(xy=(1, 2), radius=3)
    assert str(p) == 'Circle(xy=(1, 2), radius=3)'

    p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)
    assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'

    p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)
    expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'
    assert str(p) == expected

    p = mpatches.RegularPolygon((1, 2), 20, radius=5)
    assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)"

    p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20)
    assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)"

    p = mpatches.FancyBboxPatch((1, 2), width=3, height=4)
    assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)"

    # Further nice __str__ which cannot be `eval`uated:
    path_data = [([1, 2], mpath.Path.MOVETO), ([2, 2], mpath.Path.LINETO),
                 ([1, 2], mpath.Path.CLOSEPOLY)]
    p = mpatches.PathPatch(mpath.Path(*zip(*path_data)))
    assert str(p) == "PathPatch3((1, 2) ...)"

    data = [[1, 2], [2, 2], [1, 2]]
    p = mpatches.Polygon(data)
    assert str(p) == "Polygon3((1, 2) ...)"

    p = mpatches.FancyArrowPatch(path=mpath.Path(*zip(*path_data)))
    assert str(p)[:27] == "FancyArrowPatch(Path(array("

    p = mpatches.FancyArrowPatch((1, 2), (3, 4))
    assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))"

    p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data')
    assert str(p) == "ConnectionPatch((1, 2), (3, 4))"

    s = mpatches.Shadow(p, 1, 1)
    assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"

    with pytest.warns(MatplotlibDeprecationWarning):
        p = mpatches.YAArrow(plt.gcf(), (1, 0), (2, 1), width=0.1)
        assert str(p) == "YAArrow()"

    # Not testing Arrow, FancyArrow here
    # because they seem to exist only for historical reasons. 
Example 67
Project: cnidaria   Author: sauloal   File: offsetbox.py    MIT License 4 votes vote down vote up
def _update_position_xybox(self, renderer, xy_pixel):
        """
        Update the pixel positions of the annotation text and the arrow
        patch.
        """

        x, y = self.xybox
        if isinstance(self.boxcoords, tuple):
            xcoord, ycoord = self.boxcoords
            x1, y1 = self._get_xy(renderer, x, y, xcoord)
            x2, y2 = self._get_xy(renderer, x, y, ycoord)
            ox0, oy0 = x1, y2
        else:
            ox0, oy0 = self._get_xy(renderer, x, y, self.boxcoords)

        w, h, xd, yd = self.offsetbox.get_extent(renderer)

        _fw, _fh = self._box_alignment
        self.offsetbox.set_offset((ox0 - _fw * w + xd, oy0 - _fh * h + yd))

        # update patch position
        bbox = self.offsetbox.get_window_extent(renderer)
        #self.offsetbox.set_offset((ox0-_fw*w, oy0-_fh*h))
        self.patch.set_bounds(bbox.x0, bbox.y0,
                              bbox.width, bbox.height)

        x, y = xy_pixel

        ox1, oy1 = x, y

        if self.arrowprops:
            x0, y0 = x, y

            d = self.arrowprops.copy()

            # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.

            # adjust the starting point of the arrow relative to
            # the textbox.
            # TODO : Rotation needs to be accounted.
            relpos = self._arrow_relpos

            ox0 = bbox.x0 + bbox.width * relpos[0]
            oy0 = bbox.y0 + bbox.height * relpos[1]

            # The arrow will be drawn from (ox0, oy0) to (ox1,
            # oy1). It will be first clipped by patchA and patchB.
            # Then it will be shrinked by shirnkA and shrinkB
            # (in points). If patch A is not set, self.bbox_patch
            # is used.

            self.arrow_patch.set_positions((ox0, oy0), (ox1, oy1))
            fs = self.prop.get_size_in_points()
            mutation_scale = d.pop("mutation_scale", fs)
            mutation_scale = renderer.points_to_pixels(mutation_scale)
            self.arrow_patch.set_mutation_scale(mutation_scale)

            patchA = d.pop("patchA", self.patch)
            self.arrow_patch.set_patchA(patchA)