NetworkX¶

  • Rich libarary the works with MAtplotlib and Plotly
  • Flexible for customization
  • Integrates with machine learning and data nalaysis workflow

Features¶

  • Graph()
  • DiGraph()
  • MultiGraph()
In [47]:
import networkx as nx
In [48]:
G = nx.Graph()
G = nx.DiGraph()
G = nx.MultiGraph()
G = nx.MultiDiGraph()
In [49]:
G = nx.Graph()
G.add_edge(1, 2)  # default edge data=1
G.add_edge(2, 3, weight=0.9)  # specify edge data
In [50]:
import math
G.add_edge('y', 'x', function=math.cos)
G.add_node(math.cos)  # any hashable can be a node
In [51]:
elist = [(1, 2), (2, 3), (1, 4), (4, 2)]
G.add_edges_from(elist)
elist = [('a', 'b', 5.0), ('b', 'c', 3.0), ('a', 'c', 1.0), ('c', 'd', 7.3)]
G.add_weighted_edges_from(elist)

Algorithms¶

In [52]:
G = nx.Graph()
e = [('a', 'b', 0.3), ('b', 'c', 0.9), ('a', 'c', 0.5), ('c', 'd', 1.2)]
G.add_weighted_edges_from(e)
print(nx.dijkstra_path(G, 'a', 'd'))
['a', 'c', 'd']

Drawing¶

In [53]:
import matplotlib.pyplot as plt
G = nx.cubical_graph()
subax1 = plt.subplot(121)
nx.draw(G)   # default spring_layout
subax2 = plt.subplot(122)
nx.draw(G, pos=nx.circular_layout(G), node_color='r', edge_color='b')
No description has been provided for this image

Simple Visualiazation¶

In [54]:
import networkx as nx
import matplotlib.pyplot as plt

# Create a directed graph instead
G = nx.DiGraph()

# Add nodes and edges (reversed direction)
G.add_nodes_from(['A', 'B', 'C', 'D', 'E', 'F'])
G.add_edges_from([
    ('B', 'A'),
    ('C', 'A'),
    ('D', 'B'),
    ('D', 'C'),
    ('E', 'D'),
    ('F', 'E'),
    ('A', 'F')
])

# Draw the graph
nx.draw(G, with_labels=True, node_color='lightcoral', edge_color='black', node_size=1000, font_size=14, arrows=True)
plt.show()
 
No description has been provided for this image
  • spring_layout() Force-directed
  • circular_layout() - Nodes in a circle
  • shell_layout() - Cocentric circles

Advanced methods¶

In [57]:
import networkx as nx
import matplotlib.pyplot as plt
import urllib.request
import zipfile
import io
import tempfile
In [58]:
# Step 1: Download ZIP
url = "http://www-personal.umich.edu/~mejn/netdata/football.zip"
sock = urllib.request.urlopen(url)
S = io.BytesIO(sock.read())
sock.close()

# Step 2: Unzip and extract football.txt
zf = zipfile.ZipFile(S)
football_bytes = zf.read("football.txt")

# Step 3: Write to temporary file and read using read_pajek()
with tempfile.NamedTemporaryFile(delete=False, suffix=".net") as tmp_file:
    tmp_file.write(football_bytes)
    tmp_file_path = tmp_file.name

G = nx.read_pajek(tmp_file_path)
G = nx.Graph(G)  # Convert from MultiGraph
G = nx.relabel_nodes(G, lambda x: x.strip('"'))  # Clean node labels

# Step 4: Visualize
plt.figure(figsize=(14, 10))
nx.draw(G, with_labels=True, node_size=300, font_size=6)
plt.title("College Football Network (2000 Season)")
plt.show()
No description has been provided for this image
In [62]:
# Generate layout
pos = nx.spring_layout(G, seed=1969)

# Drawing options
options = {
    "with_labels": True,
    "node_size": 300,
    "font_size": 6,
    "node_color": "skyblue",
    "edge_color": "gray"
}

# Draw the graph
nx.draw(G, pos, **options)
plt.title("College Football Network (Spring Layout)")
plt.show()
No description has been provided for this image
In [63]:
#Skeleton code
url = "http://www-personal.umich.edu/~mejn/netdata/football.zip"

sock = urllib.request.urlopen(url)  # open URL
s = io.BytesIO(sock.read())  # read into BytesIO "file"
sock.close()

zf = zipfile.ZipFile(s)  # zipfile object
txt = zf.read("football.txt").decode()  # read info file
gml = zf.read("football.gml").decode()  # read gml data
# throw away bogus first line with # from mejn files
gml = gml.split("\n")[1:]
G = nx.parse_gml(gml)  # parse gml data

    
# print degree for each team - number of games
for n, d in G.degree():

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