Finding influencers, bottlenecks and key pages is often the whole point of a network analysis.
Centrality measures how important a node is, and different definitions of importance give different measures. All return a dict node -> score.
- Degree centrality (
nx.degree_centrality): the fraction of other nodes it touches directly. Cheap; spots hubs. - Closeness (
nx.closeness_centrality): based on the average distance to all other nodes. High means it can reach everyone quickly. - Betweenness (
nx.betweenness_centrality): the fraction of shortest paths between other pairs that pass through the node. Finds bridges and bottlenecks, such as brokers between communities. Takes O(nm) time, so for large graphs passk=500to sample source nodes and get an approximation. - Eigenvector centrality (
nx.eigenvector_centrality): important if connected to important nodes. - PageRank (
nx.pagerank(G, alpha=0.85)): the random-surfer version for directed graphs, robust to dangling nodes. The default choice for link graphs.
Weighted variants take weight=. Be careful: in betweenness and closeness the weight is a distance (bigger means farther), while in PageRank and eigenvector centrality it's a strength (bigger means stronger). Invert weights if needed.
Get the top nodes with sorted(scores, key=scores.get, reverse=True)[:5]. Different measures often disagree, and that disagreement itself is informative.
Example
import networkx as nx
# Two triangles joined through a single broker node "x"
G = nx.Graph([("a", "b"), ("b", "c"), ("c", "a"),
("d", "e"), ("e", "f"), ("f", "d"),
("c", "x"), ("x", "d")])
def top(scores, n=2):
return [k for k, _ in sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))[:n]]
print(top(nx.degree_centrality(G))) # ['c', 'd'] (degree 3 each)
bc = nx.betweenness_centrality(G)
print(top(bc, 3)) # ['x', 'c', 'd'] (all paths cross x)
print(round(bc["x"], 3), bc["a"]) # 0.6 0.0
D = nx.DiGraph([("a", "hub"), ("b", "hub"), ("c", "hub"), ("hub", "a")])
pr = nx.pagerank(D, alpha=0.85)
print(max(pr, key=pr.get)) # hubRemember
- Degree = hubs, betweenness = bottlenecks, closeness = reach, PageRank = link importance
- Approximate betweenness on big graphs with
k=samples - Weights mean distance for path-based measures and strength for PageRank
Watch out for
- Passing similarity weights (bigger = closer) to betweenness, which treats them as distances.