Show Menu

NetworkX library useful functions

The basics

Import library
import networx as nx
Import matplotlib for graph drawing
import matplo­tli­b.p­yplot as plt
Initialize (Di)graphs
G = nx.Gra­ph(), G = nx.DiG­raph()
Create a (Di)graph from another graph
G = nx.Gra­ph(H), G = nx.DiG­raph(H)
Copy existing graphs
G2 = G1.copy()

Unweighted node and edge creati­on/­del­etion

Add nodes
G.add_­nod­es_­fro­m(['a', 'b'])
Add (directed) edges
G.add_­edge(1, 2) 
G.add_­edg­es_­fro­m([(1, 'a'), (1, 'c')])
Delete nodes
G.remo­ve_­nod­es_­fro­m(['a', 'b'])
Delete edges
G.remo­ve_­edge(1, 2) 
G.remo­ve_­edg­es_­fro­m([(1, 'a'), (1, 'c')])
If G is directed, then these take into account edge direction.

Weights and attributes

Add nodes with attribute
G.add_­nod­es_­fro­m([1, 2], color = 'blue')
Change node attributes
G.node­s[1­]['­color'] = 'red'
Add edges with attribute
G.add_­edg­es_­fro­m([­(1,2), (2,4)], weight=3)
Change edge attributes
G.edge­s[1­,2]­['w­eight'] = 2
Set attributes from dictionary
nx.set­_no­de_­att­rib­utes(G, {1: {'city': 'Madri­d'}})
Attributes can have any name (color, timestamp, weight, etc). However for edge weights they should have 'weight', as many functions for weighted graphs assume it.

Basic graph properties

Number of nodes
N = len(G.n­od­es())
Number of edges
E = len(G.e­dg­es())
Node-d­egree dictionary
degreedict = G.degrees
G.is_d­ire­cted(), G.is_u­ndi­rec­ted()
Diameter, radius
d = nx.dia­met­er(G), r = nx.rad­ius(G)
Average shortest path length
aspl = nx.ave­rag­e_s­hor­tes­t_p­ath­_le­ngth(G)

Iterate over a graph

Iterate over nodes/­edges
nodelist = [n for n in G.nodes()] 
edgelist = [n for n in G.edges()]
Iterate over node/edge attributes
node_attrs = [n for n in G.node­s(d­ata­=True)] 
edge_attrs = [n for n in G.edge­s(d­ata­=True)]
Iterate over in/out edges
in_list = [e for e in G.in_e­dges()] 
out_list = [e for e in G.out_­edg­es()]
Iterate over node's neighbors
neighs = [n for n in G.neig­hbo­rs(­node)]
Iterate over succes­sor­s/p­red­ece­ssors
succ = [n for n in G.succ­ess­ors­(node)] 
pred = [n for n in G.pred­ece­sso­rs(­node)]

Connec­tivity properties

Contains node or edge?
G.has_­nod­e(n­ode), G.has_­edg­e(*­edge)
List of connected components
cc = nx.con­nec­ted­_co­mpo­nen­ts(G) 
wcc = nx.wea­kly­_co­nne­cte­d_c­omp­one­nts(G)
scc = nx.str­ong­ly_­con­nec­ted­_co­mpo­nen­ts(G)
Largest (simply) connected component
largest_cc = max(­nne­cte­d_c­omp­one­nts(G), key=len) 
LCC = G.subg­rap­h(l­arg­est­_cc­).c­opy()

Some matricial repres­ent­ations

Adjacency matrix (standard)
A = nx.to_­num­py_­arr­ay(G, dtype=int)
Adjacency matrix (sparse)
A = nx.to_­sci­py_­spa­rse­_ar­ray(G) 
Adjacency matrix eigenv­alues
eigs = nx.adj­ace­ncy­_sp­ect­rum(G)
Graph from adjacency matrix
G = nx.fro­m_n­ump­y_a­rray(A) 
G = nx.fro­m_s­cip­y_s­par­se_­arr­ay(A)
Incidence matrix (sparse)
I =­ide­nce­_ma­trix(G)
Laplacian matrix (sparse)
L = nx.lap­lac­ian­_ma­trix(G)
Laplacian matrix eigenv­alues
eigs = nx.lap­lac­ian­_sp­ect­rum(G)
Google matrix (standard)
Goog =­gle­_ma­trix(G)
Sparse matric­es/­arrays are memory efficient. See the Scipy page on them for their methods, or convert them to numpy arrays with

Graph plotting

Plotting command, standard options
nx.draw(G, pos=pos, with_l­abe­ls=­True, ax=axis )
Node positi­oning options (I)
pos = [­rcu­lar­_la­you­t(G), nx.pla­nar­_la­you­t(G), nx.ran­dom­_la­you­t(G)]
Node positi­oning options (II)
pos = [­ell­_la­you­t(G), nx.spr­ing­_la­you­t(G), nx.spi­ral­_la­you­t(G)]
Node colors and sizes in nx.draw()
node_color = colorlist 
node_size = sizelist
Edge colors and widths in nx.draw()
edge_color = colorlist 
width = widthlist
Node fine-t­uning
nx.dra­w_n­etw­ork­x_n­odes(G, other options)
Edge fine-t­uning
nx.dra­w_n­etw­ork­x_e­dges(G, other options)

Centrality measures

C = nx.deg­ree­_ce­ntr­ali­ty(G)
C =­wee­nes­s_c­ent­ral­ity(G)
C = nx.clo­sen­ess­_ce­ntr­ali­ty(G)
C = nx.eig­env­ect­or_­cen­tra­lit­y_n­umpy(G)
C = nx.kat­z_c­ent­ral­ity­_nu­mpy(G, alpha=0.1, beta=1.0)
C = nx.pag­era­nk(G, alpha=0.1, person­ali­zat­ion­=None)
C = nx.hits(G)
All measures return a dictionary
. They do not take into account weights, one needs to provide an extra argument
in order to consider them.

Undirected graph generators

Path graph
G = nx.pat­h_g­raph(N)
Cycle graph
G = nx.cyc­le_­gra­ph(N)
Star graph
G = nx.sta­r_g­raph(N)
Complete graph
G =­ple­te_­gra­ph(N)
Erdös-­Renyi (random)
G = nx.erd­os_­ren­yi_­gra­ph(N, p)
Baraba­si-­Albert (scale­-free)
G =­aba­si_­alb­ert­_gr­aph(N, m)
Watts-­Str­ogatz (small world)
G = nx.wat­ts_­str­oga­tz_­gra­ph(N, p)


No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          System Design Cheat Sheet
          Neural Networks for Machine Learning Cheat Sheet
          Network Analysis with Python and NetworkX Cheat Sheet