文章目录
NetworkX实例1. 基础Basic2. 绘图Drawing3. 图标Graph
NetworkX实例
代码下载地址 NetworkX 2.4版本的通用示例性示例。本教程介绍了约定和基本的图形操作。具体章节内容如下:
基础Basic绘图Drawing图标Graph
本文参考:
https://networkx.github.io/documentation/stable/auto_examples/index.html
1. 基础Basic
读写图 Read and write graphs属性 Properties
import sys
import matplotlib
.pyplot
as plt
import networkx
as nx
G
= nx
.grid_2d_graph
(5, 5)
for line
in nx
.generate_adjlist
(G
):
print(line
)
nx
.draw
(G
)
plt
.show
()
(0, 0) (1, 0) (0, 1)
(0, 1) (1, 1) (0, 2)
(0, 2) (1, 2) (0, 3)
(0, 3) (1, 3) (0, 4)
(0, 4) (1, 4)
(1, 0) (2, 0) (1, 1)
(1, 1) (2, 1) (1, 2)
(1, 2) (2, 2) (1, 3)
(1, 3) (2, 3) (1, 4)
(1, 4) (2, 4)
(2, 0) (3, 0) (2, 1)
(2, 1) (3, 1) (2, 2)
(2, 2) (3, 2) (2, 3)
(2, 3) (3, 3) (2, 4)
(2, 4) (3, 4)
(3, 0) (4, 0) (3, 1)
(3, 1) (4, 1) (3, 2)
(3, 2) (4, 2) (3, 3)
(3, 3) (4, 3) (3, 4)
(3, 4) (4, 4)
(4, 0) (4, 1)
(4, 1) (4, 2)
(4, 2) (4, 3)
(4, 3) (4, 4)
(4, 4)
import matplotlib
.pyplot
as plt
from networkx
import nx
G
= nx
.lollipop_graph
(4, 6)
pathlengths
= []
print("source vertex {target:length, }")
for v
in G
.nodes
():
spl
= dict(nx
.single_source_shortest_path_length
(G
, v
))
print('{} {} '.format(v
, spl
))
for p
in spl
:
pathlengths
.append
(spl
[p
])
print('')
print("average shortest path length %s" % (sum(pathlengths
) / len(pathlengths
)))
dist
= {}
for p
in pathlengths
:
if p
in dist
:
dist
[p
] += 1
else:
dist
[p
] = 1
print('')
print("length #paths")
verts
= dist
.keys
()
for d
in sorted(verts
):
print('%s %d' % (d
, dist
[d
]))
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
))
nx
.draw
(G
, with_labels
=True)
plt
.show
()
source vertex {target:length, }
0 {0: 0, 1: 1, 2: 1, 3: 1, 4: 2, 5: 3, 6: 4, 7: 5, 8: 6, 9: 7}
1 {1: 0, 0: 1, 2: 1, 3: 1, 4: 2, 5: 3, 6: 4, 7: 5, 8: 6, 9: 7}
2 {2: 0, 0: 1, 1: 1, 3: 1, 4: 2, 5: 3, 6: 4, 7: 5, 8: 6, 9: 7}
3 {3: 0, 0: 1, 1: 1, 2: 1, 4: 1, 5: 2, 6: 3, 7: 4, 8: 5, 9: 6}
4 {4: 0, 5: 1, 3: 1, 6: 2, 0: 2, 1: 2, 2: 2, 7: 3, 8: 4, 9: 5}
5 {5: 0, 4: 1, 6: 1, 3: 2, 7: 2, 0: 3, 1: 3, 2: 3, 8: 3, 9: 4}
6 {6: 0, 5: 1, 7: 1, 4: 2, 8: 2, 3: 3, 9: 3, 0: 4, 1: 4, 2: 4}
7 {7: 0, 6: 1, 8: 1, 5: 2, 9: 2, 4: 3, 3: 4, 0: 5, 1: 5, 2: 5}
8 {8: 0, 7: 1, 9: 1, 6: 2, 5: 3, 4: 4, 3: 5, 0: 6, 1: 6, 2: 6}
9 {9: 0, 8: 1, 7: 2, 6: 3, 5: 4, 4: 5, 3: 6, 0: 7, 1: 7, 2: 7}
average shortest path length 2.86
length #paths
0 10
1 24
2 16
3 14
4 12
5 10
6 8
7 6
radius: 4
diameter: 7
eccentricity: {0: 7, 1: 7, 2: 7, 3: 6, 4: 5, 5: 4, 6: 4, 7: 5, 8: 6, 9: 7}
center: [5, 6]
periphery: [0, 1, 2, 9]
density: 0.26666666666666666
2. 绘图Drawing
简单路径Simple Path节点颜色Node Colormap边的颜色 Edge Colormap带颜色的房子 House With Colors环形树Circular Tree等级排列Degree Rank谱嵌入Spectral Embedding四宫格Four Grids自我中心网络Ego Graph度直方图Degree histogram随机几何图形Random Geometric Graph加权图Weighted Graph有向图Directed Graph标签和颜色Labels And Colors最大连通分支Giant Component地图集Atlas
import matplotlib
.pyplot
as plt
import networkx
as nx
G
= nx
.path_graph
(8)
nx
.draw
(G
)
plt
.show
()
import matplotlib
.pyplot
as plt
import networkx
as nx
G
= nx
.cycle_graph
(24)
pos
= nx
.spring_layout
(G
, iterations
=200)
nx
.draw
(G
, pos
, node_color
=range(24), node_size
=800, cmap
=plt
.cm
.Blues
)
plt
.show
()
import matplotlib
.pyplot
as plt
import networkx
as nx
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
.show
()
import matplotlib
.pyplot
as plt
import networkx
as nx
G
= nx
.house_graph
()
pos
= {0: (0, 0),
1: (1, 0),
2: (0, 1),
3: (1, 1),
4: (0.5, 2.0)}
nx
.draw_networkx_nodes
(G
, pos
, node_size
=2000, nodelist
=[4])
nx
.draw_networkx_nodes
(G
, pos
, node_size
=3000, nodelist
=[0, 1, 2, 3], node_color
='b')
nx
.draw_networkx_edges
(G
, pos
, alpha
=0.5, width
=6)
plt
.axis
('off')
plt
.show
()
import matplotlib
.pyplot
as plt
import networkx
as nx
import pydot
from networkx
.drawing
.nx_pydot
import graphviz_layout
G
= nx
.balanced_tree
(3, 5)
pos
= graphviz_layout
(G
, prog
='twopi')
plt
.figure
(figsize
=(8, 8))
nx
.draw
(G
, pos
, node_size
=20, alpha
=0.5, node_color
="blue", with_labels
=False)
plt
.axis
('equal')
plt
.show
()
import networkx
as nx
import matplotlib
.pyplot
as plt
G
= nx
.gnp_random_graph
(100, 0.02)
degree_sequence
= sorted([d
for n
, d
in G
.degree
()], reverse
=True)
dmax
= max(degree_sequence
)
plt
.loglog
(degree_sequence
, 'b-', marker
='o')
plt
.title
("Degree rank plot")
plt
.ylabel
("degree")
plt
.xlabel
("rank")
plt
.axes
([0.45, 0.45, 0.45, 0.45])
Gcc
= G
.subgraph
(sorted(nx
.connected_components
(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
.show
()
import matplotlib
.pyplot
as plt
import networkx
as nx
options
= {
'node_color': 'C0',
'node_size': 100,
}
G
= nx
.grid_2d_graph
(6, 6)
plt
.subplot
(332)
nx
.draw_spectral
(G
, **options
)
G
.remove_edge
((2, 2), (2, 3))
plt
.subplot
(334)
nx
.draw_spectral
(G
, **options
)
G
.remove_edge
((3, 2), (3, 3))
plt
.subplot
(335)
nx
.draw_spectral
(G
, **options
)
G
.remove_edge
((2, 2), (3, 2))
plt
.subplot
(336)
nx
.draw_spectral
(G
, **options
)
G
.remove_edge
((2, 3), (3, 3))
plt
.subplot
(337)
nx
.draw_spectral
(G
, **options
)
G
.remove_edge
((1, 2), (1, 3))
plt
.subplot
(338)
nx
.draw_spectral
(G
, **options
)
G
.remove_edge
((4, 2), (4, 3))
plt
.subplot
(339)
nx
.draw_spectral
(G
, **options
)
plt
.show
()
import matplotlib
.pyplot
as plt
import networkx
as nx
G
= nx
.grid_2d_graph
(4, 4)
pos
= nx
.spring_layout
(G
, iterations
=100)
plt
.subplot
(221)
nx
.draw
(G
, pos
, font_size
=8)
plt
.subplot
(222)
nx
.draw
(G
, pos
, node_color
='k', node_size
=0, with_labels
=False)
plt
.subplot
(223)
nx
.draw
(G
, pos
, node_color
='g', node_size
=250, with_labels
=False, width
=6)
plt
.subplot
(224)
H
= G
.to_directed
()
nx
.draw
(H
, pos
, node_color
='b', node_size
=20, with_labels
=False)
plt
.show
()
from operator
import itemgetter
import matplotlib
.pyplot
as plt
import networkx
as nx
if __name__
== '__main__':
n
= 1000
m
= 2
G
= nx
.generators
.barabasi_albert_graph
(n
, m
)
node_and_degree
= G
.degree
()
(largest_hub
, degree
) = sorted(node_and_degree
, key
=itemgetter
(1))[-1]
hub_ego
= nx
.ego_graph
(G
, largest_hub
)
pos
= nx
.spring_layout
(hub_ego
)
nx
.draw
(hub_ego
, pos
, node_color
='b', node_size
=50, with_labels
=False)
nx
.draw_networkx_nodes
(hub_ego
, pos
, nodelist
=[largest_hub
], node_size
=300, node_color
='r')
plt
.show
()
import collections
import matplotlib
.pyplot
as plt
import networkx
as nx
G
= nx
.gnp_random_graph
(100, 0.02)
degree_sequence
= sorted([d
for n
, d
in G
.degree
()], reverse
=True)
degreeCount
= collections
.Counter
(degree_sequence
)
deg
, cnt
= zip(*degreeCount
.items
())
fig
, ax
= plt
.subplots
()
plt
.bar
(deg
, cnt
, width
=0.80, color
='b')
plt
.title
("Degree Histogram")
plt
.ylabel
("Count")
plt
.xlabel
("Degree")
ax
.set_xticks
([d
+ 0.4 for d
in deg
])
ax
.set_xticklabels
(deg
)
plt
.axes
([0.4, 0.4, 0.5, 0.5])
Gcc
= G
.subgraph
(sorted(nx
.connected_components
(G
), key
=len, reverse
=True)[0])
pos
= nx
.spring_layout
(G
)
plt
.axis
('off')
nx
.draw_networkx_nodes
(G
, pos
, node_size
=20)
nx
.draw_networkx_edges
(G
, pos
, alpha
=0.4)
plt
.show
()
import matplotlib
.pyplot
as plt
import networkx
as nx
G
= nx
.random_geometric_graph
(200, 0.125)
pos
= nx
.get_node_attributes
(G
, 'pos')
dmin
= 1
ncenter
= 0
for n
in pos
:
x
, y
= pos
[n
]
d
= (x
- 0.5)**2 + (y
- 0.5)**2
if d
< dmin
:
ncenter
= n
dmin
= d
p
= dict(nx
.single_source_shortest_path_length
(G
, ncenter
))
plt
.figure
(figsize
=(8, 8))
nx
.draw_networkx_edges
(G
, pos
, nodelist
=[ncenter
], alpha
=0.4)
nx
.draw_networkx_nodes
(G
, pos
, nodelist
=list(p
.keys
()),
node_size
=80,
node_color
=list(p
.values
()),
cmap
=plt
.cm
.Reds_r
)
plt
.xlim
(-0.05, 1.05)
plt
.ylim
(-0.05, 1.05)
plt
.axis
('off')
plt
.show
()
import matplotlib
.pyplot
as plt
import networkx
as nx
G
= nx
.Graph
()
G
.add_edge
('a', 'b', weight
=0.6)
G
.add_edge
('a', 'c', weight
=0.2)
G
.add_edge
('c', 'd', weight
=0.1)
G
.add_edge
('c', 'e', weight
=0.7)
G
.add_edge
('c', 'f', weight
=0.9)
G
.add_edge
('a', 'd', weight
=0.3)
elarge
= [(u
, v
) for (u
, v
, d
) in G
.edges
(data
=True) if d
['weight'] > 0.5]
esmall
= [(u
, v
) for (u
, v
, d
) in G
.edges
(data
=True) if d
['weight'] <= 0.5]
pos
= nx
.spring_layout
(G
)
nx
.draw_networkx_nodes
(G
, pos
, node_size
=700)
nx
.draw_networkx_edges
(G
, pos
, edgelist
=elarge
,width
=6)
nx
.draw_networkx_edges
(G
, pos
, edgelist
=esmall
,width
=6, alpha
=0.5, edge_color
='b', style
='dashed')
nx
.draw_networkx_labels
(G
, pos
, font_size
=20, font_family
='sans-serif')
plt
.axis
('off')
plt
.show
()
import matplotlib
as mpl
import matplotlib
.pyplot
as plt
import networkx
as nx
G
= nx
.generators
.directed
.random_k_out_graph
(10, 3, 0.5)
pos
= nx
.layout
.spring_layout
(G
)
node_sizes
= [3 + 10 * i
for i
in range(len(G
))]
M
= G
.number_of_edges
()
edge_colors
= range(2, M
+ 2)
edge_alphas
= [(5 + i
) / (M
+ 4) for i
in range(M
)]
nodes
= nx
.draw_networkx_nodes
(G
, pos
, node_size
=node_sizes
, node_color
='blue')
edges
= nx
.draw_networkx_edges
(G
, pos
, node_size
=node_sizes
, arrowstyle
='->',
arrowsize
=10, edge_color
=edge_colors
,
edge_cmap
=plt
.cm
.Blues
, width
=2)
for i
in range(M
):
edges
[i
].set_alpha
(edge_alphas
[i
])
pc
= mpl
.collections
.PatchCollection
(edges
, cmap
=plt
.cm
.Blues
)
pc
.set_array
(edge_colors
)
plt
.colorbar
(pc
)
ax
= plt
.gca
()
ax
.set_axis_off
()
plt
.show
()
import matplotlib
.pyplot
as plt
import networkx
as nx
G
= nx
.cubical_graph
()
pos
= nx
.spring_layout
(G
)
nx
.draw_networkx_nodes
(G
, pos
,
nodelist
=[0, 1, 2, 3],
node_color
='r',
node_size
=500,
alpha
=0.8)
nx
.draw_networkx_nodes
(G
, pos
,
nodelist
=[4, 5, 6, 7],
node_color
='b',
node_size
=500,
alpha
=0.8)
nx
.draw_networkx_edges
(G
, pos
, width
=1.0, alpha
=0.5)
nx
.draw_networkx_edges
(G
, pos
,
edgelist
=[(0, 1), (1, 2), (2, 3), (3, 0)],
width
=8, alpha
=0.5, edge_color
='r')
nx
.draw_networkx_edges
(G
, pos
,
edgelist
=[(4, 5), (5, 6), (6, 7), (7, 4)],
width
=8, alpha
=0.5, edge_color
='b')
labels
= {}
labels
[0] = r
'$a$'
labels
[1] = r
'$b$'
labels
[2] = r
'$c$'
labels
[3] = r
'$d$'
labels
[4] = r
'$\alpha$'
labels
[5] = r
'$\beta$'
labels
[6] = r
'$\gamma$'
labels
[7] = r
'$\delta$'
nx
.draw_networkx_labels
(G
, pos
, labels
, font_size
=16)
plt
.axis
('off')
plt
.show
()
import math
import matplotlib
.pyplot
as plt
import networkx
as nx
try:
import pygraphviz
from networkx
.drawing
.nx_agraph
import graphviz_layout
layout
= graphviz_layout
except ImportError
:
try:
import pydot
from networkx
.drawing
.nx_pydot
import graphviz_layout
layout
= graphviz_layout
except ImportError
:
print("PyGraphviz and pydot not found;\n"
"drawing with spring layout;\n"
"will be slow.")
layout
= nx
.spring_layout
n
= 150
p_giant
= 1.0 / (n
- 1)
p_conn
= math
.log
(n
) / float(n
)
pvals
= [0.003, 0.006, 0.008, 0.015]
region
= 220
plt
.subplots_adjust
(left
=0, right
=1, bottom
=0, top
=0.95, wspace
=0.01, hspace
=0.01)
for p
in pvals
:
G
= nx
.binomial_graph
(n
, p
)
pos
= layout
(G
)
region
+= 1
plt
.subplot
(region
)
plt
.title
("p = %6.3f" % (p
))
nx
.draw
(G
, pos
,
with_labels
=False,
node_size
=10
)
Gcc
= sorted(nx
.connected_components
(G
), key
=len, reverse
=True)
G0
= G
.subgraph
(Gcc
[0])
nx
.draw_networkx_edges
(G0
, pos
,
with_labels
=False,
edge_color
='r',
width
=6.0
)
for Gi
in Gcc
[1:]:
if len(Gi
) > 1:
nx
.draw_networkx_edges
(G
.subgraph
(Gi
), pos
,
with_labels
=False,
edge_color
='r',
alpha
=0.3,
width
=5.0
)
plt
.show
()
import random
try:
import pygraphviz
from networkx
.drawing
.nx_agraph
import graphviz_layout
except ImportError
:
try:
import pydot
from networkx
.drawing
.nx_pydot
import graphviz_layout
except ImportError
:
raise ImportError
("This example needs Graphviz and either "
"PyGraphviz or pydot.")
import matplotlib
.pyplot
as plt
import networkx
as nx
from networkx
.algorithms
.isomorphism
.isomorph
import graph_could_be_isomorphic
as isomorphic
from networkx
.generators
.atlas
import graph_atlas_g
def atlas6():
""" Return the atlas of all connected graphs of 6 nodes or less.
Attempt to check for isomorphisms and remove.
"""
Atlas
= graph_atlas_g
()[0:208]
U
= nx
.Graph
()
for G
in Atlas
:
zerodegree
= [n
for n
in G
if G
.degree
(n
) == 0]
for n
in zerodegree
:
G
.remove_node
(n
)
U
= nx
.disjoint_union
(U
, G
)
C
= (U
.subgraph
(c
) for c
in nx
.connected_components
(U
))
UU
= nx
.Graph
()
nlist
= []
for G
in C
:
if not iso
(G
, nlist
):
nlist
.append
(G
)
UU
= nx
.disjoint_union
(UU
, G
)
return UU
def iso(G1
, glist
):
"""Quick and dirty nonisomorphism checker used to check isomorphisms."""
for G2
in glist
:
if isomorphic
(G1
, G2
):
return True
return False
if __name__
== '__main__':
G
= atlas6
()
print("graph has %d nodes with %d edges"
% (nx
.number_of_nodes
(G
), nx
.number_of_edges
(G
)))
print(nx
.number_connected_components
(G
), "connected components")
plt
.figure
(1, figsize
=(8, 8))
pos
= graphviz_layout
(G
, prog
="neato")
C
= (G
.subgraph
(c
) for c
in nx
.connected_components
(G
))
for g
in C
:
c
= [random
.random
()] * nx
.number_of_nodes
(g
)
nx
.draw
(g
,
pos
,
node_size
=40,
node_color
=c
,
vmin
=0.0,
vmax
=1.0,
with_labels
=False
)
plt
.show
()
graph has 779 nodes with 1073 edges
137 connected components
3. 图标Graph
空手道俱乐部Karate ClubER随机图Erdos Renyi度序列Degree Sequence足球football
import matplotlib
.pyplot
as plt
import networkx
as nx
G
= nx
.karate_club_graph
()
print("Node Degree")
for v
in G
:
print('%s %s' % (v
, G
.degree
(v
)))
nx
.draw_circular
(G
, with_labels
=True)
plt
.show
()
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
import matplotlib
.pyplot
as plt
from networkx
import nx
n
= 10
m
= 20
G
= nx
.gnm_random_graph
(n
, m
)
print("node degree clustering")
for v
in nx
.nodes
(G
):
print('%s %d %f' % (v
, nx
.degree
(G
, v
), nx
.clustering
(G
, v
)))
for line
in nx
.generate_adjlist
(G
):
print(line
)
nx
.draw
(G
)
plt
.show
()
node degree clustering
0 2 1.000000
1 2 0.000000
2 3 0.333333
3 5 0.500000
4 5 0.500000
5 3 0.333333
6 4 0.500000
7 5 0.400000
8 5 0.300000
9 6 0.466667
0 9 8
1 7 6
2 4 5 8
3 7 4 9 5 6
4 6 9 7
5 8
6 9
7 9 8
8 9
9
import matplotlib
.pyplot
as plt
from networkx
import nx
z
= [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
print(nx
.is_graphical
(z
))
print("Configuration model")
G
= nx
.configuration_model
(z
)
degree_sequence
= [d
for n
, d
in G
.degree
()]
print("Degree sequence %s" % degree_sequence
)
print("Degree histogram")
hist
= {}
for d
in degree_sequence
:
if d
in hist
:
hist
[d
] += 1
else:
hist
[d
] = 1
print("degree #nodes")
for d
in hist
:
print('%d %d' % (d
, hist
[d
]))
nx
.draw
(G
)
plt
.show
()
True
Configuration model
Degree sequence [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
Degree histogram
degree #nodes
5 1
3 4
2 3
1 3
try:
import urllib
.request
as urllib
except ImportError
:
import urllib
import io
import zipfile
import matplotlib
.pyplot
as plt
import networkx
as nx
url
= "http://www-personal.umich.edu/~mejn/netdata/football.zip"
sock
= urllib
.urlopen
(url
)
s
= io
.BytesIO
(sock
.read
())
sock
.close
()
zf
= zipfile
.ZipFile
(s
)
txt
= zf
.read
('football.txt').decode
()
gml
= zf
.read
('football.gml').decode
()
gml
= gml
.split
('\n')[1:]
G
= nx
.parse_gml
(gml
)
options
= {
'node_color': 'black',
'node_size': 50,
'line_color': 'grey',
'linewidths': 0,
'width': 0.1,
}
nx
.draw
(G
, **options
)
plt
.show
()