This is a little set of examples of networkx. Very very few changes were made from the examples provided by the authors in https://github.com/networkx/networkx/tree/master/examples

Therefore please consider all this code:

# Pieter Swart [email protected]¶

You'll need networkx for this

In [30]:
import networkx as nx


and of course matplotlib for plotting!!

In [31]:
import matplotlib.pyplot as plt

In [32]:
# define G as the "path graph" w/8 nodes
G=nx.path_graph(8)

# 3 commands needed to draw/plot/save
nx.draw(G)
#plt.savefig("simple_path.png") # save as png
plt.show() # display

In [33]:
# note that networkx handles *really* simple file input
!rm simple.txt
!touch simple.txt
!echo "0 1" >> simple.txt
!echo "1 2" >> simple.txt
!echo "2 0" >> simple.txt
!cat simple.txt

0 1
1 2
2 0

In [34]:
G = nx.read_edgelist('simple.txt', create_using= nx.DiGraph())
nx.draw(G)
plt.show() # display

In [35]:
print("radius: %d" % nx.radius(G))
print("diameter: %d" % nx.diameter(G))
print("eccentricity: %s" % nx.eccentricity(G))
print("center: %s" % nx.center(G))
print("periphery: %s" % nx.periphery(G))
print("density: %s" % nx.density(G))

radius: 2
diameter: 2
eccentricity: {u'1': 2, u'0': 2, u'2': 2}
center: [u'1', u'0', u'2']
periphery: [u'1', u'0', u'2']
density: 0.5

In [36]:
# one of the most famous graphs is the 34-node "karate club" graph
G=nx.karate_club_graph()
print("Node Degree")
for v in G:
print('%s %s' % (v,G.degree(v)))

Node Degree
0 16
1 9
2 10
3 6
4 3
5 4
6 4
7 4
8 5
9 2
10 3
11 1
12 2
13 5
14 2
15 2
16 2
17 2
18 2
19 3
20 2
21 2
22 2
23 5
24 3
25 3
26 2
27 4
28 3
29 4
30 4
31 6
32 12
33 17

In [37]:
# here's an example of coloring
pos=nx.spring_layout(G)
nx.draw(G,pos,node_color=range(34),node_size=800,cmap=plt.cm.Blues)
plt.savefig("node_colormap.png") # save as png
plt.show() # display


note: it's random! try again and again for new results. :) or :(

In [38]:
print("radius: %d" % nx.radius(G))
print("diameter: %d" % nx.diameter(G))
print("eccentricity: %s" % nx.eccentricity(G))
print("center: %s" % nx.center(G))
print("periphery: %s" % nx.periphery(G))
print("density: %s" % nx.density(G))

radius: 3
diameter: 5
eccentricity: {0: 3, 1: 3, 2: 3, 3: 3, 4: 4, 5: 4, 6: 4, 7: 4, 8: 3, 9: 4, 10: 4, 11: 4, 12: 4, 13: 3, 14: 5, 15: 5, 16: 5, 17: 4, 18: 5, 19: 3, 20: 5, 21: 4, 22: 5, 23: 5, 24: 4, 25: 4, 26: 5, 27: 4, 28: 4, 29: 5, 30: 4, 31: 3, 32: 4, 33: 4}
center: [0, 1, 2, 3, 8, 13, 19, 31]
periphery: [14, 15, 16, 18, 20, 22, 23, 26, 29]
density: 0.139037433155

In [39]:
# let's try this for a 20-node star graph
G=nx.star_graph(20)
pos=nx.spring_layout(G)
colors=range(20)
nx.draw(G,pos,node_color='#A0CBE2',edge_color=colors,width=4,edge_cmap=plt.cm.Blues,with_labels=False)
plt.savefig("edge_colormap.png") # save as png
plt.show() # display

In [40]:
for v in G:
print('%s %s' % (v,G.degree(v)))

0 20
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
10 1
11 1
12 1
13 1
14 1
15 1
16 1
17 1
18 1
19 1
20 1

In [41]:
print("radius: %d" % nx.radius(G))
print("diameter: %d" % nx.diameter(G))
print("eccentricity: %s" % nx.eccentricity(G))
print("center: %s" % nx.center(G))
print("periphery: %s" % nx.periphery(G))
print("density: %s" % nx.density(G))

radius: 1
diameter: 2
eccentricity: {0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 2, 7: 2, 8: 2, 9: 2, 10: 2, 11: 2, 12: 2, 13: 2, 14: 2, 15: 2, 16: 2, 17: 2, 18: 2, 19: 2, 20: 2}
center: [0]
periphery: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
density: 0.0952380952381

In [42]:
# here's an example of networkx syntax for file i/o:
from networkx import *
import sys
G=grid_2d_graph(5,5)  # 5x5 grid

try: # Python 2.6+
except TypeError: # Python 3.x
# write edgelist to grid.edgelist
write_edgelist(G,path="grid.edgelist",delimiter=":")

#-c -f /Users/wiggins/.ipython/profile_default/security/kernel-b51c077d-2bc7-4165-a6ee-f2b4b37469d3.json --pylab inline --IPKernelApp.parent_appname='ipython-notebook' --profile-dir /Users/wiggins/.ipython/profile_default --parent=1
# GMT Mon Aug 25 15:41:03 2014
# grid_2d_graph
(1, 3) (1, 2) (0, 3) (2, 3) (1, 4)
(3, 0) (2, 0) (3, 1) (4, 0)
(2, 1) (2, 0) (3, 1) (1, 1) (2, 2)
(0, 3) (0, 2) (0, 4)
(4, 0) (4, 1)
(1, 2) (1, 1) (0, 2) (2, 2)
(3, 3) (3, 4) (3, 2) (2, 3) (4, 3)
(4, 4) (3, 4) (4, 3)
(2, 2) (3, 2) (2, 3)
(4, 1) (4, 2) (3, 1)
(1, 1) (0, 1) (1, 0)
(3, 2) (4, 2) (3, 1)
(0, 0) (0, 1) (1, 0)
(0, 4) (1, 4)
(1, 4) (2, 4)
(2, 3) (2, 4)
(4, 2) (4, 3)
(1, 0) (2, 0)
(0, 1) (0, 2)
(3, 1)
(2, 4) (3, 4)
(2, 0)
(4, 3)
(3, 4)
(0, 2)

In [43]:
# ok now something cool: an overlay of graph and its degree rank plot
G = nx.gnp_random_graph(100,0.02)

degree_sequence=sorted(nx.degree(G).values(),reverse=True) # degree sequence
#print "Degree sequence", degree_sequence
dmax=max(degree_sequence)

plt.loglog(degree_sequence,'b-',marker='o')
plt.title("Degree rank plot")
plt.ylabel("degree")
plt.xlabel("rank")

# draw graph in inset
plt.axes([0.45,0.45,0.45,0.45])
Gcc=sorted(nx.connected_component_subgraphs(G), key = len, reverse=True)[0]
pos=nx.spring_layout(Gcc)
plt.axis('off')
nx.draw_networkx_nodes(Gcc,pos,node_size=20)
nx.draw_networkx_edges(Gcc,pos,alpha=0.4)

plt.savefig("degree_rank_plot.png")
plt.show()


Finally an example of 'real world' data. Here I reproduce the example python in full, with credit and Copyright.

In [104]:
#!/usr/bin/env python
"""
Load football network in GML format and compute some network statistcs.

into a NetworkX graph.

http://www-personal.umich.edu/~mejn/netdata/football.zip

"""
__author__ = """Aric Hagberg ([email protected])"""
#    Aric Hagberg <[email protected]>
#    Dan Schult <[email protected]>
#    Pieter Swart <[email protected]>

try:
import pyparsing
except ImportError as e:
raise ImportError(str(e)+". Check http://pyparsing.wikispaces.com/")

from networkx import *

url="http://www-personal.umich.edu/~mejn/netdata/football.zip"

try: # Python 3.x
import urllib.request as urllib
except ImportError: # Python 2.x
import urllib
import io
import zipfile

sock = urllib.urlopen(url)  # open URL
sock.close()

zf = zipfile.ZipFile(s) # zipfile object
# throw away bogus first line with # from mejn files
gml=gml.split('\n')[1:]
G=parse_gml(gml) # parse gml data

print(txt)
# print degree for each team - number of games
for n,d in G.degree_iter():
print('%s %d' % (n, d))

The file football.gml contains the network of American football games
between Division IA colleges during regular season Fall 2000, as compiled
by M. Girvan and M. Newman.  The nodes have values that indicate to which
conferences they belong.  The values are as follows:

0 = Atlantic Coast
1 = Big East
2 = Big Ten
3 = Big Twelve
4 = Conference USA
5 = Independents
6 = Mid-American
7 = Mountain West
8 = Pacific Ten
9 = Southeastern
10 = Sun Belt
11 = Western Athletic

If you make use of these data, please cite M. Girvan and M. E. J. Newman,
Community structure in social and biological networks,
Proc. Natl. Acad. Sci. USA 99, 7821-7826 (2002).

Mississippi 11
OregonState 10
NotreDame 11
Wyoming 11
Minnesota 11
Illinois 11
Kent 10
Toledo 9
Indiana 11
Clemson 10
Texas 11
BostonCollege 11
MississippiState 11
Tulsa 12
Kansas 10
SouthernMethodist 12
Connecticut 7
Tulane 11
Duke 11
Missouri 10
TexasChristian 11
LouisianaState 10
CentralFlorida 8
Cincinnati 11
Washington 11
OklahomaState 10
Marshall 11
IowaState 11
Army 11
LouisianaTech 10
AlabamaBirmingham 10
MiamiOhio 11
MiddleTennesseeState 9
Maryland 11
Rice 11
SanJoseState 11
NorthCarolinaState 11
Arizona 11
Wisconsin 12
Pittsburgh 11
Michigan 11
Purdue 11
Oregon 11
Syracuse 11
SouthernCalifornia 12
Northwestern 11
SanDiegoState 11
Florida 11
BowlingGreenState 11
NewMexicoState 11
Baylor 10
MichiganState 11
Ohio 10
Buffalo 11
SouthernMississippi 10
WashingtonState 11
BoiseState 9
WakeForest 10
NorthernIllinois 10
KansasState 13
WesternMichigan 11
Navy 11
VirginiaTech 11
UtahState 9
Oklahoma 12
GeorgiaTech 11
Louisville 10
Arkansas 10
Temple 11
BallState 10
Vanderbilt 11
LouisianaLafayette 8
California 11
Akron 11
FresnoState 11
Georgia 10
TexasA&M 11
FloridaState 12
Rutgers 10
PennState 12
LouisianaMonroe 8
ArizonaState 11
Memphis 11
BrighamYoung 12
UCLA 11
Auburn 11
ArkansasState 10
EasternMichigan 11
SouthCarolina 11
MiamiFlorida 10
Idaho 9
OhioState 11
Utah 11
Virginia 10
TexasElPaso 11
TexasTech 12
NewMexico 11
CentralMichigan 11
Stanford 11
EastCarolina 11
NorthCarolina 11
Hawaii 11
Kentucky 10