Search code examples
pythontraveling-salesman

Plotting graph an answer to traveling-salesman problem


I need to plot the graph of the solution for the TSP. I am using the TSPLIB 95 library and public problem (ch130.tsp).

I have been given the requirements for the assignment to solve the problem in a rudimentary 3 steps.

Step 1. Select randomly starting city and 'move' there.

Step 2. Select closest available (not visited) city to the currently resided one.

Step 3. If there is any available city, then repeat step 2.

I implemented code that gives me a list - path taken as the answer. Now I wish to plot a graph with my answer that will look close to this, but with only my anwser path. But have no idea how. I tried to make a variable G = tsplib95.fields.ToursField(list_of_visited_cities) but dont know what to do with it next. Can some code wizards help me with it?

Graph was generated from

problem = tsplib95.load('ch130.tsp') 
G = problem.get_graph() 
nx.draw_networkx(G) 
plt.show()

Graph of the problem


Solution

  • You can use the edgelist argument to nx.draw_networkx_edges() to only draw specific edges:

    pos = G.nodes(data="coord")
    nx.draw_networkx_nodes(G, pos)
    nx.draw_networkx_labels(G, pos)
    nx.draw_networkx_edges(G, pos, edgelist=list(zip(path, path[1:])))