Mathew K Analytics

Python library centre

Introduction to NetworkX in Python for Graph Analysis and Network Science

NetworkX is a Python package for the creation, manipulation, and study of complex networks. You use it to analyze graphs, social networks, computer…

⬇ Download notebookOpen in Colab ↗
NetworkXMatplotlib

📓 Full notebook

Download .ipynb

Introduction to NetworkX#

  • NetworkX is a Python package for the creation, manipulation, and study of complex networks.
  • You use it to analyze graphs, social networks, computer networks, and more.
  • Real world uses include social network analysis, transportation routes, recommendation systems, and biological networks.
  • It makes working with networks simpler by providing powerful functions and simple commands.
  • This lesson will guide you step-by-step with hands-on code and explanations.
import warnings; warnings.filterwarnings("ignore")
import sys
# Install NetworkX if missing (uncomment next line if needed)
# !{sys.executable} -m pip install networkx
import networkx as nx

Core concepts in NetworkX#

  • The main objects in NetworkX are graphs.
  • Graphs have nodes (also called vertices) and edges (connections).
  • There are different types of graphs:
    • Graph: undirected
    • DiGraph: directed
    • MultiGraph: multiple edges allowed
  • You can add or remove nodes and edges.
  • Graphs can store extra data on nodes or edges.
# Create a simple undirected graph
G = nx.Graph()
print(G)
Graph with 0 nodes and 0 edges
# Add nodes to the graph
G.add_node(1)
G.add_node(2)
G.add_node("A")
print(G.nodes())
[1, 2, 'A']
# Add edges between nodes
G.add_edge(1, 2)
G.add_edge(2, "A")
print(G.edges())
[(1, 2), (2, 'A')]
# Counting nodes and edges
print("Number of nodes:", G.number_of_nodes())
print("Number of edges:", G.number_of_edges())
Number of nodes: 3
Number of edges: 2
# Neighbors of a node
print("Neighbors of 2:", list(G.neighbors(2)))
Neighbors of 2: [1, 'A']
# Remove a node and an edge
G.remove_node("A")
G.remove_edge(1, 2)
print(G.nodes())
print(G.edges())
[1, 2]
[]

Beginner Example 1: Simple Social Network#

  • Let us represent three people and their friendships.
  • Alice, Bob, and Carol are friends.
  • Alice is friends with Bob and Carol.
  • Carol is also friends with Bob.
# Create the social network graph
social = nx.Graph()
social.add_edges_from([('Alice', 'Bob'), ('Alice', 'Carol'), ('Bob', 'Carol')])
print(social.nodes())
print(social.edges())
['Alice', 'Bob', 'Carol']
[('Alice', 'Bob'), ('Alice', 'Carol'), ('Bob', 'Carol')]
# Find the person with most friends
degree_dict = dict(social.degree())
print(degree_dict)
{'Alice': 2, 'Bob': 2, 'Carol': 2}
# Draw the graph (needs matplotlib)
import matplotlib.pyplot as plt
nx.draw(social, with_labels=True)
plt.show()
No description has been provided for this image

Beginner Example 2: Directed Graph#

  • A directed graph has edges with directions.
  • Think of who follows whom on a social app.
  • We will use nx.DiGraph for this.
# Create a directed graph
D = nx.DiGraph()
D.add_edge('John', 'Mary')
D.add_edge('Mary', 'Kate')
print(D.nodes())
print(D.edges())
print('Mary is followed by:', list(D.predecessors('Mary')))
print('Mary follows:', list(D.successors('Mary')))
['John', 'Mary', 'Kate']
[('John', 'Mary'), ('Mary', 'Kate')]
Mary is followed by: ['John']
Mary follows: ['Kate']

Beginner Example 3: Adding attributes to nodes#

  • You can store extra data with nodes.
  • For example, age or city.
# Add attributes to nodes
info = nx.Graph()
info.add_node('Sam', age=25, city='Boston')
info.add_node('Lana', age=30, city='Paris')
print(info.nodes(data=True))
[('Sam', {'age': 25, 'city': 'Boston'}), ('Lana', {'age': 30, 'city': 'Paris'})]

Intermediate Example 1: Loading a graph from edge list#

  • Sometimes you have edges listed in a file or a variable.
  • NetworkX can load graphs from an edge list.
# Loading graph from edge list
edges = [(1,2), (2,3), (3,4), (4,1)]
G2 = nx.Graph()
G2.add_edges_from(edges)
print(G2.nodes())
print(G2.edges())
[1, 2, 3, 4]
[(1, 2), (1, 4), (2, 3), (3, 4)]
# Checking if path exists between two nodes
path_exists = nx.has_path(G2, 1, 3)
print("Path exists from 1 to 3:", path_exists)
Path exists from 1 to 3: True
# Find shortest path
path = nx.shortest_path(G2, 1, 3)
print("Shortest path from 1 to 3:", path)
Shortest path from 1 to 3: [1, 2, 3]

Intermediate Example 2: Weighted edges#

  • Sometimes edges have weights: distances, costs, or times.
  • We will make a graph with weights.
# Create a weighted graph
W = nx.Graph()
W.add_edge('A', 'B', weight=5)
W.add_edge('B', 'C', weight=2)
W.add_edge('A', 'C', weight=10)
for u, v, d in W.edges(data=True):
    print(f"{u}-{v} weight: {d['weight']}")
A-B weight: 5
A-C weight: 10
B-C weight: 2
# Shortest weighted path
path = nx.shortest_path(W, 'A', 'C', weight='weight')
print("Weighted shortest path from A to C:", path)
Weighted shortest path from A to C: ['A', 'B', 'C']

Intermediate Example 3: Connected components#

  • A connected component is a chunk of nodes that are all connected.
  • Let us find connected components in a graph.
# Finding connected components
G3 = nx.Graph([(1,2), (2,3), (4,5)])
components = list(nx.connected_components(G3))
print("Connected components:", components)
Connected components: [{1, 2, 3}, {4, 5}]

Advanced Example 1: Graph algorithms - PageRank#

  • PageRank is an algorithm used by Google to rank web pages.
  • NetworkX can compute PageRank scores easily.
# PageRank on a directed graph
web = nx.DiGraph()
web.add_edges_from([('A', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B')])
pr = nx.pagerank(web)
print(pr)
{'A': 0.21481051315058508, 'B': 0.3974000441421556, 'C': 0.387789442707259}

Advanced Example 2: Exporting and importing graphs#

  • You may want to save or load graphs to files.
  • NetworkX supports writing to many formats.
# Export to and import from an adjacency list
nx.write_adjlist(social, "social.adjlist")
loaded = nx.read_adjlist("social.adjlist")
print(list(loaded.nodes()))
print(list(loaded.edges()))
['Alice', 'Bob', 'Carol']
[('Alice', 'Bob'), ('Alice', 'Carol'), ('Bob', 'Carol')]

Error handling: What if you add an edge with missing nodes?#

  • NetworkX will create nodes if you add an edge with new nodes.
  • This makes it easy, but always check for typos.
# Adding an edge with a node that does not exist
err_g = nx.Graph()
err_g.add_edge('dog', 'cat')
print(err_g.nodes())
print(err_g.edges())
['dog', 'cat']
[('dog', 'cat')]
# What if you remove a non-existent node?
try:
    err_g.remove_node('mouse')
except nx.NetworkXError as e:
    print("Error:", e)
Error: The node mouse is not in the graph.

Debugging tips#

  • Print nodes and edges after making changes.
  • Use try-except blocks to catch errors.
  • Use explicit graph properties to summarize your graph.
# Summarize a graph
print("Nodes:", W.number_of_nodes())
print("Edges:", W.number_of_edges())
print("Directed:", W.is_directed())
print("Density:", nx.density(W))
Nodes: 3
Edges: 3
Directed: False
Density: 1.0

Best practices#

  • Always use clear and short node names.
  • Keep graphs small when testing.
  • Remove unused nodes and edges.
  • Save graphs after making many changes.
# Removing all nodes and edges
print("G2 nodes before clear:", G2.nodes())
G2.clear()
print("G2 edges after clear:", G2.edges())
G2 nodes before clear: [1, 2, 3, 4]
G2 edges after clear: []

Tiny Mini-Project: Simple Flight Map#

  • You are given city pairs for airline routes.
  • Add the routes to a graph.
  • Find which city has the most direct flights.
# Define city flight routes
routes = [('NYC', 'LA'), ('NYC', 'Miami'), ('LA', 'San Francisco'), ('Miami', 'Dallas'), ('LA', 'Dallas')]
flights = nx.Graph()
flights.add_edges_from(routes)
print(flights.nodes())
print(flights.edges())
['NYC', 'LA', 'Miami', 'San Francisco', 'Dallas']
[('NYC', 'LA'), ('NYC', 'Miami'), ('LA', 'San Francisco'), ('LA', 'Dallas'), ('Miami', 'Dallas')]
# Find city with most direct flights
degrees = dict(flights.degree())
most = max(degrees, key=degrees.get)
print("City with most direct flights:", most)
City with most direct flights: LA
# Find shortest path between two cities
start = input('Enter start city: ')
end = input('Enter destination city: ')
try:
    sp = nx.shortest_path(flights, start, end)
    print('Shortest flight path:', sp)
except nx.NetworkXNoPath:
    print('No flight path found.')
Shortest flight path: ['NYC', 'LA', 'San Francisco']

Thank you for learning with us!#

  • If you want more tutorials, subscribe to our channel.
  • Like and share if this helped you.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.