How to plot the lists from a dictionary that correspond to indices of points with x and y coordinates?

Question:

Say i have a dictionary named "DictionaryOfRoutes" that includes lists like in the following example:

'DictionaryOfRoutes'= {'RouteOfVehicle_1': [0, 6, 1, 5, 0],
                       'RouteOfVehicle_2': [0, 4, 3, 0],
                       'RouteOfVehicle_3': [0, 2, 0]
}

The lists in the values of it correspond to routes and the integers inside them to indices of points.
For the points i have the following data in the form of lists:

allIds = [0, 1, 2, 3, 4, 5, 6] 
allxs = [50, 18, 33, 98, 84, 13, 50]
allys = [50, 73, 16, 58, 49, 63, 56]

For example the first point has an id of 0, x coordinates of 50, and y coordinates of 50, and so on..
I want to plot these routes like in the following png:
Example of Routes Visualized and Colorized

So far i have only managed to visualize one route (list) but not all of them, by using the following code:

def SolutionPlot(xx, yy, all_ids, matrix, final_route):   
    '''
    xx = [50, 18, 33, 98, 84, 13, 50]
    yy = [50, 73, 16, 58, 49, 63, 56]
    all_ids = [0, 1, 2, 3, 4, 5, 6] 
    matrix = a numpy array of arrays (a distance matrix)
    final_route = [0, 5, 4, 3, 2, 1]
    '''

    fig, ax = plt.subplots()
    fig.set_size_inches(6, 6)
    allxs = np.array(xx) 
    allys = np.array(yy)
    final_route = np.array(final_route) 

    ax.plot(allxs[final_route], allys[final_route], ls="-", marker="o", markersize=6)
    plt.xlim([0, 100])
    plt.ylim([0, 100])
    plt.title("Travelling Salesman (Nearest Neighbor Algorithm)")

    for xi, yi, pidi in zip(xx, yy, all_ids):
        ax.annotate(str(pidi), xy=(xi,yi))

    plt.show()

which returns the following plot:
Plot i made so far

Asked By: Yannis_Tr

||

Answers:

I hope this helps, usings the keys() function on the dictionary object for a loop helps.

final_routes=[]
for key in DictionaryOfRoutes.keys(): 
         temp=[]
         for index in DictionaryOfRoutes[key]:
              temp.append(all_Ids[index])
         final_routes.append(temp)         
SolutionPlot(xx,yy,all_Ids,final_routes)

and in the function I added this,

for final_route in final_routes:
        final_route = np.array(final_route) 
        
        ax.plot(allxs[final_route], allys[final_route], ls="-", marker="x", markersize=6)
        plt.xlim([0, 100])
        plt.ylim([0, 100])
        plt.title("Travelling Salesman (Nearest Neighbor Algorithm)")

        for xi, yi, pidi in zip(xx, yy, all_ids):
            ax.annotate(str(pidi), xy=(xi,yi))
        plt.show()

I am not so sure what the matrix variable is for.
I started this expecting to have to use plt.hold(True) but this wasn’t the case, and I’m not sure why.

Answered By: user6752871

I modified your code as below:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np


def SolutionPlot(xx, yy, all_ids, routes_dictionary , color):

    plt.style.use('dark_background')
    fig, ax = plt.subplots()

    for route in routes_dictionary.keys():


        x = [xx[i] for i in routes_dictionary[route]]
        y = [yy[i] for i in routes_dictionary[route]]
        ind = [all_ids[i] for i in routes_dictionary[route]]

        u = np.diff(x)
        v = np.diff(y)

        pos_x = x[:-1] + u/2
        pos_y = y[:-1] + v/2

        # calculate position and direction vectors:
        x0 = np.array(x[:-1])
        x1 = np.array(x[1:])


        y0 = np.array(y[:-1])
        y1 = np.array(y[1:])

        xpos = (x0+x1)/2
        ypos = (y0+y1)/2

        xdir = x1-x0
        ydir = y1-y0

        ax.plot(x,y , color = color[route] , lw = 3)
        ax.scatter(x,y , c = 'white' , edgecolors = color[route] , s = 200)

        # plot arrow on each line:
        for label, x_text, y_text, X,Y,dX,dY in zip(ind, x , y, xpos, ypos, xdir, ydir):
            ax.annotate("", xytext=(X,Y),xy=(X+0.001*dX,Y+0.001*dY), 
            arrowprops=dict(arrowstyle="->", color = color[route]), size = 20)

            ax.annotate(label, (x_text - 1 ,y_text - 1), color = 'black' , size = 10)

    plt.grid(color='white', linestyle='-', linewidth=0.7)
    plt.show()



DictionaryOfRoutes = {'RouteOfVehicle_1': [0, 6, 1, 5, 0],
                       'RouteOfVehicle_2': [0, 4, 3, 0],
                       'RouteOfVehicle_3': [0, 2, 0]}

allIds = [0, 1, 2, 3, 4, 5, 6] 
allxs = [50, 18, 33, 98, 84, 13, 50]
allys = [50, 73, 16, 58, 49, 63, 56]

colors = {'RouteOfVehicle_1': 'red',
        'RouteOfVehicle_2': 'green',
        'RouteOfVehicle_3': 'blue'}

SolutionPlot(allxs, allys, allIds, DictionaryOfRoutes , colors)

And this is the result:

enter image description here

Answered By: Mahsa Alidadi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.