Centrality measures and shortest path

BeginnerGraph and network analysisNetwork analysis

Goal: Analysing a well-known social graph.

Python — example.py
import networkx as nx

G = nx.karate_club_graph()
print("Nodes and edges:", G.number_of_nodes(), G.number_of_edges())
bc = nx.betweenness_centrality(G)
top = sorted(bc, key=bc.get, reverse=True)[:3]
print("Highest betweenness:", [(n, round(bc[n], 3)) for n in top])
print("Shortest path 0→33:", nx.shortest_path(G, 0, 33))
print("Number of communities (Louvain):", len(nx.community.louvain_communities(G, seed=0)))

Code explanation

Zachary's karate club graph ships with NetworkX. We compute degree and betweenness centrality and find a shortest path. These measures are also used as node features before graph neural networks.

Requirements

Shell
pip install networkx

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

Nodes and edges: 34 78
Highest betweenness: [(0, 0.438), (33, 0.304), (32, 0.145)]
Shortest path 0→33: [0, 8, 33]
Number of communities (Louvain): 4

This example was actually run and tested on 21 November 2026 on a CPU — networkx 3.7, python 3.13.18

Libraries used