示例#1
0
def plotte_gradientenabstieg(f, pfad):
    x = np.linspace(-6.5, 6.5, 100)
    plt.figure(figsize=(6, 8))

    # Zunaechst die Funktion einzeichnen
    plt.plot(x, f(x))
    ax = plt.gca()

    # Dann Pfeile einzeichnen für den Gradientenabstieg
    # OH DIESE PFEILE IN MATPLOTLIB!
    for i in range(0, len(pfad) - 1):
        posA = (pfad[i], f(pfad[i]))
        posB = (pfad[i + 1], f(pfad[i]))
        p = FancyArrowPatch(posA=posA,
                            posB=posB,
                            arrowstyle='fancy, head_width=6, head_length=4',
                            color='red')
        ax.add_artist(p)
        posA = posB
        posB = (pfad[i + 1], f(pfad[i + 1]))
        p = FancyArrowPatch(posA=posA,
                            posB=posB,
                            arrowstyle='fancy, head_width=6, head_length=4',
                            color='grey')
        ax.add_artist(p)
示例#2
0
def plot_north_cross(lon0, lat0, basemap, ax=None):
    """
    :type ax: Axes
    """
    d = 2
    lonw = lon0 - d
    lone = lon0 + d
    latn = lat0 + d
    lats = lat0 - d

    west_point = basemap(lonw, lat0)
    east_point = basemap(lone, lat0)
    north_point = basemap(lon0, latn)
    south_point = basemap(lon0, lats)

    # hor_line = Line2D([xe, xw], [ye, yw], color="k")
    ax.add_line(
        FancyArrowPatch(south_point,
                        north_point,
                        arrowstyle="->",
                        mutation_scale=30,
                        linewidth=4))
    ax.add_line(
        FancyArrowPatch(east_point,
                        west_point,
                        arrowstyle="-",
                        mutation_scale=30,
                        linewidth=4))
    ax.annotate("N",
                xy=north_point,
                va="bottom",
                ha="center",
                font_properties=FontProperties(weight="bold", size=20))

    pass
def draw_vthresh(ax, x):
    """ draws a threshold """
    ylim = ax.get_ylim()
    xlim = ax.get_xlim()
    ax.fill_between([xlim[0], x], [ylim[1], ylim[1]], alpha=0.2, color=dlblue)
    ax.fill_between([x, xlim[1]], [ylim[1], ylim[1]],
                    alpha=0.2,
                    color=dldarkred)
    ax.annotate("z >= 0",
                xy=[x, 0.5],
                xycoords='data',
                xytext=[30, 5],
                textcoords='offset points')
    d = FancyArrowPatch(
        posA=(x, 0.5),
        posB=(x + 3, 0.5),
        color=dldarkred,
        arrowstyle='simple, head_width=5, head_length=10, tail_width=0.0',
    )
    ax.add_artist(d)
    ax.annotate("z < 0",
                xy=[x, 0.5],
                xycoords='data',
                xytext=[-50, 5],
                textcoords='offset points',
                ha='left')
    f = FancyArrowPatch(
        posA=(x, 0.5),
        posB=(x - 3, 0.5),
        color=dlblue,
        arrowstyle='simple, head_width=5, head_length=10, tail_width=0.0',
    )
    ax.add_artist(f)
def draw_network(G, pos, ax, sg=None):
    nx.draw_networkx_nodes(G,
                           pos,
                           nodelist=G.nodes,
                           node_size=120,
                           node_color='k',
                           alpha=.9)
    nx.draw_networkx_nodes(G, pos, node_size=100, node_color='w', alpha=1)
    for n in G:
        c = Circle(pos[n], radius=.01, alpha=0.1)
        ax.add_patch(c)
        G.node[n]['patch'] = c
        x, y = pos[n]

    nx.draw_networkx_labels(G,
                            pos,
                            font_size=10,
                            font_family='sans-serif',
                            font_color='k')

    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
        colors = ['green', 'purple', 'black', 'white']
        lw = 2

        if d['weight'] > 0.0:
            alpha = 0.5
            e = FancyArrowPatch(n1.center,
                                n2.center,
                                patchA=n1,
                                patchB=n2,
                                arrowstyle='-|>',
                                connectionstyle='arc3,rad=%s' % rad,
                                mutation_scale=10.0,
                                lw=lw,
                                alpha=alpha,
                                color=colors[0])
            seen[(u, v)] = rad
            ax.add_patch(e)
        else:
            alpha = 0.25
            e = FancyArrowPatch(n1.center,
                                n2.center,
                                patchA=n1,
                                patchB=n2,
                                arrowstyle='-|>',
                                connectionstyle='arc3,rad=%s' % rad,
                                mutation_scale=10.0,
                                lw=lw,
                                alpha=alpha,
                                color=colors[1])
            seen[(u, v)] = rad
            ax.add_patch(e)
    return e
示例#5
0
def draw_cartesian_coord_system(axis, dim):

    arrow_prop_dict = dict(mutation_scale=20,
                           linewidth=2,
                           arrowstyle='->',
                           shrinkA=0,
                           shrinkB=0)

    if dim.lower() == '2d':
        axis.add_artist(
            FancyArrowPatch([0, 0], [0, 0.2], **arrow_prop_dict, color='r'))
        axis.add_artist(
            FancyArrowPatch([0, 0], [0.2, 0], **arrow_prop_dict, color='b'))
        axis.text(-0.02, -0.02, r'$O$')
        axis.text(0.22, 0, r'$X$')
        axis.text(0, 0.22, r'$Y$')
    elif dim.lower() == '3d':
        arrow_prop_dict = dict(mutation_scale=20,
                               arrowstyle='->',
                               shrinkA=0,
                               shrinkB=0)
        axis.add_artist(
            Arrow3D([0, 1], [0, 0], [0, 0], **arrow_prop_dict, color='r'))
        axis.add_artist(
            Arrow3D([0, 0], [0, 1], [0, 0], **arrow_prop_dict, color='b'))
        axis.add_artist(
            Arrow3D([0, 0], [0, 0], [0, 1], **arrow_prop_dict, color='g'))
        axis.text(0.0, 0.0, -0.1, r'$O$')
        axis.text(1.1, 0, 0, r'$X$')
        axis.text(0, 1.1, 0, r'$Y$')
        axis.text(0, 0, 1.1, r'$Z$')
    else:
        raise ValueError('dim must be 2D or 3D.')
示例#6
0
def add_arrow(ax1, ax2, label="", kind="straight", eps=0):
    fig = ax1.figure

    if kind == "straight":
        fig.patches.append(
            FancyArrowPatch(
                fig.transFigure.inverted().transform(
                    ax1.transData.transform((-0.9, 0))),
                fig.transFigure.inverted().transform(
                    ax2.transData.transform((0.9 - eps, 0))),
                transform=fig.transFigure,
                fc="k",
                arrowstyle="-|>",
                alpha=1,
                mutation_scale=10.0,
            ))
        ax1.text(
            -0.3,
            0.65,
            label,
            transform=ax1.transAxes,
            size=15,
            weight="bold",
            ha="center",
            va="center",
        )
    else:
        if kind == "bar_up":
            ytext = 1.15
            sgn = -1
        else:
            ytext = -0.15
            sgn = 1
        fig.patches.append(
            FancyArrowPatch(
                fig.transFigure.inverted().transform(
                    ax1.transData.transform((-0.9, 0))),
                fig.transFigure.inverted().transform(
                    ax2.transData.transform((0.9 - eps, 0))),
                transform=fig.transFigure,
                fc="k",
                arrowstyle="-|>",
                connectionstyle="bar,angle=90,fraction={}".format(sgn * 0.2),
                alpha=1,
                mutation_scale=10.0,
            ))
        ax1.text(
            -0.18,
            ytext,
            label,
            transform=ax1.transAxes,
            size=15,
            weight="bold",
            ha="center",
            va="center",
        )
示例#7
0
    def update_compass(self, *args, **kwargs):

        if not self._compass_show:
            return

        rx, ry = self._compass_position
        length = self._compass_length
        color = self._compass_color

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

        x0 = rx * (xmax - xmin) + xmin
        y0 = ry * (ymax - ymin) + ymin

        xw, yw = self.pixel2world(x0, y0)

        len_pix = length * (ymax - ymin)

        degrees_per_pixel = wcs_util.celestial_pixel_scale(self._wcs)

        len_deg = len_pix * degrees_per_pixel

        # Should really only do tiny displacement then magnify the vectors - important if there is curvature

        x1, y1 = self.world2pixel(xw + len_deg / np.cos(np.radians(yw)), yw)
        x2, y2 = self.world2pixel(xw, yw + len_deg)

        if self._compass:
            self._compass[0].remove()
            self._compass[1].remove()

        arrow1 = FancyArrowPatch(posA=(x0, y0),
                                 posB=(x1, y1),
                                 arrowstyle='-|>',
                                 mutation_scale=20.,
                                 fc=color,
                                 ec=color,
                                 shrinkA=0.,
                                 shrinkB=0.)
        arrow2 = FancyArrowPatch(posA=(x0, y0),
                                 posB=(x2, y2),
                                 arrowstyle='-|>',
                                 mutation_scale=20.,
                                 fc=color,
                                 ec=color,
                                 shrinkA=0.,
                                 shrinkB=0.)

        self._compass = (arrow1, arrow2)

        self._ax1.add_patch(arrow1)
        self._ax1.add_patch(arrow2)
def display_bicycle_wheels(rear_wheel, front_wheel, theta):               
    # Initialize figure
    fig = plt.figure(figsize=(5, 5))
    ax = plt.gca()
    ax.set_xlim([0,4])
    ax.set_ylim([0,4])
    ax.tick_params(axis='both', which='major', labelsize=7)
    plt.title('Overhead View')
    plt.xlabel('X (m)',weight='bold')
    plt.ylabel('Y (m)',weight='bold')

    ax.plot(0,0)
  
    rear_wheel_x = FancyArrowPatch((0,0), (0.4,0),
                                        mutation_scale=8,color='red')
    rear_wheel_y = FancyArrowPatch((0,0), (0,0.4),
                                        mutation_scale=8,color='red')

    front_wheel_x = FancyArrowPatch((0,0), (0.4,0),
                                        mutation_scale=8,color='blue') 
    front_wheel_y = FancyArrowPatch((0,0), (0,0.4),
                                        mutation_scale=8,color='blue')

    custom_lines = [Line2D([0], [0], color='red', lw=4),
                    Line2D([0], [0], color='blue', lw=4)]
    
    # Apply translation and rotation as specified by current robot state
    cos_theta, sin_theta = np.cos(theta), np.sin(theta)
    Tw_rear = np.eye(3)
    Tw_rear[0:2,2] = rear_wheel
    Tw_rear[0:2,0:2] = [[cos_theta,-sin_theta],[sin_theta,cos_theta]]
    Tw_rear_obj = transforms.Affine2D(Tw_rear)

    Tw_front = np.eye(3)
    Tw_front[0:2,2] = front_wheel
    Tw_front[0:2,0:2] = [[cos_theta,-sin_theta],[sin_theta,cos_theta]]
    Tw_front_obj = transforms.Affine2D(Tw_front)

    ax_trans = ax.transData
    
    rear_wheel_x.set_transform(Tw_rear_obj+ax_trans)
    rear_wheel_y.set_transform(rear_wheel_x.get_transform())
    ax.add_patch(rear_wheel_x)
    ax.add_patch(rear_wheel_y)

    front_wheel_x.set_transform(Tw_front_obj+ax_trans)
    front_wheel_y.set_transform(front_wheel_x.get_transform())
    ax.add_patch(front_wheel_x)
    ax.add_patch(front_wheel_y)

    ax.legend(custom_lines, ['Rear Wheel', 'Front Wheel']) 
        
示例#9
0
def plot_C_arrows(ax, pos, C, R=None, c_index=0, scale=1., **kwargs):
    """ Plot growth constants as arrows.

    Parameters
    ----------
    ax : matplotlib.axes.Axes
        Axes on which the arrows will be drawn.
    pos : torch.Tensor
        Positions of the growth constants arrows.
    C : torch.Tensor
        Growth constants.
    R : torch.Tensor, default=None
        Local frame of each positions. If none, will assume idendity.
    c_index : int, default=0
        The dimension of the growth constants that will get drawn.
    scale : float, default=1.
        Scale applied to the arrow lengths.
    kwargs : dict
        Keyword arguments that gets passed to the underlying matplotlib plot
        functions.
    """
    for i in range(pos.shape[0]):
        C_i = scale * C[i, :, c_index]

        arrowstyle_x = "<->"
        arrowstyle_y = "<->"
        if C_i[0] <= 0.:
            arrowstyle_x += ",head_length=-0.4"
        if C_i[1] <= 0.:
            arrowstyle_y += ",head_length=-0.4"

        if R is not None:
            rotmat = R[i].numpy()
        else:
            rotmat = np.eye(2)

        top_pos = np.dot(rotmat, np.array([0., C_i[1] / 2.])) + pos[i].numpy()
        bot_pos = np.dot(rotmat, -np.array([0., C_i[1] / 2])) + pos[i].numpy()
        left_pos = np.dot(rotmat, -np.array([C_i[0] / 2, 0.])) + pos[i].numpy()
        right_pos = np.dot(rotmat, np.array([C_i[0] / 2, 0.])) + pos[i].numpy()

        ax.add_patch(
            FancyArrowPatch(left_pos,
                            right_pos,
                            arrowstyle=arrowstyle_x,
                            **kwargs))
        ax.add_patch(
            FancyArrowPatch(bot_pos,
                            top_pos,
                            arrowstyle=arrowstyle_y,
                            **kwargs))
    def __set_animation_layout(self):
        """
        Adds layout components that are required for an animation
        """

        offset = self.__offset
        o_width = self.__width_u
        phi_o = self._agent.phi + offset
        gamma_o = self._agent.gamma + offset

        # U flow (R1)
        self._arr_u_flow = FancyArrowPatch((o_width, phi_o),
                                           (o_width + 0.1, phi_o),
                                           arrowstyle='simple',
                                           mutation_scale=0,
                                           ec='white',
                                           fc=self.__u_color)
        self._ann_u_flow = Text(text="flow: ", ha='right', fontsize="large", x=o_width, y=phi_o - 0.05)

        # Tap flow (Power)
        self._arr_power_flow = FancyArrowPatch((self._ann_lf.get_position()[0], offset - 0.05),
                                               (self._ann_lf.get_position()[0], 0.0),
                                               arrowstyle='simple',
                                               mutation_scale=0,
                                               ec='white',
                                               color=self.__p_color)
        self._ann_power_flow = Text(text="flow: ", ha='center', fontsize="large", x=self._ann_lf.get_position()[0],
                                    y=offset - 0.05)

        # LS flow (R2)
        self._arr_r2_l_pos = [(self._ls.get_x(), gamma_o),
                              (self._ls.get_x() - 0.1, gamma_o)]
        self._arr_r2_flow = FancyArrowPatch(self._arr_r2_l_pos[0],
                                            self._arr_r2_l_pos[1],
                                            arrowstyle='simple',
                                            mutation_scale=0,
                                            ec='white',
                                            color=self.__ls_color)
        self._ann_r2_flow = Text(text="flow: ", ha='left', fontsize="large", x=self._ls.get_x(),
                                 y=gamma_o - 0.05)

        # information annotation
        self._ann_time = Text(x=1, y=0.9 + offset, ha="right")

        self._ax1.add_artist(self._ann_power_flow)
        self._ax1.add_artist(self._arr_power_flow)
        self._ax1.add_artist(self._arr_u_flow)
        self._ax1.add_artist(self._ann_u_flow)
        self._ax1.add_artist(self._arr_r2_flow)
        self._ax1.add_artist(self._ann_r2_flow)
def arrow(x, y, ax, n, z=None):
    d = len(x) // (n + 1)
    ind = np.arange(d, len(x), d)
    for i in ind:
        if z is None:
            ar = FancyArrowPatch((x[i - 1], y[i - 1]), (x[i], y[i]),
                                 arrowstyle='->',
                                 mutation_scale=20)
        else:
            ar = FancyArrowPatch((x[i - 1], y[i - 1], z[i - 1]),
                                 (x[i], y[i], z[i]),
                                 arrowstyle='->',
                                 mutation_scale=20)
        ax.add_patch(ar)
示例#12
0
    def init_artists(self):
        main_arrow_props = {
            "alpha": 0.5 if not self.active else 0.2,
            "animated": True,
            "arrowstyle": "->,head_length=10,head_width=7",
            "color": self.color,
            "linestyle": "solid",
        }

        opp_arrow_props = {
            "alpha": 0.3 if not self.active else 0.1,
            "animated": True,
            "arrowstyle": "->,head_length=10,head_width=7",
            "color": self.color,
            "linestyle": "dashed",
        }

        line_props = {
            "alpha": 0.7 if not self.active else 0.3,
            "animated": True,
            "color": self.color,
            "linestyle": "",
            "marker": "x",
            "markerfacecolor": self.color,
            "markersize": 8,
            "markevery": [1],
        }

        cx, cy = self.cxy
        wx, wy = self.wxy
        dx, dy = wx - cx, wy - cy

        # main arrow
        main_arrow = FancyArrowPatch(self.cxy, self.wxy, **main_arrow_props)
        self.artists["main_arrow"] = main_arrow
        self.axes.add_patch(main_arrow)

        # opposite arrow
        opp_arrow = FancyArrowPatch(self.cxy, (cx - dx, cy - dy), **opp_arrow_props)
        self.artists["opp_arrow"] = opp_arrow
        self.axes.add_patch(opp_arrow)

        # line
        (line,) = self.axes.plot(
            [cx - dx, cx, cx + dx], [cy - dy, cy, cy + dy], **line_props
        )
        self.artists["line"] = line
        self.axes.add_line(line)
    def initialize(self, states, dt_render=0.2, dt_data=0.02):
        self.lock = thrd.Lock()
        
        self.initialized = False
        self.paused = False
        self.cur_frame = 0
        self.dt_render = dt_render
        self.dt_data = dt_data
                        
        # Initialize figure
        fig = plt.figure(figsize=(5, 5))
        ax = plt.gca()
        ax.set_xlim([-10, 10])
        ax.set_ylim([-10, 10])
        ax.tick_params(axis='both', which='major', labelsize=7)
        plt.title('Overhead View')
        plt.xlabel('X (m)',weight='bold')
        plt.ylabel('Y (m)',weight='bold')

        self.states = states
        self.figure = fig
        
        self.line, = ax.plot(states[0,0], states[0,1])
            
        # Create Robot Axes 
        self.robot_ax = []
        self.robot_ax.append(FancyArrowPatch((0,0), (1,0),
                                            mutation_scale=8,color='red'))
        self.robot_ax.append(FancyArrowPatch((0,0), (0,1),
                                            mutation_scale=8,color='green'))
        
        # Apply translation and rotation as specified by current robot state
        cos_theta, sin_theta = np.cos(states[0,2]), np.sin(states[0,2])
        Tw_r = np.eye(3)
        Tw_r[0:2,2] = [0, 0]
        Tw_r[0:2,0:2] = [[cos_theta,-sin_theta],[sin_theta,cos_theta]]
        Tw_r_obj = transforms.Affine2D(Tw_r)
        self.ax_trans = ax.transData
        self.robot_ax[0].set_transform(Tw_r_obj+self.ax_trans)
        self.robot_ax[1].set_transform(self.robot_ax[0].get_transform())
        ax.add_patch(self.robot_ax[0])
        ax.add_patch(self.robot_ax[1])
                
        
        if not self.is_alive():
            self.start()
            
        self.initialized = True
def gen_patches(drop, h, resolution=64):
    """Generate patches for droplet at height h
    """
    # Generate arc starting form theta1 to theta2
    def gen_arc(center, r, theta1, theta2):
        t = numpy.linspace(theta1, theta2, resolution)
        vert = r * numpy.vstack((numpy.cos(t),
                                 numpy.sin(t))).T
        return vert + center
    print(h)
    drop.h = h                  # set height and update
    delta_t, delta_b = drop.get_separate_height()
    r1 = drop.r1; r2 = drop.r2
    t_t = drop.theta_t; t_b = drop.theta_b
    center_r = (r1 - r2, delta_b)
    center_l = (-(r1 - r2), delta_b)
    v_r = gen_arc(center_r, r2,
                  -(t_b - pi / 2), (t_t - pi / 2))
    v_l = gen_arc(center_l, r2,
                  pi - (t_t - pi / 2),
                  pi + (t_b - pi / 2))
    p_b = v_r[0]; p_t = v_r[-1]
    verts = numpy.concatenate((v_r, v_l, (p_b, p_b)))  # vertices for patch
    codes = [Path.MOVETO] + [Path.LINETO] * (resolution * 2) \
            + [Path.CLOSEPOLY]  # codes for path
    drop_patch = PathPatch(Path(verts, codes),
                           facecolor="#ccdfff")
    drop_patch.set_alpha(0.5)
    circle = Circle(center_r, radius=r2,
                    ls="--", fill=False,
                    linewidth=0.5,
                    edgecolor="#ffb4a5")

    arr1 = FancyArrowPatch((0, delta_b), (r1, delta_b),
                           mutation_scale=10,
                           linewidth=0,
                           facecolor="#9b9b9b")
    
    arr2 = FancyArrowPatch(center_r, p_t,
                           mutation_scale=10,
                           linewidth=0,
                           facecolor="#ffa047")

    pressure = drop.get_delta_stress()
    pr = (r1, delta_b)
    print(pr, p_t)
    return drop_patch, circle, arr1, arr2, \
           pressure, pr, p_t
示例#15
0
def draw_FA(G, pos, ax):
    # Draw NFA/DFA
    for n in G:
        c = Circle(pos[n], radius=0.1, alpha=0.7, color='red', gid='11')
        ax.add_patch(c)
        G.node[n]['patch'] = c
        ax.text(pos[n][0]-0.05, pos[n][1]-0.04, str(n))
    seen={}
    for (u,v,d) in G.edges(data=True):
        n1 = G.node[u]['patch']
        n2 = G.node[v]['patch']
        rad = 0.7
        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)
示例#16
0
    def _render_on_subplot(self, subplot):
        """
        Render this arrow in a subplot.  This is the key function that
        defines how this arrow graphics primitive is rendered in
        matplotlib's library.

        EXAMPLES:

        This function implicitly ends up rendering this arrow on
        a matplotlib subplot::

            sage: arrow((0,1), (2,-1))

        TESTS:

        The length of the ends (shrinkA and shrinkB) should not depend
        on the width of the arrow, because Matplotlib already takes
        this into account. See :trac:`12836`::

            sage: fig = Graphics().matplotlib()
            sage: sp = fig.add_subplot(1,1,1)
            sage: a = arrow((0,0), (1,1))
            sage: b = arrow((0,0), (1,1), width=20)
            sage: p1 = a[0]._render_on_subplot(sp)
            sage: p2 = b[0]._render_on_subplot(sp)
            sage: p1.shrinkA == p2.shrinkA
            True
            sage: p1.shrinkB == p2.shrinkB
            True

        """
        options = self.options()
        head = options.pop('head')
        if head == 0: style = '<|-'
        elif head == 1: style = '-|>'
        elif head == 2: style = '<|-|>'
        else:
            raise KeyError(
                'head parameter must be one of 0 (start), 1 (end) or 2 (both).'
            )
        width = float(options['width'])
        arrowshorten_end = float(options.get('arrowshorten', 0)) / 2.0
        arrowsize = float(options.get('arrowsize', 5))
        head_width = arrowsize
        head_length = arrowsize * 2.0
        color = to_mpl_color(options['rgbcolor'])
        from matplotlib.patches import FancyArrowPatch
        p = FancyArrowPatch((self.xtail, self.ytail), (self.xhead, self.yhead),
                            lw=width,
                            arrowstyle='%s,head_width=%s,head_length=%s' %
                            (style, head_width, head_length),
                            shrinkA=arrowshorten_end,
                            shrinkB=arrowshorten_end,
                            fc=color,
                            ec=color,
                            linestyle=options['linestyle'])
        p.set_zorder(options['zorder'])
        p.set_label(options['legend_label'])
        subplot.add_patch(p)
        return p
示例#17
0
    def init_artists(self):
        main_arrow_props: Dict[str, Any] = {
            "alpha": 0.5 if self.active else 0.2,
            "animated": True,
            "arrowstyle": "->,head_length=10,head_width=7",
            "color": self.color,
            "linestyle": "solid",
        }

        line_props: Dict[str, Any] = {
            "alpha": 0.7 if self.active else 0.3,
            "animated": True,
            "color": self.color,
            "linestyle": "",
            "marker": "x",
            "markerfacecolor": self.color,
            "markersize": 8,
            "markevery": [0],
        }

        cx, cy = self.cxy
        wx, wy = self.wxy

        # main arrow
        main_arrow = FancyArrowPatch(posA=self.cxy, posB=self.wxy, **main_arrow_props)
        self.artists["main_arrow"] = main_arrow
        self.axes.add_patch(main_arrow)

        # line
        (line,) = self.axes.plot([cx, wx], [cy, wy], **line_props)
        self.artists["line"] = line
        self.axes.add_line(line)
示例#18
0
 def plot_slip_linear(self,
                      planes,
                      lines,
                      sense=True,
                      arrowsize=radians(10),
                      arrowcolor="#4D4D4D",
                      footwall=False,
                      **kwargs):
     options = dict(self.slip_defaults.items() + kwargs.items())
     for plane, line in zip(planes, lines):
         arrow_from = cos(arrowsize / 2.) * plane + sin(
             arrowsize / 2.) * line
         arrow_to = cos(-arrowsize / 2.) * plane + sin(
             -arrowsize / 2.) * line
         if footwall:
             arrow_from, arrow_to = arrow_to, arrow_from
         X, Y = self.project((arrow_from, arrow_to))
         if not sense:
             self.axis.add_line(
                 Line2D(X, Y, c=arrowcolor, label='_nolegend_', **options))
         else:
             a, b = (X[0], Y[0]), (X[1], Y[1])
             self.axis.add_patch(
                 FancyArrowPatch(
                     a,
                     b,
                     shrinkA=0.0,
                     shrinkB=0.0,
                     arrowstyle='->,head_length=2.5,head_width=1',
                     connectionstyle='arc3,rad=0.0',
                     mutation_scale=2.0,
                     ec=arrowcolor,
                     **options))
示例#19
0
    def draw(self, ax=None):
        self.ax = ax or self.ax or plt.gca()

        x1, y1 = np.cos(self.angle) * self.circ_stretch * self.r, np.sin(
            self.angle) * self.circ_stretch * self.r
        theta1 = self.angle + np.pi - self.shrink
        theta2 = self.angle - np.pi + self.shrink
        rs = np.linspace(theta2, theta1)
        xs = np.cos(rs) * self.circ_rad * self.r + x1
        ys = np.sin(rs) * self.circ_rad * self.r + y1
        path = Path(np.stack((xs, ys)).T)

        self.arrow = FancyArrowPatch(path=path,
                                     arrowstyle=ArrowStyle(
                                         self.arrowstyle,
                                         head_length=self.head_length,
                                         head_width=self.head_width),
                                     linewidth=self.edgewidth,
                                     color=self.edgecolor)

        self.ax.add_patch(self.arrow)

        if self.label is not None:
            self.ax.text(x1 * self.circ_stretch,
                         y1 * self.circ_stretch,
                         self.label,
                         horizontalalignment='center',
                         verticalalignment='center',
                         bbox=dict(facecolor=self.label_facecolor,
                                   edgecolor=self.label_edgecolor,
                                   alpha=0),
                         color=self.label_color,
                         fontname=self.fontname,
                         fontsize=self.fontsize)
示例#20
0
def draw_network(G, pos, ax, sg=None):
    for n in G:
        c = Circle(pos[n], radius=0.09, alpha=0.1, )
        ax.add_patch(c)
        G.node[n]['patch'] = c
        x, y = pos[n]
    seen = {}
    for (u, v, d) in G.edges(data=True):
        # print('-->',u,v,d)
        n1 = G.node[u]['patch']
        n2 = G.node[v]['patch']
        rad = 0.3
        if (u, v) in seen:
            rad = seen.get((u, v))
            rad = (rad + np.sign(rad) * 0.1) * -1
        alpha = d['weight'] / 10
        color = 'k'

        ast = ArrowStyle("-|>, head_length=" + str(
            (1 + alpha) * (1 + alpha) * (1 + alpha) * (1 + alpha) * (1 + alpha) / 14) + ", head_width=0.2")
        e = FancyArrowPatch(n1.center, n2.center, patchA=n1, patchB=n2,
                            arrowstyle=ast,
                            connectionstyle='arc3,rad=%s' % rad,
                            mutation_scale=17.0,
                            lw=2,
                            alpha=alpha,
                            color=color, linewidth=alpha * alpha + 0.3, antialiased=True)
        seen[(u, v)] = rad
        ax.add_patch(e)
    return e
示例#21
0
def arrowify(row):
    arrow = FancyArrowPatch(
        path=row["path"],
        arrowstyle="Simple,tail_width=0.005,head_width=0.2,head_length=0.4",
        alpha=row.alpha,
        color=row.edgecolor)
    return pd.Series(arrow)
示例#22
0
    def _plot_averted_arrow(axis, bar_4, tot_benefit, risk_tot, norm_fact,
                            **kwargs):
        """ Plot arrow inn fourth bar of total averted damage by implementing
        all the measures.

        Parameters:
            axis (matplotlib.axes._subplots.AxesSubplot, optional): axis to use
            bar_4 (matplotlib.container.BarContainer): bar where arrow is plotted
            tot_benefit (float): arrow length
            risk_tot (float): total risk
            norm_fact (float): normalization factor
            kwargs (optional): arguments for bar matplotlib function, e.g. alpha=0.5
        """
        bar_bottom, bar_top = bar_4.get_bbox().get_points()
        axis.text(bar_top[0] - (bar_top[0] - bar_bottom[0]) / 2,
                  bar_top[1],
                  "Averted",
                  ha="center",
                  va="top",
                  rotation=270,
                  size=15)
        arrow_len = min(tot_benefit / norm_fact, risk_tot / norm_fact)

        if 'color' not in kwargs:
            kwargs['color'] = 'k'
        if 'alpha' not in kwargs:
            kwargs['alpha'] = 0.4
        if 'mutation_scale' not in kwargs:
            kwargs['mutation_scale'] = 100
        axis.add_patch(FancyArrowPatch((bar_top[0] - (bar_top[0]-bar_bottom[0])/2, \
            bar_top[1]), (bar_top[0]- (bar_top[0]-bar_bottom[0])/2, \
            risk_tot/norm_fact-arrow_len), **kwargs))
示例#23
0
 def as_arrow_on_pole(self,
                      planes,
                      lines,
                      sense=True,
                      arrowsize=radians(10),
                      arrowcolor="#4D4D4D",
                      footwall=False,
                      **kwargs):
     options = ChainMap({}, kwargs, self.arrow_defaults)
     for plane, line in zip(planes, lines):
         arrow_from = (cos(arrowsize / 2.0) * plane +
                       sin(arrowsize / 2.0) * line)
         arrow_to = (cos(-arrowsize / 2.0) * plane +
                     sin(-arrowsize / 2.0) * line)
         if footwall:
             arrow_from, arrow_to = arrow_to, arrow_from
         X, Y = self.projection.direct((arrow_from, arrow_to))
         if not sense:
             self.axis.add_line(
                 Line2D(X, Y, c=arrowcolor, label="_nolegend_", **options))
         else:
             a, b = (X[0], Y[0]), (X[1], Y[1])
             self.axis.add_patch(
                 FancyArrowPatch(
                     a,
                     b,
                     shrinkA=0.0,
                     shrinkB=0.0,
                     arrowstyle="->,head_length=2.5,head_width=1",
                     connectionstyle="arc3,rad=0.0",
                     mutation_scale=2.0,
                     ec=arrowcolor,
                     **options))
def draw(G, pos, ax, name):
    for n in G:
        c = Circle(pos[n], radius=0.2, alpha=0.5)
        ax.add_patch(c)
        G.node[n]['patch'] = c
    for u, v in G.edges():
        n1 = G.node[u]['patch']
        n2 = G.node[v]['patch']
        e = FancyArrowPatch(n1.center,
                            n2.center,
                            patchA=n1,
                            patchB=n2,
                            arrowstyle='-|>',
                            connectionstyle='arc3,rad=0.2',
                            mutation_scale=10.0,
                            lw=1,
                            alpha=0.5,
                            color='k')
        ax.add_patch(e)
    ax.text(0.5,
            0.0,
            name,
            transform=ax.transAxes,
            horizontalalignment='center')
    ax.set_xlim(-1.0, 3.0)
    ax.set_ylim(-0.5, 1.5)
    plt.axis('equal')
    plt.axis('off')
    return
示例#25
0
    def draw(self, axes, feature, bbox, loc, style_param):
        from matplotlib.patches import FancyArrowPatch, ArrowStyle
        from matplotlib.path import Path

        x_center = bbox.x0 + bbox.width / 2
        y_center = bbox.y0 + bbox.height / 2

        path = Path(vertices=[
            (bbox.x0, y_center),
            (bbox.x0, y_center - bbox.height / 2 * self._head_height),
            (bbox.x1, y_center - bbox.height / 2 * self._head_height),
        ],
                    codes=[Path.MOVETO, Path.CURVE3, Path.CURVE3])
        style = ArrowStyle.CurveFilledB(head_width=self._head_width,
                                        head_length=self._head_length)
        arrow = FancyArrowPatch(path=path,
                                arrowstyle=style,
                                linewidth=self._line_width,
                                color="black")
        axes.add_patch(arrow)

        if "note" in feature.qual:
            axes.text(x_center,
                      y_center + bbox.height / 4,
                      feature.qual["note"],
                      color="black",
                      ha="center",
                      va="center",
                      size=9)
示例#26
0
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)
示例#27
0
def draw_connections(G, pos, node_colors, ax, edge_weights=None):

    alpha = 1.0
    for n in G:
        c = Ellipse(pos[n], width=0.015, height=0.015,
                    alpha=alpha, color=node_colors[n], clip_on=False)
        ax.add_patch(c)
        G.nodes[n]["patch"] = c
        x, y = pos[n]
    seen = {}
    alpha = 1.0  # 0.8
    for (u, v, d) in G.edges(data=True):
        n1 = G.nodes[u]["patch"]
        n2 = G.nodes[v]["patch"]
        rad = 0.1
        if (u, v) in seen:
            rad = seen.get((u, v))
            rad = (rad + np.sign(rad) * 0.1) * -1
        color = node_colors[u]
        e = FancyArrowPatch(n1.center,
                            n2.center,
                            patchA=n1,
                            patchB=n2,
                            shrinkA=0,
                            shrinkB=0,
                            arrowstyle='-',
                            linewidth=0.5,
                            connectionstyle="arc3, rad=%s" % rad,
                            mutation_scale=10.0,
                            alpha=alpha,
                            color=color,
                            clip_on=False)
        ax.add_patch(e)
        seen[(u, v)] = rad
示例#28
0
文件: pgm_viz.py 项目: whaozl/ibeis
    def draw_network(G, pos, ax, sg=None):
        for n in G:
            c = Circle(pos[n], radius=10, alpha=0.5, color=pt.NEUTRAL_BLUE)
            ax.add_patch(c)
            G.node[n]['patch'] = c
            x, y = pos[n]
            pt.ax_absolute_text(x, y, n, ha='center', va='center')
        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='-|>',
                arrowstyle='-',
                connectionstyle='arc3,rad=%s' % rad,
                mutation_scale=10.0,
                lw=2,
                alpha=alpha,
                color=color)
            seen[(u, v)] = rad
            ax.add_patch(e)
        return e
示例#29
0
def plot_fieldlines(ax, flines, pos=5, **kwargs):
    """Plot field lines with arrows.

    Parameters
    ----------
    ax: matplotlib axes
        Axes in which to plot the field lines.
    flines: list of 2D arrays
        The field lines.
    pos: float
        The position of the arrow on the field line in units of the coordinates.
    **kwargs: key word arguments
        Passed on to plot().
        Applies optional zorder argument also to arrow.
    """
    xmin, xmax = ax.get_xlim()
    ymin, ymax = ax.get_ylim()
    dx = 0.05 * np.abs(xmax - xmin)
    dy = 0.05 * np.abs(ymax - ymin)
    akwargs = dict()
    if 'zorder' in kwargs:
        akwargs['zorder'] = kwargs['zorder']
    lw = 1
    if 'lw' in kwargs:
        lw = kwargs['lw']
    if 'linewidth' in kwargs:
        lw = kwargs['linewidth']
    for fl in flines:
        ax.plot(fl[:, 0], fl[:, 1], **kwargs)
        # arrows:
        d = np.diff(fl, axis=0)
        dd = np.linalg.norm(d, axis=1)
        dist = np.cumsum(dd)
        if dist[-1] >= 6:
            idx0 = np.argmin(np.abs(dist - pos))
            if (np.abs(fl[0, 0] - xmin) < dx or np.abs(fl[0, 0] - xmax) < dx
                    or np.abs(fl[0, 1] - ymin) < dy
                    or np.abs(fl[0, 1] - ymax) < dy):
                idx0 = np.argmin(np.abs(dist[-1] - dist - pos))
            idx1 = np.argmin(np.abs(dist - 0.5 * dist[-1]))
            idx = min(idx0, idx1)
            adx = fl[idx + 1, :] - fl[idx, :]
            ndx = np.linalg.norm(adx)
            if ndx < 1e-10:
                continue
            adx /= ndx
            posa = fl[idx + 1, :] - 0.1 * min(dx, dy) * adx
            posb = fl[idx + 1, :]
            arrow = FancyArrowPatch(posA=posa,
                                    posB=posb,
                                    shrinkA=0,
                                    shrinkB=0,
                                    arrowstyle='fancy',
                                    mutation_scale=8 * lw,
                                    connectionstyle='arc3',
                                    fill=True,
                                    color=kwargs['color'],
                                    **akwargs)
            ax.add_patch(arrow)
示例#30
0
文件: os_plot.py 项目: spamlab-iee/os
 def plot_arrow(self, planes, lines, arrow_settings, has_sense, sliplinear):
     for plane, line, sense in zip(planes, lines, has_sense):
         if not sliplinear:  # FIXME: wrong name?
             arrowsize = radians(arrow_settings["arrowsize"])
             if plane[-1] > 0:
                 plane = -plane
             arrow_from = (
                 cos(arrowsize / 2.0) * plane + sin(arrowsize / 2.0) * line
             )
             arrow_to = (
                 cos(-arrowsize / 2.0) * plane
                 + sin(-arrowsize / 2.0) * line
             )
             if arrow_settings.get("footwall", False):
                 arrow_from, arrow_to = arrow_to, arrow_from
             X, Y = self.project(
                 *np.transpose((arrow_from, arrow_to)),
                 invert_positive=False
             )
         else:
             line_direction = line[:2] / np.linalg.norm(line[:2])
             dx, dy = line_direction * arrow_settings["arrowsize"] * 0.0075
             x, y = self.project(*line, invert_positive=True)
             X, Y = [x - dx, x + dx], [y - dy, y + dy]
         if not sense:
             self.plotaxes.add_line(
                 Line2D(
                     X,
                     Y,
                     c=arrow_settings["arrowcolor"],
                     label="_nolegend_",
                     lw=arrow_settings["lw"],
                     ls=arrow_settings["ls"],
                 )
             )
         else:
             a, b = (X[0], Y[0]), (X[1], Y[1])
             self.plotaxes.add_patch(
                 FancyArrowPatch(
                     a,
                     b,
                     shrinkA=0.0,
                     shrinkB=0.0,
                     arrowstyle="->,head_length=2.5,head_width=1",
                     connectionstyle="arc3,rad=0.0",
                     mutation_scale=2.0,
                     ec=arrow_settings["arrowcolor"],
                     lw=arrow_settings["lw"],
                     ls=arrow_settings["ls"],
                 )
             )
     return Line2D(
         X,
         Y,
         c=arrow_settings["arrowcolor"],
         label="_nolegend_",
         lw=arrow_settings["lw"],
         ls=arrow_settings["ls"],
     )