Introduction to NetworkX

What is NetworkX?

Wikipedia says NetworkX is a Python library for studying graphs and networks.

General usage

Import the necessary packages

import networkx as nx
import matplotlib.pyplot as plt

Create a graph object

G = nx.Graph()

Generating the nodes

G.add_node(1)
G.add_node(2)
G.add_node(3)
G.add_node(4)
G.add_node(5)
G.add_node(6)

Generating the edges

G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(2,3)
G.add_edge(4,5)
G.add_edge(5,6)
G.add_edge(3,5)

Draw the graph using matplotlib

nx.draw(G, with_labels=1)
plt.show()

png

Generating a complete graph

Generating a complete graph of 6 vertices

Z = nx.complete_graph(6)
print(Z.edges)
[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]

To get number of vertices and edges in the graph

print(Z.order())
print(Z.size())
6
15
nx.draw(Z, with_labels=1)
plt.show()

png

To generate a random graph

Generating a graph of 10 vertices with probability of 0.5 of edge formation

R = nx.gnp_random_graph(10, 0.5)
print(R.order())
print(R.size())
10
22
nx.draw(R)
plt.show()

png

2 mins · · code, networkx, network-analysis