Last updated: Fri Feb 14 21:16:57 GMT 2014
In this notebook we introduce the NetworkX package for network analysis. To get started using NetworkX, first we have to import the package.
Based on the NetworkX tutorial at http://networkx.github.io/documentation/latest/tutorial/tutorial.html
Source code: https://gist.github.com/MHenderson/5902080
Notebook viewer: http://nbviewer.ipython.org/gist/MHenderson/5902080
In [1]:
pylab.rcParams['figure.figsize'] = 6, 6
import random
random.seed(0)
In [1]:
import networkx as nx
G = nx.Graph()
In [2]:
G.add_node(1)
G.add_nodes_from([2,3])
In [3]:
H = nx.path_graph(10)
In [4]:
G.add_nodes_from(H)
In [5]:
G.add_node(H)
In [7]:
nx.draw(G)
In [8]:
G.add_edge(1,2)
nx.draw(G)
In [9]:
e = (2,3)
G.add_edge(*e)
nx.draw(G)
In [10]:
G.add_edges_from([(1,2),(1,3)])
G.add_edges_from(H.edges())
nx.draw(G)
In [11]:
G.remove_node(H)
In [12]:
nx.draw(G)
In [13]:
G.clear()
G.add_edges_from([(1,2),(1,3)])
G.add_node(1)
G.add_edge(1,2)
G.add_node("spam") # adds node "spam"
G.add_nodes_from("spam") # adds 4 nodes: 's', 'p', 'a', 'm'
nx.draw(G)
In [14]:
G.number_of_nodes()
Out[14]:
In [15]:
G.number_of_edges()
Out[15]:
In [16]:
G.nodes()
Out[16]:
In [17]:
G.edges()
Out[17]:
In [18]:
G.neighbors(1)
Out[18]:
In [19]:
G.remove_nodes_from("spam")
G.nodes()
Out[19]:
In [20]:
G.remove_edge(1,3)
In [21]:
H = nx.DiGraph(G)
H.edges = [(1,2),(2,1)]
In [22]:
edgelist = [(0,1),(1,2),(2,3)]
H = nx.Graph(edgelist)
nx.draw(H)
In [23]:
G[1]
Out[23]:
In [24]:
G[1][2]
Out[24]:
In [25]:
G.add_edge(1,3)
In [26]:
G[1][3]['color'] = 'blue'
In [27]:
FG = nx.Graph()
FG.add_weighted_edges_from([(1,2,0.125),(1,3,0.75),(2,4,1.2),(3,4,0.375)])
for n,nbrs in FG.adjacency_iter():
for nbr,eattr in nbrs.items():
data=eattr['weight']
if data<0.5: print('(%d, %d, %.3f)' % (n,nbr,data))
In [28]:
G = nx.Graph(day="Friday")
G.graph
Out[28]:
In [29]:
G.graph['day'] = 'Monday'
G.graph
Out[29]:
In [30]:
G.add_node(1, time = '5pm')
G.add_nodes_from([3], time = '2pm')
G.node[1]
Out[30]:
In [31]:
G.node[1]['room'] = 714
G.nodes(data = True)
Out[31]:
In [32]:
G.add_edge(1, 2, weight = 4.7 )
G.add_edges_from([(3,4),(4,5)], color = 'red')
G.add_edges_from([(1,2,{'color':'blue'}), (2,3,{'weight':8})])
G[1][2]['weight'] = 4.7
G.edge[1][2]['weight'] = 4
In [33]:
DG = nx.DiGraph()
DG.add_weighted_edges_from([(1,2,0.5), (3,1,0.75)])
In [34]:
DG.out_degree(1,weight = 'weight')
Out[34]:
In [35]:
DG.degree(1,weight = 'weight')
Out[35]:
In [36]:
DG.successors(1)
Out[36]:
In [37]:
DG.neighbors(1)
Out[37]:
In [38]:
DG
Out[38]:
In [39]:
DG = nx.Graph(DG)
In [40]:
DG
Out[40]:
In [41]:
MG = nx.MultiGraph()
MG.add_weighted_edges_from([(1,2,.5), (1,2,.75), (2,3,.5)])
In [42]:
MG.degree(weight = 'weight')
Out[42]:
In [43]:
GG = nx.Graph()
for n,nbrs in MG.adjacency_iter():
for nbr,edict in nbrs.items():
minvalue=min([d['weight'] for d in edict.values()])
GG.add_edge(n,nbr, weight = minvalue)
nx.shortest_path(GG,1,3)
Out[43]:
In [44]:
G = nx.petersen_graph()
H = nx.subgraph(G, [1,2,3,4,5,6,7,8])
nx.draw(H)
In [45]:
H1 = nx.subgraph(G, [1,2,3,4])
H2 = nx.subgraph(G, [5,6,7,8])
HH = nx.union(H1, H2)
nx.draw_circular(HH)
In [46]:
H4 = nx.disjoint_union(H1, H1)
nx.draw_circular(H4)
In [47]:
H5 = nx.cartesian_product(H1, H1)
nx.draw_circular(H5)
In [48]:
H1 = nx.subgraph(G, [1,2,3,4])
nx.draw_circular(H1)
In [49]:
H2 = nx.subgraph(G, [3,4,5,6])
nx.draw_circular(H2)
In [50]:
HH = nx.compose(H1, H2)
nx.draw_circular(HH)
In [51]:
GP = nx.nx.complement(G)
nx.draw_circular(GP)
In [52]:
petersen = nx.petersen_graph()
tutte = nx.tutte_graph()
maze = nx.sedgewick_maze_graph()
tet = nx.tetrahedral_graph()
In [53]:
nx.draw(petersen)
In [54]:
nx.draw(tutte)
In [55]:
nx.draw(maze)
In [56]:
nx.draw(tet)
In [57]:
K_5 = nx.complete_graph(5)
K_3_5 = nx.complete_bipartite_graph(3,5)
nx.draw(K_3_5)
In [58]:
barbell = nx.barbell_graph(10,10)
nx.draw(barbell)
In [59]:
lollipop = nx.lollipop_graph(10,20)
nx.draw(lollipop)
In [96]:
er = nx.erdos_renyi_graph(100,0.15)
nx.draw(er, with_labels = False, node_size = 20, linewidths = 0.5, width = 0.5, arrows = False)
In [97]:
ws = nx.watts_strogatz_graph(30,3,0.1)
nx.draw(ws, with_labels = False, node_size = 20, linewidths = 0.5, width = 0.5, arrows = False)
In [98]:
ba = nx.barabasi_albert_graph(100,5)
nx.draw(ba, with_labels = False, node_size = 20, linewidths = 0.5, width = 0.5, arrows = False)
In [99]:
red = nx.random_lobster(100,0.9,0.9)
nx.draw(red, with_labels = False, node_size = 20, linewidths = 0.5, width = 0.5, arrows = False)
In [64]:
nx.write_gml(red,"/home/matthew/tmp/red.gml")
mygraph = nx.read_gml("/home/matthew/tmp/red.gml")
In [65]:
nx.write_gml(er, "/home/matthew/tmp/er.gml")
In [100]:
nx.draw(mygraph, with_labels = False, node_size = 20, linewidths = 0.5, width = 0.5, arrows = False)
In [67]:
pylab.rcParams['figure.figsize'] = 10, 10
gephi_graph = nx.read_graphml("/home/matthew/tmp/red.graphml")
nx.draw(gephi_graph, with_labels = False, node_size = 20, linewidths = 0.5, width = 0.5, arrows = False)
In [68]:
pos = dict([(v,(gephi_graph.node[v]['x'], gephi_graph.node[v]['y'])) for v in gephi_graph.nodes()])
nx.draw(gephi_graph, pos = pos, with_labels = False, node_size = 20, linewidths = 0.5, width = 0.5, arrows = False)
In [69]:
G = nx.erdos_renyi_graph(20, 0.2)
print G.name + '\n' + len(G.name)*'-' + '\n'
print "Number of nodes:\t%i.\nNumber of edges:\t%i." % (G.order(), G.size())
In [70]:
G.nodes()
Out[70]:
In [71]:
v = G.nodes()[0]
v
Out[71]:
In [72]:
G.degree(v)
Out[72]:
In [73]:
G.neighbors(v)
Out[73]:
In [74]:
G.edges()
Out[74]:
In [75]:
e = G.edges()[5]
e
Out[75]:
In [76]:
nx.connected_components(G)
Out[76]:
In [77]:
sorted(nx.degree(G).values())
Out[77]:
In [78]:
nx.clustering(G)
Out[78]:
In [79]:
nx.degree(G,4)
Out[79]:
In [80]:
G.degree(4)
Out[80]:
In [81]:
G.degree([2,3,4])
Out[81]:
In [82]:
sorted(G.degree([2,3,4]).values())
Out[82]:
In [83]:
sorted(G.degree().values())
Out[83]:
In [84]:
pylab.rcParams['figure.figsize'] = 6, 6
nx.draw(G)
In [85]:
nx.draw_random(G)
In [86]:
nx.draw_circular(G)
In [87]:
nx.draw_spectral(G)
NetworkX has several different iterators to make it convenient to tranverse the nodes and edges of graphs. The most basic are the nodes_iter
and edges_iter
which, respectively, iterate through the nodes and edges of a graph.
If, for example, we want to iterate through the vertices of the Petersen graph and calculate the degree of each vertex in turn then we can do the following:
In [88]:
for node in G.nodes_iter():
print "The degree of node %s is %i." % (node, G.degree(node))
In fact, as this is such a common routine, NetworkX provides a special degree_iter
iterator for just this function.
In [89]:
for node, degree in G.degree_iter():
print "The degree of node %i is %i." % (node, degree)
By using the neighbors
graph method we can iterate over the nodes in a graph finding the neighbors of every node.
In [90]:
for node in G.nodes_iter():
print "The neighbors of node %i in G are %s." % (node, G.neighbors(node))
In many graph algorithms we need to examine the neighbours of a vertex to test a condition. For example, to find the neighbouring vertex of highest degree. The neighbors_iter
is a convenient method for doing this in NetworkX.
In [91]:
for i in G.neighbors_iter(v):
print i
Combining the nodes_iter
and neighbours_iter
makes it very easy to visit the neighbours of every node in a graph.
In [92]:
for node in G.nodes_iter():
for neighbor in G.neighbors_iter(node):
print "Node %i is a neighbor of node %i." % (node, neighbor)
In [93]:
for i in G.edges_iter():
print i
In [94]:
nx.node_boundary(G, [1,2,3])
Out[94]:
In [95]:
nx.edge_boundary(G, [1,2,3])
Out[95]: