Introduction to NetworkX

Some Key Featuress

  • A python library for creating, analyzing and visualizing graphs
  • Easy to use
  • Excellent documentation
  • Free software

Creating graphs


In [1]:
import networkx as nx
%matplotlib inline

In [2]:
G=nx.Graph()

In [3]:
G.nodes()


Out[3]:
[]

In [4]:
G.edges()


Out[4]:
[]

In [5]:
G.add_node(1)

In [6]:
G.nodes()


Out[6]:
[1]

In [7]:
G.add_nodes_from([5,6,7])

In [8]:
G.add_edge(7,1)

In [9]:
nx.draw(G)



In [10]:
G.add_edges_from([(6,7),(1,5)])

In [11]:
nx.draw(G)


Accessing graph elements

Looping over nodes


In [12]:
for n in G.nodes_iter():
    print(n)


1
5
6
7

Looping over edges


In [13]:
for u,v in G.edges_iter():
    print(u,v)


1 5
1 7
6 7

Looping over neighbourhood of a node


In [14]:
G[1]    #All dictionaries


Out[14]:
{5: {}, 7: {}}

In [15]:
G[5]


Out[15]:
{1: {}}

So it's really easy to loop over the whole graph or the neighbourhood of a node


In [16]:
[n for n in G[1]]


Out[16]:
[5, 7]

In [17]:
G.neighbors(1)


Out[17]:
[5, 7]

Accessing global graph properties


In [18]:
G.number_of_nodes()


Out[18]:
4

In [19]:
G.number_of_edges()


Out[19]:
3

In [20]:
nx.diameter(G)


Out[20]:
3

In [21]:
nx.radius(G)


Out[21]:
2

Time for some Exercises!