Mathew K Analytics

Lesson 37 · Data visualisation in python

Visualizing Network Graphs with NetworkX and PyVis in Python

In this lesson, you will learn about network graphs using NetworkX and PyVis. You will be able to: Build and visualize graphs (networks) in Python Load real…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Welcome to Python Network Graphs!#

In this lesson, you will learn about network graphs using NetworkX and PyVis.

You will be able to:

  • Build and visualize graphs (networks) in Python
  • Load real data and display it as a graph
  • Customize nodes and edges
  • Explore real-world use cases, like airline routes or social networks

Let us start our journey!

# Let us import the required packages.
import warnings; warnings.filterwarnings('ignore')
import networkx as nx
from pyvis.network import Network
import matplotlib.pyplot as plt
import pandas as pd
 
 

What is a Network Graph?#

A network graph is a way to show how things are connected.

  • Nodes are the items (like cities, people, or websites).
  • Edges are how they link together (like flights, friendships, or links).

We use network graphs to see and study these connections easily.

# Let us create our very first, simple graph.
G = nx.Graph()
G.add_node('A')
G.add_node('B')
G.add_node('C')
G.add_edge('A', 'B')
G.add_edge('B', 'C')
G.add_edge('C', 'A')
 
 
# Let us see our basic graph as a picture.
nx.draw(G, with_labels=True, node_color='lightblue', font_weight='bold')
plt.show()
 
 
No description has been provided for this image
# Let us make the graph interactive with PyVis.
net = Network(height='350px', width='600px', notebook=True)
net.from_nx(G)
net.show('basic_graph.html')
 
 
Warning: When  cdn_resources is 'local' jupyter notebook has issues displaying graphics on chrome/safari. Use cdn_resources='in_line' or cdn_resources='remote' if you have issues viewing graphics in a notebook.
basic_graph.html

Real Data Example: Airport Routes#

Let us use real airline route data to build a network graph.

Each airport is a node. Each flight route is an edge.

This helps us understand how airports are connected worldwide.

# Data setup: Let us download airline passenger data.
df = pd.read_csv('https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv')
print('Shape:', df.shape)
df.head()
 
 
Shape: (144, 2)
Month Passengers
0 1949-01 112
1 1949-02 118
2 1949-03 132
3 1949-04 129
4 1949-05 121
# Let us plot passenger counts to see trends.
plt.figure(figsize=(10,4))
plt.plot(df['Passengers'])
plt.title('Airline Passengers Over Time')
plt.xlabel('Month')
plt.ylabel('Passengers')
plt.grid()
plt.show()
 
 
No description has been provided for this image
# Let us suppose airports are nodes and The number of passengers is the edge value.
airports = ['JFK', 'LAX', 'ORD', 'DFW', 'ATL']
# We build a toy network, for learning.
G2 = nx.DiGraph()
G2.add_nodes_from(airports)
G2.add_edge('JFK', 'LAX', weight=103)
G2.add_edge('LAX', 'DFW', weight=95)
G2.add_edge('DFW', 'ATL', weight=87)
G2.add_edge('ORD', 'ATL', weight=83)
G2.add_edge('ATL', 'JFK', weight=110)
 
 
# Let us draw the airline route graph and show edge weights.
pos = nx.circular_layout(G2)
nx.draw(G2, pos, with_labels=True, node_color='lightgreen', node_size=1200, font_size=10, arrows=True)
edge_labels = nx.get_edge_attributes(G2, 'weight')
nx.draw_networkx_edge_labels(G2, pos, edge_labels=edge_labels)
plt.show()
 
 
No description has been provided for this image
# Let us make this routes network interactive with PyVis.
net2 = Network(height='350px', width='600px', directed=True, notebook=True)
for u, v, d in G2.edges(data=True):
    net2.add_edge(u, v, value=d['weight'], title=f'Passengers: {d['weight']}')
for n in G2.nodes() :
    net2.add_node(n, label=n, title=f'Airport: {n}')
net2.show('airline_routes.html')
 
 
Warning: When  cdn_resources is 'local' jupyter notebook has issues displaying graphics on chrome/safari. Use cdn_resources='in_line' or cdn_resources='remote' if you have issues viewing graphics in a notebook.
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Cell In[9], line 4
      2 net2 = Network(height='350px', width='600px', directed=True, notebook=True)
      3 for u, v, d in G2.edges(data=True):
----> 4     net2.add_edge(u, v, value=d['weight'], title=f'Passengers: {d['weight']}')
      5 for n in G2.nodes() :
      6     net2.add_node(n, label=n, title=f'Airport: {n}')

File c:\Users\makmw\AppData\Local\Programs\Python\Python312\Lib\site-packages\pyvis\network.py:369, in Network.add_edge(self, source, to, **options)
    366 edge_exists = False
    368 # verify nodes exists
--> 369 assert source in self.get_nodes(), \
    370     "non existent node '" + str(source) + "'"
    372 assert to in self.get_nodes(), \
    373     "non existent node '" + str(to) + "'"
    375 # we only check existing edge for undirected graphs

AssertionError: non existent node 'JFK'

Exploring Graph Properties#

Graphs have useful properties:

  • Degree: How many connections a node has.
  • Shortest path: The quickest way to get from one node to another.
  • Neighbors: Who is linked to whom.

Let us check these in our next steps.

# Let us print every airport and how many airports it connects to.
for airport in G2.nodes():
    print(f"{airport}: {G2.degree(airport)} connections")
 
 
JFK: 2 connections
LAX: 2 connections
ORD: 1 connections
DFW: 2 connections
ATL: 3 connections
# Let us find the shortest route from JFK to ATL.
shortest_path = nx.shortest_path(G2, source='JFK', target='ATL')
print('Shortest path from JFK to ATL:', shortest_path)
 
 
Shortest path from JFK to ATL: ['JFK', 'LAX', 'DFW', 'ATL']
# Let us see all neighbors of ATL.
print('Neighbors of ATL:', list(G2.neighbors('ATL')))
 
 
Neighbors of ATL: ['JFK']
# Let us filter routes with more than 100 passengers.
busy_routes = [(u, v) for u, v, d in G2.edges(data=True) if d['weight'] > 100]
print('Busy routes:', busy_routes)
 
 
Busy routes: [('JFK', 'LAX'), ('ATL', 'JFK')]
# Let us show how to safely check if an airport exists before adding a route.
source = 'SEA'
target = 'JFK'
if source in G2.nodes() and target in G2.nodes():
    G2.add_edge(source, target, weight=77)
    print(f"Added a route from {source} to {target}.")
else:
    print(f"Cannot add route: one or both airports are missing.")
 
 
Cannot add route: one or both airports are missing.
# Let us remove an airport from the graph.
airport_remove = 'SEA'
if airport_remove in G2:
    G2.remove_node(airport_remove)
    print(f"Removed {airport_remove} from the network.")
else:
    print(f"Airport {airport_remove} not found.")
 
 
Airport SEA not found.
# Let us get a list of all current airports and edges.
airports_list = list(G2.nodes())
routes_list = list(G2.edges(data=True))
print('Airports:', airports_list)
print('Routes:', routes_list)
 
 
Airports: ['JFK', 'LAX', 'ORD', 'DFW', 'ATL']
Routes: [('JFK', 'LAX', {'weight': 103}), ('LAX', 'DFW', {'weight': 95}), ('ORD', 'ATL', {'weight': 83}), ('DFW', 'ATL', {'weight': 87}), ('ATL', 'JFK', {'weight': 110})]
# Mini-Project, Part 1: Build a social network graph from user input.
num_people = int(input('How many people are in your group? '))
people = []
for i in range(num_people):
    name = input(f'Enter name of person {i+1}: ')
    people.append(name)
socialG = nx.Graph()
socialG.add_nodes_from(people)
# Now add some connections.
num_connections = int(input('How many friendships? '))
for i in range(num_connections):
    p1 = input('Person 1: ')
    p2 = input('Person 2: ')
    socialG.add_edge(p1, p2)
print('People:', socialG.nodes())
print('Friendships:', socialG.edges())
 
 
People: ['Alice', 'Bob', 'Chris']
Friendships: [('Alice', 'Bob'), ('Bob', 'Chris')]
# Mini-Project, Part 2: Visualize your social network.
pos = nx.spring_layout(socialG)
nx.draw(socialG, pos, with_labels=True, node_color='orange', node_size=1500, font_size=12)
plt.title('Your Social Network')
plt.show()
 
 
No description has been provided for this image
# Best practice: Give nodes and edges meaningful names and values.
# Always check if nodes and edges exist before changing them.
# Use visuals to debug your work and spot mistakes.
 
# Troubleshooting tip: If you get an error, check for typos in node names.
# If a node is missing, add it before adding an edge.
# Check that your packages are installed with the right spelling.
 
# Extra tip: Try adding more information to your graph.
# For example, add colors by group or size by passenger count.
# Visuals are more fun when they tell a story.
 
# Quick challenge: Add a new node and connect it to two others.
# Can you plot the network and see the update?
 

Lesson Recap#

Today you built and visualized network graphs in Python.

You learned to:

  • Create nodes and edges
  • Use real data to build a graph
  • Visualize networks, both basic and interactive
  • Explore properties like degree and shortest path
  • Apply your knowledge in a real network project

Keep practicingnetworks are everywhere!

Thanks for learning with us!#

If you enjoyed this lesson, please like the video and subscribe for more beginner Python guides.

Let us know in the comments what network you want to graph next!

Have fun exploring networks!

Found this useful?

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