# Import libraries
# NetworkX is a package for the Python programming language that's used to create, manipulate, and study the structure, dynamics, and functions of compl
import networkx as nx
# Matplotlib is a plotting library for the Python
import matplotlib.pyplot as plt
# Create an empty dia graph with no nodes and no edges
G = nx.DiGraph()
# Adding node(s) and links
G.add_edges_from([(1, 1), (1, 7), (2, 1), (2, 2), (2, 3),
(2, 6), (3, 5), (4, 3), (5, 4), (5, 8),
(5, 9), (6, 4), (7, 2), (7, 6), (8, 7)])
# Draw graph
nx.draw(G, with_labels = True)
plt.show()
plt.savefig("filename.png")
<Figure size 432x288 with 0 Axes>
plt.figure(figsize =(9, 9))
nx.draw(G, with_labels = True, node_color ='green')
# Change layout of graph
pos=nx.spring_layout(G)
# Draw graph
nx.draw(G, with_labels = True)
plt.show()
# getting different graph attributes
print("Total number of nodes: ", int(G.number_of_nodes()))
print("Total number of edges: ", int(G.number_of_edges()))
print("List of all nodes: ", list(G.nodes()))
print("List of all edges: ", list(G.edges()))
print("In-degree for all nodes: ", dict(G.in_degree()))
print("Out degree for all nodes: ", dict(G.out_degree))
print("List of all nodes we can go to in a single step from node 2: ",
list(G.successors(2)))
print("List of all nodes from which we can go to node 2 in a single step: ",
list(G.predecessors(2)))
Total number of nodes: 9
Total number of edges: 15
List of all nodes: [1, 7, 2, 3, 6, 5, 4, 8, 9]
List of all edges: [(1, 1), (1, 7), (7, 2), (7, 6), (2, 1), (2, 2), (2, 3), (2, 6), (3, 5), (6, 4), (5, 4), (5, 8), (5, 9), (4, 3), (8, 7)]
In-degree for all nodes: {1: 2, 7: 2, 2: 2, 3: 2, 6: 2, 5: 1, 4: 2, 8: 1, 9: 1}
Out degree for all nodes: {1: 2, 7: 2, 2: 4, 3: 1, 6: 1, 5: 3, 4: 1, 8: 1, 9: 0}
List of all nodes we can go to in a single step from node 2: [1, 2, 3, 6]
List of all nodes from which we can go to node 2 in a single step: [2, 7]