I have coded an algorithm to carry out the dijkstra's algorithm. This is for a maths revision game I am making as part of my A level coursework.
I have this data:
Vertices: {'M', 'Y', 'X', 'C', 'F', 'Q'}
Edges: defaultdict(<class 'list'>, {'X': ['Y'], 'C': ['M'], 'M': ['C', 'F', 'Y'], 'Q': ['F'], 'Y': ['X', 'M'], 'F': ['M', 'Q']})
Weights: {('M', 'C'): 44, ('Q', 'F'): 27, ('Y', 'X'): 42, ('X', 'Y'): 42, ('Y', 'M'): 6, ('M', 'F'): 9, ('M', 'Y'): 6, ('F', 'Q'): 27, ('F', 'M'): 9, ('C', 'M'): 44}
These values are random, so different every time.
What can I use to visualise the network to make it more clear, something like with nodes (vertices) and arcs (edges)? Or is there a way I can visualise it using print statements like print("o----o")
.
An example with networkx
package. We will need Weights
you provided to build the graph.
import matplotlib.pyplot as plt
import networkx as nx
%matplotlib notebook
Weights = {('M', 'C'): 44, ('Q', 'F'): 27, ('Y', 'X'): 42, ('X', 'Y'): 42, ('Y', 'M'): 6, ('M', 'F'): 9, ('M', 'Y'): 6, ('F', 'Q'): 27, ('F', 'M'): 9, ('C', 'M'): 44}
G = nx.Graph()
# each edge is a tuple of the form (node1, node2, {'weight': weight})
edges = [(k[0], k[1], {'weight': v}) for k, v in Weights.items()]
G.add_edges_from(edges)
pos = nx.spring_layout(G) # positions for all nodes
# nodes
nx.draw_networkx_nodes(G,pos,node_size=700)
# labels
nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif')
# edges
nx.draw_networkx_edges(G,pos,edgelist=edges, width=6)
# weights
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
Layout
Code is modified from this Tutorial by Aric Hagberg and answer by Marcus Müller.