Skip to content Skip to sidebar Skip to footer

Drawing A Network With Nodes And Edges In Python3

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', '

Solution 1:

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

enter image description here

Code is modified from this Tutorial by Aric Hagberg and answer by Marcus Müller.

Solution 2:

Have a look at networkx, plot.ly, or graph-tool. I cannot recommend some text based ASCII art-like visualization. Using an elaborate package gives you way more freedom and can also work with more complex data where a visualization is not as easy to set up for.

Solution 3:

You can create a class Network to represent each edge with vertex and create a __repr__ method for custom visualization:

tree = {'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} 
classVertex:
   def__init__(self, vertex, children):
      self.vertex = vertex
      self.children = children
   def__repr__(self):
      return' -- '.join('{} -> {}:{}'.format(self.vertex, i, weights.get((self.vertex, i), weights.get((i, self.vertex), None))) for i in self.children)
    
classNetwork:
   def__init__(self, tree):
       self.__full_tree = [Vertex(*i) for i in tree.items()]
   def__repr__(self):
       return'\n'.join(repr(i) for i in self.__full_tree)

full_tree = Network(tree)
print(full_tree)

Output:

X -> Y:42
C -> M:44
M -> C:44 -- M -> F:9 -- M -> Y:6
Q -> F:27
Y -> X:42 -- Y -> M:6
F -> M:9 -- F -> Q:27

While it is far from a textbook representation, it does give the basic idea. If you are looking for a more professional graph, see the links provided by @mattmilten's answer below.

Post a Comment for "Drawing A Network With Nodes And Edges In Python3"