当前位置: 首页>>代码示例>>Python>>正文


Python pyplot.arrow函数代码示例

本文整理汇总了Python中matplotlib.pyplot.arrow函数的典型用法代码示例。如果您正苦于以下问题:Python arrow函数的具体用法?Python arrow怎么用?Python arrow使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了arrow函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: phaseportrait

def phaseportrait(fs,inits,t=(-5,5),n=100, head_width = 0.13, head_length = 0.3, **kw):
    """
    plots phase portrait of the differential equation (\dot x,\dot y)=fs(x,y)

    f  -- must accept an array of X and t=0, and return a 2D array of \dot y and \dot x
    inits -- list of vectors representing inital conditions
    t -- time interval
    n -- number of points

    Example
    =======
    
    from itertools import product
    phaseportrait(lambda X, t=0: array([X[0],2*X[1]]), product(linspace(-4,4,15),linspace(-4,4,15)), [-2,0.3], n=20)
    """
    assert(t[0]<t[1] and t[1]>0)
    X=[]
    Y=[]
    for x0 in inits:
        x0=np.array(x0)
        if t[0]<0:
            segments=[np.linspace(0,t[0],n),np.linspace(0,t[1],n)]
        else:
            segments=[np.linspace(t[0],t[1],2*n)]
        for s in segments:
            points=integrate.odeint(fs,x0,s)
            for i,Z in enumerate([X,Y]):
                Z.extend(points[:,i])
                Z.append(None)
        direction = fs(x0)
        direction = direction / scipy.linalg.norm(direction) * 0.01
        plt.arrow(x0[0]-direction[0],x0[1]-direction[1],direction[0],direction[1],
              head_width=head_width, head_length=head_length, lw=0.0, **kw)
    plt.plot(X,Y,**kw)
开发者ID:ischurov,项目名称:qqmbr,代码行数:34,代码来源:odebook.py

示例2: draw_arrow

    def draw_arrow(pair, alpha=alpha, ec=ec, labelcolor=labelcolor):
        # set the length of the arrow
        if display == 'length':
            length = max_head_length + data[pair]/sf*(max_arrow_length -
                                                      max_head_length)
        else:
            length = max_arrow_length
        # set the transparency of the arrow
        if display == 'alph':
            alpha = min(data[pair]/sf, alpha)
        else:
            alpha = alpha
        # set the width of the arrow
        if display == 'width':
            scale = data[pair]/sf
            width = max_arrow_width*scale
            head_width = max_head_width*scale
            head_length = max_head_length*scale
        else:
            width = max_arrow_width
            head_width = max_head_width
            head_length = max_head_length

        fc = colors[pair]
        ec = ec or fc

        x_scale, y_scale = deltas[pair]
        x_pos, y_pos = positions[pair]
        plt.arrow(x_pos, y_pos, x_scale*length, y_scale*length,
              fc=fc, ec=ec, alpha=alpha, width=width, head_width=head_width,
              head_length=head_length, **arrow_params)

        # figure out coordinates for text
        # if drawing relative to base: x and y are same as for arrow
        # dx and dy are one arrow width left and up
        # need to rotate based on direction of arrow, use x_scale and y_scale
        # as sin x and cos x?
        sx, cx = y_scale, x_scale

        where = label_positions[pair]
        if where == 'left':
            orig_position = 3*np.array([[max_arrow_width, max_arrow_width]])
        elif where == 'absolute':
            orig_position = np.array([[max_arrow_length/2.0, 3*max_arrow_width]])
        elif where == 'right':
            orig_position = np.array([[length - 3*max_arrow_width,
                                    3*max_arrow_width]])
        elif where == 'center':
            orig_position = np.array([[length/2.0, 3*max_arrow_width]])
        else:
            raise ValueError("Got unknown position parameter %s" % where)

        M = np.array([[cx, sx], [-sx, cx]])
        coords = np.dot(orig_position, M) + [[x_pos, y_pos]]
        x, y = np.ravel(coords)
        orig_label = rate_labels[pair]
        label = '$%s_{_{\mathrm{%s}}}$' % (orig_label[0], orig_label[1:])

        plt.text(x, y, label, size=label_text_size, ha='center', va='center',
             color=labelcolor or fc)
开发者ID:AlexandreAbraham,项目名称:matplotlib,代码行数:60,代码来源:arrow_demo.py

示例3: plot_pick_and_place_stage

def plot_pick_and_place_stage(image_rgb, labeled_image, approximated_polygon, unfold_paths,
                              pick_point, place_point, to_file=None, show=True):
    plot_rgb(image_rgb, show=False)
    plt.imshow(labeled_image, cmap=plt.cm.RdGy, alpha=0.6)
    points = [tuple(point[0]) for point in approximated_polygon]
    # Plot polygon lines
    for (start_x, start_y), (end_x, end_y) in zip(points, points[1:]+points[0:1]):
        plt.plot( (start_x, end_x), (start_y, end_y), 'r-', linewidth=2.0 )
    # Plot polygon points
    for x, y in points:
        plt.plot(x, y, 'ro')
    #Plot unfold paths
    for path in unfold_paths:
        (start_x, start_y), (end_x, end_y) = path
        plt.plot( (start_x, end_x), (start_y, end_y), 'go-', linewidth=2.0 )
    # Plot arrow
    plt.arrow(pick_point[0], pick_point[1], place_point[0]-pick_point[0], place_point[1]-pick_point[1],
               head_width=15, head_length=15, fc='blue', ec='blue', lw=5, alpha=0.7)
    plt.axis('off')

    if to_file:
        plt.savefig(to_file, bbox_inches='tight')
        plt.close()
    elif show:
        plt.show()
开发者ID:roboticslab-uc3m,项目名称:textiles,代码行数:25,代码来源:GarmentPlot.py

示例4: draw_experiment_data

def draw_experiment_data(experiment, viewport=None, estimate=True, camera=True, truth=True, cov=False):
    with open('/home/cristi/Dropbox/FIRM/Experiments/iser_trials/experiment_data_{}.txt'.format(experiment), 'r') as fin:
        for line in fin:
            line = line.strip()
            if line.startswith('#'):
                pass
            elif line:
                data = dict(eval(line))
                if data.has_key('opti') and data.has_key('filter'):
                    plot_data = []
                    if estimate:
                        plot_data.append((data['x'], (1.0, 0, 0)))
                    if camera:
                        plot_data.append((data['filter'], (1, 1, 0)))
                    if truth:
                        plot_data.append((data['opti'], (0, 1, 0))) # TODO: colors 'g'
                    
                    for (x, y, yaw,), col in plot_data:
                        plt.arrow(x, y, 0.1*np.cos(yaw), 0.1*np.sin(yaw),
                                  hold=True, color=col)
                    
                    if cov:
                        viewport.add_patch( Mission.covariance_ellipse(
                            data['x'][:2], np.diag(data['cov'][:2]), color='b',
                            fill=False, lw=1, zorder=0))
开发者ID:wasserfeder,项目名称:gdtl-firm,代码行数:25,代码来源:plot_experiment.py

示例5: animate

            def animate(generation):
                chromosome = ts_ga.generation_fittest[generation]
                ax.clear()

                x, y = [], []
                for city_id, point in city_points.items():
                    x.append(point[0])
                    y.append(point[1])
                ax.plot(x, y, marker='s', linestyle='', label='cities', alpha=0.6)

                # plot optimal route
                chrom_city_ids = ts_ga.translator.translate_chromosome(chromosome)
                dist = round(ts_ga.calc_distance(chromosome), 2)

                ax.set_title("generation " + str(generation) + "\ndistance = " + str(dist))

                for i, start_city_id in enumerate(chrom_city_ids):
                    end_city_idx = i + 1

                    if end_city_idx == num_cities:
                        # distance from last city to first
                        end_city_idx = 0

                    end_city_id = chrom_city_ids[end_city_idx]

                    x1, y1 = city_points[start_city_id]
                    x2, y2 = city_points[end_city_id]
                    mid_x = (x2 - x1) / 2 + x1
                    mid_y = (y2 - y1) / 2 + y1

                    plt.arrow(x1, y1, x2 - x1, y2 - y1, head_width=1.5, fc='k', ec='k', alpha=0.7, linestyle='dotted', length_includes_head=True)
                    plt.text(mid_x, mid_y, str(i + 1))
开发者ID:nk,项目名称:ga,代码行数:32,代码来源:travelling_salesman.py

示例6: Velocities_2D

def Velocities_2D(n):
    dim = 2
    fig = plt.figure(dim, figsize=(8, 8), facecolor='white')
    fig.clf()
    xmin, xmax, ymin, ymax = 1000, -1000, 1000, -1000
    e = .5
    for k in range((2*n+1)**dim):
        v = pylbm.stencil.Velocity(dim = dim, num = k)
        x = v.vx
        y = v.vy
        xmin = min(xmin, x)
        xmax = max(xmax, x)
        ymin = min(ymin, y)
        ymax = max(ymax, y)
        couleur_texte = 0.
        couleur_trait = 0.5
        plt.text(x, y, str(v.num), color=[couleur_texte]*3,
                 horizontalalignment='center',verticalalignment='center',
                 fontsize=15)
    for x in range(xmin, xmax+1):
        plt.plot([x, x], [ymin, ymax], ':', color=[couleur_trait]*3)
    for y in range(ymin, ymax+1):
        plt.plot([xmin, xmax], [y, y], ':', color=[couleur_trait]*3)
    plt.text(0., ymax+2*e, "Velocities numbering {0:1d}D".format(dim),fontsize=20,
        verticalalignment='center', horizontalalignment='center', color='b')
    plt.arrow(xmin-e, ymin-e, 1, 0, head_width=0.05*dim, head_length=0.1, fc='b', ec='b')
    plt.arrow(xmin-e, ymin-e, 0, 1, head_width=0.05*dim, head_length=0.1, fc='b', ec='b')
    plt.text(xmin-e+.5, ymin-1.5*e, 'x', color='b',
        verticalalignment='center', horizontalalignment='center')
    plt.text(xmin-1.5*e, ymin-e+.5, 'y', color='b',
        verticalalignment='center', horizontalalignment='center')
    plt.axis('off')
    plt.xlim(xmin-2*e, xmax+2*e)
    plt.ylim(ymin-2*e, ymax+2*e)
    plt.draw()
开发者ID:bgraille,项目名称:pylbm,代码行数:35,代码来源:Velocities.py

示例7: plot_state

    def plot_state(self, i, history):
        plt.clf()
        ax = plt.gca()
        w = float(self.width + 1)
        h = float(self.height + 1)

        minw = np.min(self.internal_weights)
        maxw = np.max(self.internal_weights)
        diffw = maxw - minw

        for n, neuron in enumerate(self.neurons):
            x, y = self.neuron_position(n)
            line_y = -history[i - 100:i:4, n]
            #line_y = history[max(i - 20, 0):i, n] + .25
            line_x = np.arange(len(line_y)) / 50.0
            #line_x = np.arange(len(line_y)) / 40.0
            line = mlines.Line2D((line_x + x + .75) / w, 1 - (line_y + y + 1) / h)
            ax.add_line(line)

            k = .2
            for dx, dy in DIRECTIONS:
                weight = self.internal_weights[self.neuron_index(x, y), self.neuron_index((x + dx) % self.width, (y + dy) % self.height)]

                plt.arrow(
                    (1 + x + (1 - k) / 2 * dx) / w,
                    1 - (1 + y + (1 - k) / 2 * dy) / h,
                    (k * dx) / w,
                    -(k * dy) / h,
                    width=.0002,
                    color=str(weight / maxw),
                )

        plt.draw()
开发者ID:andreasjansson,项目名称:esn,代码行数:33,代码来源:wind.py

示例8: show

def show(model):
    spiral_x = []
    spiral_y = []
    model.calculate_spiral(spiral_x, spiral_y)
    print("sp")

    figure = plot.figure(1)
    plot.subplot2grid((1, 3), (0, 2), colspan=1)
    plot.title('Комплексная амплитуда волны E')
    plot.xlabel('Re(E)')
    plot.ylabel('Im(E)')

    #d = sqrt((spiral_x[1] - spiral_x[0])**2 + (spiral_y[1] - spiral_y[0])**2)
    d = 0.01
    w = d / 3
    h_w = w * 2
    h_l = d / 3

    plot.plot(spiral_x, spiral_y, color='r', linewidth=2)
    #for i in arange(0, len(spiral_x) - 1, 1):
    #    plot.arrow(spiral_x[i], spiral_y[i], spiral_x[i + 1] - spiral_x[i], spiral_y[i + 1] - spiral_y[i],
    #    width=w, head_width=h_w, head_length=h_l, length_includes_head=True, fc='r', ec='k')

    plot.arrow(0, 0, spiral_x[-1], spiral_y[-1],
               width=w*1.5, head_width=h_w*1.5, head_length=h_l*1.5, length_includes_head=True, fc='g', ec='k')


    plot.grid(True)
    mx = max(spiral_x)
    my = max(spiral_y)
    #plot.xlim([-mx - d, mx + d])
    #plot.ylim([-d, my + d])

    model.draw(figure)
开发者ID:snakerock,项目名称:fresnelzones,代码行数:34,代码来源:fresnel_spiral.py

示例9: visual_addition

def visual_addition(vectors):
    x = 0
    y = 0
    for v in vectors:
        plt.arrow(x, y, v[0], v[1], head_width=0.1, head_length=0.1)
        x += v[0]
        y += v[1]
开发者ID:jColeChanged,项目名称:MIT,代码行数:7,代码来源:vector_drawing.py

示例10: draw

 def draw(self, show_normal=False, color='green'):
     for i, segment in enumerate(self.segments):
         plt.plot(segment[:, 0], segment[:, 1], color=color)
         if show_normal:
             normal = math2d.normal(segment)
             center = math2d.center(segment)
             plt.arrow(center[0], center[1], normal[0], normal[1], width=0.01, color=color)
开发者ID:lynch829,项目名称:PyTracer,代码行数:7,代码来源:detector.py

示例11: draw

    def draw(self,file=None):
        """
        Trace l'ensemble des lignes de champ passant par les points de départ 
        stockés dans Startpoints. Si un nom de fichier est donné, enregistre 
        la figure dans le fichier mais n'affiche rien à l'écran
        """

        def fun(P,t):
            B = self.B(P)
            Bx = B[0]
            By = B[1]
            B = np.sqrt(Bx*Bx+By*By)
            return [Bx/pow(B,4./3.),By/pow(B,4./3.)]

        t = np.linspace(0,self.k*self.maxint,self.numpoints/2)
        t2 = - t
        for P0 in self.startpoints:
            sol = odeint(fun,P0,t)
            x = sol[:,0]
            y = sol[:,1]
            pl.plot(x,y,'-',color='k')
            sol = odeint(fun,P0,t2)
            x = sol[1:,0]
            y = sol[1:,1]
            pl.plot(x,y,'-',color='k')
            pl.arrow(x[1],y[1],x[0]-x[1],y[0]-y[1],color='k')
        pl.title(self.title)
        pl.xlim([-self.size,self.size])
        pl.ylim([-self.size,self.size])
        if file:
            pl.savefig(file)
            pl.close()
        else:
            pl.show()
开发者ID:cjorssen,项目名称:py4phys,代码行数:34,代码来源:I1_lignes_champ_magnetique.py

示例12: open_spline_chain_main

def open_spline_chain_main():
    #x = [0, 3, -20, -10]
    #y = [0, 30, -5, -3]
    #th = [np.pi/2., np.pi, -np.pi/2., 0.]
    x = np.cos(np.deg2rad(135.))*np.array([-10., 1., 50.])
    y = np.sin(np.deg2rad(135.))*np.array([-10., 1., 50.])
    th = [np.deg2rad(135.), np.deg2rad(135.), np.deg2rad(135.)]
    X = np.column_stack((x, y))
    # Random desired discretization along the splines for demonstration purposes
    Ns = np.random.random_integers(100., 200., (X.shape[0]-1,))  # one less spline than waypoints.
    sx, sy, sth, length, u, coeffs = PiazziSpline.splineOpenChain(X, th, Ns)

    plt.plot(sx, sy, 'k-', linewidth=2.0)
    #test_x = 3.0
    #test_y = 30.01
    test_x = 0.013
    test_y = 0.008
    u_star, closest, distance = closestPointOnSpline2D(length, sx, sy, test_x, test_y, u, coeffs, guess=None)
    print "closest X = {:.3f}, {:.3f},  u* = {}".format(closest[0], closest[1], u_star)

    # Figure out the LOS controller using this example
    tangent_th = np.interp(u_star, u, sth)
    print "tangent th = {:.3f} deg".format(tangent_th*180.0/np.pi)
    lookAhead = 0.1  # how far forward in u
    lookaheadState = splineToEuclidean2D(coeffs, min(u_star + lookAhead, u[-1]))
    print "lookahead X = {:.3f}, {:.3f}".format(lookaheadState[0], lookaheadState[1])
    dx_global = lookaheadState[0] - closest[0]
    dy_global = lookaheadState[1] - closest[1]
    print "dx_global = {:.3f}, dy_global = {:.3f}".format(dx_global, dy_global)
    dx_frenet = dx_global*math.cos(tangent_th) + dy_global*math.sin(tangent_th)
    dy_frenet = dx_global*math.sin(tangent_th) - dy_global*math.cos(tangent_th)
    print "y error = {:.3f}, dx_frenet = {:.3f}, dy_frenet = {:.3f}".format(distance, dx_frenet, dy_frenet)

    # need sign of distance to spline to change
    # look at sign of cross product to determine "handed-ness"
    angle_from_closest_to_test = math.atan2(closest[1] - test_y, closest[0] - test_x)
    print "angle from closest to test = {:.3f} deg".format(angle_from_closest_to_test*180./np.pi)
    sign_test = np.cross([math.cos(tangent_th), math.sin(tangent_th)], [math.cos(angle_from_closest_to_test), math.sin(angle_from_closest_to_test)])
    distance *= np.sign(sign_test)
    print "distance to spline after sign update = {:.3f}".format(distance)

    # resulting triangle
    relative_angle = math.atan2((distance - dy_frenet), dx_frenet)
    global_angle = tangent_th + relative_angle
    print "relative angle = {:.3f} deg, global angle = {:.3f} deg".format(relative_angle*180./np.pi, global_angle*180./np.pi)

    # plot
    plt.plot(test_x, test_y, 'r+', markersize=12., markeredgewidth=2.0)
    plt.plot(closest[0], closest[1], 'gx', markersize=12., markeredgewidth=2.0)
    plt.plot(lookaheadState[0], lookaheadState[1], 'go', markersize=12., markeredgewidth=2.0)
    result_line = np.array([[test_x, test_y], closest])
    lookAhead_line = np.array([closest, lookaheadState])
    plt.plot(result_line[:, 0], result_line[:, 1], 'b-')
    plt.plot(lookAhead_line[:, 0], lookAhead_line[:, 1], 'g-')
    plt.arrow(closest[0], closest[1], 10.*math.cos(tangent_th), 10.*math.sin(tangent_th), linestyle='dashed')
    d = math.sqrt(math.pow(lookaheadState[0] - test_x, 2) + math.pow(lookaheadState[1] - test_y, 2))
    plt.arrow(test_x, test_y, d*math.cos(global_angle), d*math.sin(global_angle), linestyle='dotted')
    plt.axis('equal')
    plt.title("length = {:.2f}, u = {:.4f}, distance = {:.2f}".format(length[-1], u_star, distance))
    plt.show()
开发者ID:jjblum,项目名称:simple_boat_defense,代码行数:60,代码来源:Utility.py

示例13: plotArrow

def plotArrow(p0, p1, headWidth=.1):
    
    dx = p1[0] - p0[0]
    dy = p1[1] - p0[1]
    
    plt.arrow(p0[0], p0[1], dx, dy, head_width=headWidth, 
                  length_includes_head = True)
开发者ID:mjcorriere,项目名称:theSandbox,代码行数:7,代码来源:convexhull_v1.py

示例14: matrix2png

def matrix2png(matrixname, savedfolder, xlim, ylim, arrows):
    matrix = open(matrixname, 'r').readlines()
    matrix = [i.split() for i in matrix]
    matrix = [[float(j) for j in i] for i in matrix]

    matrix_t = transposed(matrix)

    y = []

    for col in range(0,len(matrix_t)):
        y.append(matrix_t[col])

    longitud = len(y)

    for i in range(0, len(y[1])):
        for j in range(0, longitud/2):                    
            plt.plot(y[j*2][i],y[j*2+1][i],'o')
        
        for a in arrows:
            ao = a[0] - 1
            ai = a[1] - 1
            plt.arrow(y[ao*2][i], y[ao*2+1][i], y[ai*2][i]-y[ao*2][i],y[ai*2+1][i]-y[ao*2+1][i])        

        #Limites de los ejes
        plt.xlim(xlim[0], xlim[1])
        plt.ylim(ylim[0], ylim[1])
        plt.savefig(savedfolder + str(i).zfill(5) + '.png')
        plt.clf()
        
    plt.close()
开发者ID:deljodavis,项目名称:mis_scripts,代码行数:30,代码来源:load_matrix.py

示例15: plotarrows

def plotarrows():
    COORDINATES = np.load(savefilename)
    plt.figure()
    plt.rc('text', usetex=True)
    ypmin = 0
    ypmax = 100
    xpmin = 0
    xpmax = 70
        
    plt.xlim(xmin=xpmin, xmax=xpmax)
    plt.ylim(ymin=ypmin, ymax=ypmax)
    
    for i in range(0,len(COORDINATES)-1):
        lw = 1+COORDINATES[i,2]*10.
        if i%2==0:
            plt.arrow(COORDINATES[i,0], COORDINATES[i,1], (COORDINATES[i+1,0] - COORDINATES[i,0]), (COORDINATES[i+1,1] - COORDINATES[i,1]), fc="k", ec="k", head_width=1.5, head_length=1, linewidth=lw)
        else:
            plt.arrow(COORDINATES[i,0], COORDINATES[i,1], (COORDINATES[i+1,0] - COORDINATES[i,0]), (COORDINATES[i+1,1] - COORDINATES[i,1]), linewidth=lw)
    
    plt.gca().set_aspect('equal')    
    plt.title('Trajectory over time: ' + str(len(COORDINATES)*100))
    plt.xlabel('$r/r_g$')
    plt.ylabel('$r/r_g$')
    plt.show()
    plt.savefig('/Users/Anton/Dropbox/Aleksander/Figures/simavg0070-0134/particles/particle_'+ str(gSTART_INDEX) +'_'+ str(gSTART_x)+'_'+str(gSTART_y), bbox_inches='tight') 
开发者ID:Mylleranton,项目名称:AccretionDisks,代码行数:25,代码来源:particle_trail.py


注:本文中的matplotlib.pyplot.arrow函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。