Search code examples
pythonplotcoordinate-systems

How to plot routes in python


I have been studying Travelling Salesman Problem recently. I need to get route visualization on coordinate system. I have longtitudes and latitudes as series: [x_c],[y_c]

I get the TSP solution, according to the solution my best route is:

best_route2
array([ 0.,  7., 10.,  8.,  9.,  1., 13., 11.,  5.,  6., 12.,  4.,  3.,
    2.,  0.])

I start plotting as follows. But i cannot find a way connected the dots in best route.

plt.plot(x_c[0], y_c[0], c='r', marker='*')
plt.scatter(x_c[1:], y_c[1:], c='b')

plot

How can I connect the dots in the following order? 0 - 7 - 10 - 8 - 9 - 1 - 13 - 11 - 5 - 6 - 12 - 4 - 3 - 2 - 0

Thanks!


Solution

  • Here is a code snippet you could modify to meet your requirements:

    import numpy as np
    import matplotlib.pyplot as plt
    
    #number of points
    n_points = 8
    
    #for the reproducibility purpose
    np.random.seed(12345)
    
    #an array to be used as the hypothetical order
    myorder=np.random.choice(range(n_points), n_points, replace=False)
    
    #sample coordinates
    x_c = np.arange(n_points)
    y_c = np.random.uniform(0,n_points,n_points)
    
    #sorting coordinates
    x_c_sorted=[]
    y_c_sorted=[]
    for sn in myorder:
        x_c_sorted.append(x_c[sn])
        y_c_sorted.append(y_c[sn])
        
    #plotting
    plt.plot(x_c_sorted, y_c_sorted, '--o')
    plt.show()
    

    enter image description here