Python matplotlib.pyplot.arrow() Examples

The following are 23 code examples of matplotlib.pyplot.arrow(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: pca.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def plot2d(self,ix=0,iy=1,clf=True):
        """
        Generates a 2-dimensional plot of the data set and principle components
        using matplotlib.

        ix specifies which p-dimension to put on the x-axis of the plot
        and iy specifies which to put on the y-axis (0-indexed)
        """
        import matplotlib.pyplot as plt
        x,y=self.N[:,ix],self.N[:,iy]
        if clf:
            plt.clf()
        plt.scatter(x,y)
        vals,evs=self.getEigensystem()
        #evx,evy=evs[:,ix],evs[:,iy]
        xl,xu=plt.xlim()
        yl,yu=plt.ylim()
        dx,dy=(xu-xl),(yu-yl)
        for val,vec,c in zip(vals,evs.T,self._colors):
            plt.arrow(0,0,val*vec[ix],val*vec[iy],head_width=0.05*(dx*dy/4)**0.5,fc=c,ec=c)
        #plt.arrow(0,0,vals[ix]*evs[ix,ix],vals[ix]*evs[iy,ix],head_width=0.05*(dx*dy/4)**0.5,fc='g',ec='g')
        #plt.arrow(0,0,vals[iy]*evs[ix,iy],vals[iy]*evs[iy,iy],head_width=0.05*(dx*dy/4)**0.5,fc='r',ec='r')
        if self.names is not None:
            plt.xlabel('$'+self.names[ix]+'/\\sigma$')
            plt.ylabel('$'+self.names[iy]+'/\\sigma$') 
Example #2
Source File: MakeSingleFigure.py    From dybm with Apache License 2.0 6 votes vote down vote up
def subplot(N, n, i, title=True):
    ax = fig.add_subplot(N, 1, i)
    image = np.array(x[n]).T
    ax.imshow(image, cmap=plt.cm.gray, interpolation="nearest")
    if title:
        if n == 0:
            ax.set_title('Before training', **title_font)
        else:
            num = str(n)
            if len(num) > 3:
                num = num[:-3] + "," + num[-3:]
            if len(num) > 7:
                num = num[:-7] + "," + num[-7:]
            ax.set_title('After training ' + num + " times", **title_font)
    plt.tick_params(axis='both', which='both', bottom='off', top='off',
                    right="off", left="off", labelleft="off",
                    labelbottom='off')
    if i == N:
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
        plt.arrow(xlim[0], ylim[0] + 1, xlim[1] - xlim[0] - 1.5, 0, width=.1,
                  color="k", clip_on=False, head_width=1., head_length=1.5) 
Example #3
Source File: MakeEvolutionFigure.py    From dybm with Apache License 2.0 6 votes vote down vote up
def subplot(N, n, i, title=True):
    ax = fig.add_subplot(N, 1, i)
    image = np.array(x[n]).T
    ax.imshow(image, cmap=plt.cm.gray, interpolation="nearest")
    if title:
        if n == 0:
            ax.set_title('Before training', **title_font)
        else:
            num = str(n)
            if len(num) > 3:
                num = num[:-3] + "," + num[-3:]
            if len(num) > 7:
                num = num[:-7] + "," + num[-7:]
            ax.set_title('After training ' + num + " times", **title_font)
    plt.tick_params(axis='both', which='both', bottom='off', top='off',
                    right="off", left="off", labelleft="off",
                    labelbottom='off')
    if i == N:
        xlim = ax.get_xlim()
        ylim = ax.get_ylim()
        plt.arrow(xlim[0], ylim[0] + 1, xlim[1] - xlim[0] - 1.5, 0, width=.1,
                  color="k", clip_on=False, head_width=1., head_length=1.5) 
Example #4
Source File: graph.py    From landlab with MIT License 6 votes vote down vote up
def plot_links(
    graph, color="b", linestyle="solid", with_id=True, as_arrow=True, linewidth=None
):
    if as_arrow:
        head_width = 0.1
    else:
        head_width = 0.0
    for link, nodes in enumerate(graph.nodes_at_link):
        x, y = graph.x_of_node[nodes[0]], graph.y_of_node[nodes[0]]
        dx, dy = graph.x_of_node[nodes[1]] - x, graph.y_of_node[nodes[1]] - y
        plt.arrow(
            x,
            y,
            dx,
            dy,
            head_width=head_width,
            linewidth=linewidth,
            length_includes_head=True,
            color=color,
            linestyle=linestyle,
        )
        if with_id:
            plt.text(x + dx * 0.5, y + dy * 0.5, link, size=16, color=color) 
Example #5
Source File: ch_591_stage_area.py    From hydrology with GNU General Public License v3.0 6 votes vote down vote up
def poly_plot(xy, titlestr = "", margin = 0.25):
    """
        Plots polygon. For arrow see:
        http://matplotlib.org/examples/pylab_examples/arrow_simple_demo.html
        x = xy[:,0], y = xy[:,1]
    """
    xmin = np.min(xy[:,0])
    xmax = np.max(xy[:,0])
    ymin = np.min(xy[:,1])
    ymax = np.max(xy[:,1])
    hl = 0.1
    l = len(xy)
    for i in range(l):
        j = (i+1)%l  # keep index in [0,l)
        dx = xy[j,0] - xy[i,0]
        dy = xy[j,1] - xy[i,1]
        dd = np.sqrt(dx*dx + dy*dy)
        dx *= (1 - hl/dd)
        dy *= (1 - hl/dd)
        plt.arrow(xy[i,0], xy[i,1], dx, dy, head_width=0.05, head_length=0.1, fc='b', ec='b')
        plt.xlim(xmin-margin, xmax+margin)
        plt.ylim(ymin-margin, ymax+margin)
    plt.title(titlestr) 
Example #6
Source File: ch_599_stage_vol_area.py    From hydrology with GNU General Public License v3.0 6 votes vote down vote up
def poly_plot(xy, titlestr = "", margin = 0.25):
    """
        Plots polygon. For arrow see:
        http://matplotlib.org/examples/pylab_examples/arrow_simple_demo.html
        x = xy[:,0], y = xy[:,1]
    """
    xmin = np.min(xy[:,0])
    xmax = np.max(xy[:,0])
    ymin = np.min(xy[:,1])
    ymax = np.max(xy[:,1])
    hl = 0.1
    l = len(xy)
    for i in range(l):
        j = (i+1)%l  # keep index in [0,l)
        dx = xy[j,0] - xy[i,0]
        dy = xy[j,1] - xy[i,1]
        dd = np.sqrt(dx*dx + dy*dy)
        dx *= (1 - hl/dd)
        dy *= (1 - hl/dd)
        plt.arrow(xy[i,0], xy[i,1], dx, dy, head_width=0.05, head_length=0.1, fc='b', ec='b')
        plt.xlim(xmin-margin, xmax+margin)
        plt.ylim(ymin-margin, ymax+margin)
    plt.title(titlestr) 
Example #7
Source File: electrostatics.py    From electrostatics with GNU General Public License v3.0 6 votes vote down vote up
def plot(self, linewidth=None, linestyle='-',
             startarrows=True, endarrows=True):
        """Plots the field line and arrows."""

        if linewidth is None:
            linewidth = matplotlib.rcParams['lines.linewidth']

        x, y = zip(*self.x)
        pyplot.plot(x, y, '-k', linewidth=linewidth, linestyle=linestyle)

        n = int(len(x)/2) if len(x) < 225 else 75
        if startarrows:
            pyplot.arrow(x[n], y[n], (x[n+1]-x[n])/100., (y[n+1]-y[n])/100.,
                         fc="k", ec="k",
                         head_width=0.1*linewidth, head_length=0.1*linewidth)

        if len(x) < 225 or not endarrows:
            return

        pyplot.arrow(x[-n], y[-n],
                     (x[-n+1]-x[-n])/100., (y[-n+1]-y[-n])/100.,
                     fc="k", ec="k",
                     head_width=0.1*linewidth, head_length=0.1*linewidth) 
Example #8
Source File: analysis.py    From velocyto.py with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def plot_cell_transitions(self, cell_ix: int=0, alpha: float=0.1, alpha_neigh: float=0.2,
                              cmap_name: str="RdBu_r", plot_arrow: bool=True,
                              mark_cell: bool=True, head_width: int=3) -> None:
        """Plot the probability of a cell to transition to any other cell

        This function is untested
        """
        cmap = plt.cm.get_cmap(name=cmap_name)
        colorandum = np.ones((self.embedding.shape[0], 4))
        colorandum *= 0.3
        colorandum[:, -1] = alpha
        
        plt.scatter(self.embedding[:, 0], self.embedding[:, 1],
                    c=colorandum, s=50, edgecolor="")
        if mark_cell:
            plt.scatter(self.embedding[cell_ix, 0], self.embedding[cell_ix, 1],
                        facecolor="none", s=100, edgecolor="k")
        if plot_arrow:
            plt.arrow(self.embedding[cell_ix, 0], self.embedding[cell_ix, 1],
                      self.delta_embedding[cell_ix, 0], self.delta_embedding[cell_ix, 1],
                      head_width=head_width, length_includes_head=True) 
Example #9
Source File: pca.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def plot2d(self,ix=0,iy=1,clf=True):
        """
        Generates a 2-dimensional plot of the data set and principle components
        using matplotlib.

        ix specifies which p-dimension to put on the x-axis of the plot
        and iy specifies which to put on the y-axis (0-indexed)
        """
        import matplotlib.pyplot as plt
        x,y=self.N[:,ix],self.N[:,iy]
        if clf:
            plt.clf()
        plt.scatter(x,y)
        vals,evs=self.getEigensystem()
        #evx,evy=evs[:,ix],evs[:,iy]
        xl,xu=plt.xlim()
        yl,yu=plt.ylim()
        dx,dy=(xu-xl),(yu-yl)
        for val,vec,c in zip(vals,evs.T,self._colors):
            plt.arrow(0,0,val*vec[ix],val*vec[iy],head_width=0.05*(dx*dy/4)**0.5,fc=c,ec=c)
        #plt.arrow(0,0,vals[ix]*evs[ix,ix],vals[ix]*evs[iy,ix],head_width=0.05*(dx*dy/4)**0.5,fc='g',ec='g')
        #plt.arrow(0,0,vals[iy]*evs[ix,iy],vals[iy]*evs[iy,iy],head_width=0.05*(dx*dy/4)**0.5,fc='r',ec='r')
        if self.names is not None:
            plt.xlabel('$'+self.names[ix]+'/\\sigma$')
            plt.ylabel('$'+self.names[iy]+'/\\sigma$') 
Example #10
Source File: visualize.py    From pureples with MIT License 6 votes vote down vote up
def draw_es(id_to_coords, connections, filename):
    fig = plt.figure()
    plt.axis([-1.1, 1.1, -1.1, 1.1])
    fig.add_subplot(111)

    for c in connections:
        color = 'red'
        if c.weight > 0.0:
            color = 'black'
        plt.arrow(c.x1, c.y1, c.x2-c.x1, c.y2-c.y1, head_width=0.00, head_length=0.0, 
                  fc=color, ec=color, length_includes_head = True)

    for (coord, idx) in id_to_coords.iteritems():
        plt.plot(coord[0], coord[1], marker='o', markersize=8.0, color='grey')

    plt.grid()
    fig.savefig(filename) 
Example #11
Source File: reeds_shepp_path_planning.py    From 3D_Path_Planning with MIT License 5 votes vote down vote up
def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"):
    """
    Plot arrow
    """

    if not isinstance(x, float):
        for (ix, iy, iyaw) in zip(x, y, yaw):
            plot_arrow(ix, iy, iyaw)
    else:
        plt.arrow(x, y, length * math.cos(yaw), length * math.sin(yaw),
                  fc=fc, ec=ec, head_width=width, head_length=width)
        plt.plot(x, y) 
Example #12
Source File: dubins_path_planning.py    From 3D_Path_Planning with MIT License 5 votes vote down vote up
def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"):
    u"""
    Plot arrow
    """
    import matplotlib.pyplot as plt

    if not isinstance(x, float):
        for (ix, iy, iyaw) in zip(x, y, yaw):
            plot_arrow(ix, iy, iyaw)
    else:
        plt.arrow(x, y, length * math.cos(yaw), length * math.sin(yaw),
                  fc=fc, ec=ec, head_width=width, head_length=width)
        plt.plot(x, y) 
Example #13
Source File: axicon.py    From RayTracing with MIT License 5 votes vote down vote up
def drawAt(self, z, axes):  # pragma: no cover
        halfHeight = 4
        if self.apertureDiameter != float('Inf'):
            halfHeight = self.apertureDiameter / 2

        plt.arrow(z, 0, 0, halfHeight, width=0.1, fc='k', ec='k', head_length=0.25, head_width=0.25,
                  length_includes_head=True)
        plt.arrow(z, 0, 0, -halfHeight, width=0.1, fc='k', ec='k', head_length=0.25, head_width=0.25,
                  length_includes_head=True) 
Example #14
Source File: visualization.py    From spatial-reasoning with MIT License 5 votes vote down vote up
def arrow(i, j, action):
    ## up, down, left, right
    ## x, y, w, h
    arrows = {0: (.5,.95,0,-.4), 1: (.5,.05,0,.4), 2: (.95,.5,-.4,0), 3: (.05,.5,.4,0)}
    arrow = arrows[action]
    return j+arrow[0], i+arrow[1], arrow[2], arrow[3] 
Example #15
Source File: visualization.py    From spatial-reasoning with MIT License 5 votes vote down vote up
def visualize_values(mdp, values, policy, filename, title=None):
    states = mdp.states
    # print states
    plt.clf()
    m = max(states, key=lambda x: x[0])[0] + 1
    n = max(states, key=lambda x: x[1])[1] + 1
    data = np.zeros((m,n))
    for i in range(m):
        for j in range(n):
            state = (i,j)
            if type(values) == dict:
                data[i][j] = values[state]
            else:
                # print values[i][j]
                data[i][j] = values[i][j]
            action = policy[state]
            ## if using all_reachable actions, pick the best one
            if type(action) == tuple:
                action = action[0]
            if action != None:
                x, y, w, h = arrow(i, j, action)
                plt.arrow(x,y,w,h,head_length=0.4,head_width=0.4,fc='k',ec='k')
    heatmap = plt.pcolor(data, cmap=plt.get_cmap('jet'))
    plt.colorbar()
    plt.gca().invert_yaxis()

    if title:
        plt.title(title)
    plt.savefig(filename + '.png')
    # print data 
Example #16
Source File: streetmover_distance.py    From generative-graph-transformer with MIT License 5 votes vote down vote up
def show_assignments(a, b, P, title=""):
    norm_P = P / P.max()
    for i in range(a.shape[0]):
        for j in range(b.shape[0]):
            plt.arrow(a[i, 0], a[i, 1], b[j, 0] - a[i, 0], b[j, 1] - a[i, 1],
                      alpha=norm_P[i, j].item() / 2)
    plt.scatter(a[:, 0], a[:, 1], label="target")
    plt.scatter(b[:, 0], b[:, 1], label="prediction")
    plt.axis('off')
    plt.legend(prop={'size': 20})
    plt.title(f'StreetMover: {title[:6]}', fontsize=25)
    plt.tight_layout()
    # plt.show()
    plt.savefig(f"./sinkhorn/wass{title}.png")
    plt.clf() 
Example #17
Source File: point_v3.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def draw(x, y):
        # set up range of the plot
        limit = max(x, y) + 1

        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.set_aspect('equal')

        # lines corresponding to x- and y-coordinates
        plt.plot([x, x], [0, y], '-', c='blue', linewidth=3)
        plt.plot([0, x], [y, y], '-', c='blue', linewidth=3)

        plt.scatter(x, y, s=100, marker='o', c='red')  # actual point

        ax.set_xlim((-limit, limit))
        ax.set_ylim((-limit, limit))

        # axis arrows
        left, right = ax.get_xlim()
        bottom, top = ax.get_ylim()
        plt.arrow(left, 0, right - left, 0, length_includes_head=True,
                  head_width=0.15)
        plt.arrow(0, bottom, 0, top - bottom, length_includes_head=True,
                  head_width=0.15)

        plt.grid()
        plt.show() 
Example #18
Source File: brush.py    From viznet with MIT License 5 votes vote down vote up
def _arrow(ax, mxy, direction, head_width, head_length, lw, zorder, color):
    '''draw an arrow.'''
    head_vec = direction * head_length
    mxy = mxy - head_vec * 0.6
    dx, dy = direction
    obj = plt.arrow(*mxy, 1e-8 * dx, 1e-8 * dy,
              head_length=head_length, width=0,
              head_width=head_width, fc=color,
              length_includes_head=False, lw=lw, edgecolor=color, zorder=zorder)
    return obj 
Example #19
Source File: brush.py    From viznet with MIT License 5 votes vote down vote up
def basicline_handler(sxy, exy, style, head_length):
    '''draw a line between start and end.'''
    # the distance and unit distance
    d = np.asarray(exy) - sxy
    unit_d = d / norm(d)

    # get arrow locations.
    arrows = []
    segs = []
    for s in style:
        if s in ['>', '<']:
            sign = 1 if s == '>' else -1
            arrows.append([len(segs), sign*unit_d])
        else:
            segs.append(s)
    head_vec = unit_d * head_length
    vec_d = d - head_vec * 1.2
    num_segs = len(segs)
    for al in arrows:
        al[0] = al[0] * vec_d / max(num_segs, 1) + sxy + 0.6 * head_vec

    # get the line locations.
    uni = d / num_segs
    lines = []
    end = start = sxy
    seg_pre = ''
    for seg in segs:
        if seg != seg_pre and seg_pre != '':
            lines.append([seg_pre, [start, end]])
            start = end
        seg_pre = seg
        end = end + uni
    lines.append([seg, [start, end]])

    # fix end of line
    if style[-1] in ['<', '>']:
        lines[-1][1][1] -= head_vec
    if style[0] in ['<', '>']:
        lines[0][1][0] += head_vec
    return arrows, lines 
Example #20
Source File: brush.py    From viznet with MIT License 5 votes vote down vote up
def clink_handler(sxy, exy, style, offsets, roundness, head_length):
    '''a C style link between two edges.'''
    nturn = len(offsets)
    offsets = np.asarray(offsets)
    unit_t = (exy - sxy)/norm(exy - sxy)
    unit_l = rotate(unit_t, np.pi/2.)
    vl, vr = [sxy], [exy]

    # get arrow locations and directions
    # - first, get head and tail vector.
    arrows = []
    unit_head_vec = (-unit_t if nturn%2==0 else unit_l)*(np.sign(offsets[0]) if len(offsets)!=0 else -1)
    sign_eo = -1 if nturn%2 == 0 else 1
    unit_tail_vec = unit_head_vec * sign_eo
    head_vec = unit_head_vec * head_length
    tail_vec = unit_tail_vec * head_length
    if style[0] in ['<', '>']:
        sign = (1 if style[0]=='>' else -1)
        arrows.append((sxy+head_vec*0.6, unit_head_vec * sign))
        style = style[1:]
        vl[0] = vl[0] + head_vec
    if style[-1] in ['<', '>']:
        sign = (-1 if style[-1]=='>' else 1)
        arrows.append((exy+tail_vec*0.6, unit_tail_vec * sign))
        style = style[:-1]
        vr[0] = vr[0] + tail_vec

    # get path
    ls = style
    if len(ls) !=1:
        raise ValueError('style must contain exactly 1 line style code.')
    for i, dxy in enumerate(offsets):
        sxy = sxy + (-unit_t if i%2 == nturn%2 else unit_l)*dxy
        exy = exy + (unit_t if i%2 == nturn%2 else unit_l)*dxy
        vl.append(sxy)
        vr.append(exy)
    return arrows, [(ls, rounded_path(vl+vr[::-1], roundness))], (vl[-1], vr[-1]) 
Example #21
Source File: quickplotter.py    From phidl with MIT License 5 votes vote down vote up
def _draw_port(ax, port, arrow_scale, color):
    # x,y = port.midpoint
    nv = port.normal
    n = (nv[1]-nv[0])
    dx,dy = n*port.width/8*arrow_scale
    dx += n[1]*port.width/8*arrow_scale
    dy += n[0]*port.width/8*arrow_scale
    # dx,dy = np.array(np.cos(port.orientation/180*np.pi), np.sin(port.orientation/180*np.pi))*port.width/10*arrow_scale + \
    #         np.array(np.cos((port.orientation+90)/180*np.pi), np.sin((port.orientation+90)/180*np.pi))*port.width/4*arrow_scale
    # print(port.midpoint)
    # print(port.width)
    # print(nv)
    xbound, ybound = np.column_stack(port.endpoints)
    #plt.plot(x, y, 'rp', markersize = 12) # Draw port midpoint
    arrow_points = np.array([[0,0],[10,0],[6,4],[6,2],[0,2]])/(40)*port.width*arrow_scale
    arrow_points += port.midpoint
    arrow_points = _rotate_points(arrow_points, angle = port.orientation, center = port.midpoint)
    xmin,ymin = np.min(np.vstack([arrow_points,port.endpoints]), axis = 0)
    xmax,ymax = np.max(np.vstack([arrow_points,port.endpoints]), axis = 0)
    ax.plot(xbound, ybound, alpha = 0.5, linewidth = 3, color = color) # Draw port edge
    ax.plot(arrow_points[:,0], arrow_points[:,1], alpha = 0.5, linewidth = 1, color = color) # Draw port edge
    # plt.arrow(x, y, dx, dy,length_includes_head=True, width = 0.1*arrow_scale,
    #           head_width=0.3*arrow_scale, alpha = 0.5, **kwargs)
    ax.text(port.midpoint[0]+dx, port.midpoint[1]+dy, port.name,
        horizontalalignment = 'center', verticalalignment = 'center', fontsize = 14)
    bbox = [xmin,ymin,xmax,ymax]
    return bbox 
Example #22
Source File: plot_top_down_view.py    From allesfitter with MIT License 4 votes vote down vote up
def plot_top_down_view(params_median, params_star, a=None, timestep=None, scaling=5., colors=sns.color_palette('deep'), linewidth=2, plot_arrow=False, ax=None):
    
    sim = rebound.Simulation()
    sim.add(m=1)
    
    for i, companion in enumerate(config.BASEMENT.settings['companions_all']):
        if (i==0) and (timestep is None): 
            timestep = params_median[companion+'_epoch'] #calculate it for the timestep where the first companion is in transit
        first_epoch = get_first_epoch(timestep, params_median[companion+'_epoch'], params_median[companion+'_period'])
        phase = calc_phase(timestep, params_median[companion+'_period'], first_epoch)
        ecc = params_median[companion+'_f_s']**2 + params_median[companion+'_f_c']**2
        w = np.arccos( params_median[companion+'_f_c'] / np.sqrt(ecc) ) #in rad
        inc = params_median[companion+'_incl']/180.*np.pi
        if a is None:
            a1 = params_star['R_star'] / params_median[companion+'_radius_1'] #in Rsun 
            a1 *= 0.004650467260962157 #in AU
        else:
            a1 = a[i]
#        print(a, inc, ecc, w, phase*2*np.pi)
        if ecc>0:
            sim.add(a=a1, inc=inc-np.pi/2., e=ecc, omega=w, f=phase*2*np.pi)
        else:
            sim.add(a=a1, inc=inc--np.pi/2., f=phase*2*np.pi)
#    print(len(sim.particles))
    
#    print('Epoch, Period and mean anomaly, b:', sim.particles[0].M )
#    print('Mean anomaly, c:', sim.particles[0].M )
#    print('Mean anomaly, c:', sim.particles[0].M )
#    err
    
    fig, ax = OrbitPlot(sim, xlabel='AU', ylabel='AU', color=colors, lw=linewidth, ax=ax) #color=[sns.color_palette('deep')[i] for i in [0,1,3]],
    
    for i, companion in enumerate(config.BASEMENT.settings['companions_all']):
        
        R_companion = params_star['R_star'] * params_median[companion+'_rr'] # in Rsun
        R_companion *= 0.004650467260962157 #in AU
        R_companion *= scaling
    
        
        x = sim.particles.get(i+1).x
        y = sim.particles.get(i+1).y
        p = Circle((x,y), R_companion, color=colors[i])
        ax.add_artist(p)
        
    if plot_arrow:
        x0, x1 = ax.get_xlim()
        plt.arrow( 0.1*x1, 0, 0.7*x1, 0, color='silver', zorder=1 ) 
              
    plt.axis('equal')
#    ax.set(xlim=[-0.12,0.12], ylim=[-0.12,0.12])
#    loc = plticker.MultipleLocator(base=0.05) # this locator puts ticks at regular intervals
#    ax.xaxis.set_major_locator(loc)
#    ax.yaxis.set_major_locator(loc)

    return fig, ax 
Example #23
Source File: visualize_tsp.py    From simulated-annealing-tsp with MIT License 4 votes vote down vote up
def plotTSP(paths, points, num_iters=1):

    """
    path: List of lists with the different orders in which the nodes are visited
    points: coordinates for the different nodes
    num_iters: number of paths that are in the path list

    """

    # Unpack the primary TSP path and transform it into a list of ordered
    # coordinates

    x = []; y = []
    for i in paths[0]:
        x.append(points[i][0])
        y.append(points[i][1])

    plt.plot(x, y, 'co')

    # Set a scale for the arrow heads (there should be a reasonable default for this, WTF?)
    a_scale = float(max(x))/float(100)

    # Draw the older paths, if provided
    if num_iters > 1:

        for i in range(1, num_iters):

            # Transform the old paths into a list of coordinates
            xi = []; yi = [];
            for j in paths[i]:
                xi.append(points[j][0])
                yi.append(points[j][1])

            plt.arrow(xi[-1], yi[-1], (xi[0] - xi[-1]), (yi[0] - yi[-1]),
                    head_width = a_scale, color = 'r',
                    length_includes_head = True, ls = 'dashed',
                    width = 0.001/float(num_iters))
            for i in range(0, len(x) - 1):
                plt.arrow(xi[i], yi[i], (xi[i+1] - xi[i]), (yi[i+1] - yi[i]),
                        head_width = a_scale, color = 'r', length_includes_head = True,
                        ls = 'dashed', width = 0.001/float(num_iters))

    # Draw the primary path for the TSP problem
    plt.arrow(x[-1], y[-1], (x[0] - x[-1]), (y[0] - y[-1]), head_width = a_scale,
            color ='g', length_includes_head=True)
    for i in range(0,len(x)-1):
        plt.arrow(x[i], y[i], (x[i+1] - x[i]), (y[i+1] - y[i]), head_width = a_scale,
                color = 'g', length_includes_head = True)

    #Set axis too slitghtly larger than the set of x and y
    plt.xlim(min(x)*1.1, max(x)*1.1)
    plt.ylim(min(y)*1.1, max(y)*1.1)
    plt.show()