draw the graph (network) to illustrate the solution of the tsp in python

Here is an example code to draw the graph(network) to illustrate the solution of the TSP in Python using NetworkX and Matplotlib libraries:

main.py
import networkx as nx
import matplotlib.pyplot as plt

# create a graph with nodes and edges
G = nx.Graph()
G.add_nodes_from([1, 2, 3, 4])
G.add_weighted_edges_from([(1, 2, 5), (1, 3, 10), (1, 4, 8),
                           (2, 3, 7), (2, 4, 6), (3, 4, 12)])

# define the positions of the nodes on the graph
pos = nx.spring_layout(G)

# find the shortest path using the traveling salesman problem algorithm
tsp_path = nx.tsp.nearest_neighbor(G)

# draw the graph
nx.draw_networkx_nodes(G, pos, node_size=500)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edge_labels(G, pos,
                             edge_labels={(u, v): d['weight'] for u, v, d in G.edges(data=True)})
nx.draw_networkx_edges(G, pos, edgelist=tsp_path, edge_color='r', width=2)

# show the graph
plt.axis('off')
plt.show()
831 chars
27 lines

This code will create a graph with nodes and edges, define the positions of the nodes, find the shortest path using the TSP algorithm, and then draw the graph. The edges of the TSP path will be colored in red to distinguish them from the other edges. The resulting graph will be displayed using Matplotlib.

gistlibby LogSnag