[python] NetworkX实例
NetworkX实例
代码下载地址
NetworkX 2.4版本的通用示例性示例。本教程介绍了约定和基本的图形操作。具体章节内容如下:
- 基础Basic
- 绘图Drawing
- 图标Graph
本文参考:
https://networkx.github.io/documentation/stable/auto_examples/index.html
1. 基础Basic
- 读写图 Read and write graphs
- 属性 Properties
## 读写图 Read and write graphs
# Author: Aric Hagberg (hagberg@lanl.gov)
# Copyright (C) 2004-2019 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
import sys
import matplotlib.pyplot as plt
import networkx as nx
# 生成网格
G = nx.grid_2d_graph(5, 5) # 5x5 grid
# print the adjacency list
# 打印网络
for line in nx.generate_adjlist(G):
print(line)
# write edgelist to grid.edgelist
# 写数据
#nx.write_edgelist(G, path="grid.edgelist", delimiter=":")
# read edgelist from grid.edgelist
# 读数据
#H = nx.read_edgelist(path="grid.edgelist", delimiter=":")
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)
## 属性 Properties
# Copyright (C) 2004-2019 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
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)))
# histogram of path lengths
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
## 简单路径Simple Path
import matplotlib.pyplot as plt
import networkx as nx
G = nx.path_graph(8)
nx.draw(G)
plt.show()
## 节点颜色Node Colormap
# Author: Aric Hagberg (hagberg@lanl.gov)
import matplotlib.pyplot as plt
import networkx as nx
G = nx.cycle_graph(24)
# 设置排列位置,iterations迭代次数
pos = nx.spring_layout(G, iterations=200)
# node_color节点颜色
nx.draw(G, pos, node_color=range(24), node_size=800, cmap=plt.cm.Blues)
plt.show()
## 边的颜色 Edge Colormap
# Author: Aric Hagberg (hagberg@lanl.gov)
import matplotlib.pyplot as plt
import networkx as nx
G = nx.star_graph(20)
pos = nx.spring_layout(G)
colors = range(20)
# edge_color边的颜色
nx.draw(G, pos, node_color='#A0CBE2', edge_color=colors,
width=4, edge_cmap=plt.cm.Blues, with_labels=False)
plt.show()
## 带颜色的房子 House With Colors
# Author: Aric Hagberg (hagberg@lanl.gov)
import matplotlib.pyplot as plt
import networkx as nx
G = nx.house_graph()
# explicitly set positions
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()
## 环形树Circular Tree
# 管理员权限下 pip install pydot
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()
## 等级排列Degree Rank
# Author: Aric Hagberg <aric.hagberg@gmail.com>
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)
# 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 = 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()
## 谱嵌入Spectral Embedding
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()
## 四宫格Four Grids
# Author: Aric Hagberg (hagberg@lanl.gov)
# Copyright (C) 2004-2019
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
import matplotlib.pyplot as plt
import networkx as nx
# 生成四宫格点
G = nx.grid_2d_graph(4, 4) # 4x4 grid
# 点排列
pos = nx.spring_layout(G, iterations=100)
plt.subplot(221)
nx.draw(G, pos, font_size=8)
plt.subplot(222)
# node_color节点的颜色
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()
## 自我中心网络Ego Graph
# Author: Drew Conway (drew.conway@nyu.edu)
from operator import itemgetter
import matplotlib.pyplot as plt
import networkx as nx
if __name__ == '__main__':
# Create a BA model graph
n = 1000
m = 2
G = nx.generators.barabasi_albert_graph(n, m)
# find node with largest degree
node_and_degree = G.degree()
(largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[-1]
# Create ego graph of main hub
hub_ego = nx.ego_graph(G, largest_hub)
# Draw graph
pos = nx.spring_layout(hub_ego)
nx.draw(hub_ego, pos, node_color='b', node_size=50, with_labels=False)
# Draw ego as large and red
nx.draw_networkx_nodes(hub_ego, pos, nodelist=[largest_hub], node_size=300, node_color='r')
plt.show()
## 度直方图Degree histogram
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) # degree sequence
# print "Degree sequence", degree_sequence
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)
# draw graph in inset
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()
## 随机几何图形Random Geometric Graph
import matplotlib.pyplot as plt
import networkx as nx
G = nx.random_geometric_graph(200, 0.125)
# position is stored as node attribute data for random_geometric_graph
pos = nx.get_node_attributes(G, 'pos')
# find node near center (0.5,0.5)
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
# color by path length from node near center
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()
## 加权图Weighted Graph
# Author: Aric Hagberg (hagberg@lanl.gov)
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)
# 长边 权重大于0.5
elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 0.5]
# 短边 权重小于0.5
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] <= 0.5]
# 设置位置
pos = nx.spring_layout(G) # positions for all nodes
# nodes
# 画节点
nx.draw_networkx_nodes(G, pos, node_size=700)
# edges
# 画边
nx.draw_networkx_edges(G, pos, edgelist=elarge,width=6)
# style边的样式
nx.draw_networkx_edges(G, pos, edgelist=esmall,width=6, alpha=0.5, edge_color='b', style='dashed')
# labels
# 画标签
nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif')
plt.axis('off')
plt.show()
## 有向图Directed Graph
# Author: Rodrigo Dorantes-Gilardi (rodgdor@gmail.com)
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)
# set alpha value for each edge
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()
## 标签和颜色Labels And Colors
# Author: Aric Hagberg (hagberg@lanl.gov)
import matplotlib.pyplot as plt
import networkx as nx
# 生成立体图
G = nx.cubical_graph()
# 确定位置
pos = nx.spring_layout(G) # positions for all nodes
# nodes
# 画节点
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)
# edges
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')
# some math labels
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()
## 最大连通分支Giant Component
# Copyright (C) 2006-2019
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
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 # 150 nodes
# p value at which giant component (of size log(n) nodes) is expected
p_giant = 1.0 / (n - 1)
# p value at which graph is expected to become completely connected
p_conn = math.log(n) / float(n)
# the following range of p values should be close to the threshold
pvals = [0.003, 0.006, 0.008, 0.015]
region = 220 # for pylab 2x2 subplot layout
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
)
# identify largest connected component
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
)
# show other connected components
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()
## 地图集Atlas
# Author: Aric Hagberg (hagberg@lanl.gov)
# Copyright (C) 2004-2019 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
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] # 208
# remove isolated nodes, only connected graphs are left
U = nx.Graph() # graph for union of all graphs in atlas
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)
# iterator of graphs of all connected components
C = (U.subgraph(c) for c in nx.connected_components(U))
UU = nx.Graph()
# do quick isomorphic-like check, not a true isomorphism checker
nlist = [] # list of nonisomorphic graphs
for G in C:
# check against all nonisomorphic graphs so far
if not iso(G, nlist):
nlist.append(G)
UU = nx.disjoint_union(UU, G) # union the nonisomorphic graphs
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))
# layout graphs with positions using graphviz neato
pos = graphviz_layout(G, prog="neato")
# color nodes the same in each connected subgraph
C = (G.subgraph(c) for c in nx.connected_components(G))
for g in C:
c = [random.random()] * nx.number_of_nodes(g) # random color...
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 Club
- ER随机图Erdos Renyi
- 度序列Degree Sequence
- 足球football
## 空手道俱乐部Karate Club
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
## ER随机图Erdos Renyi
# Author: Aric Hagberg (hagberg@lanl.gov)
# Copyright (C) 2004-2019 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
import matplotlib.pyplot as plt
from networkx import nx
n = 10 # 10 nodes
m = 20 # 20 edges
G = nx.gnm_random_graph(n, m)
# some properties
print("node degree clustering")
for v in nx.nodes(G):
print('%s %d %f' % (v, nx.degree(G, v), nx.clustering(G, v)))
# print the adjacency list
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
## 度序列Degree Sequence
# Author: Aric Hagberg (hagberg@lanl.gov)
# Date: 2004-11-03 08:11:09 -0700 (Wed, 03 Nov 2004)
# Revision: 503
# Copyright (C) 2004-2019 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
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) # configuration model
degree_sequence = [d for n, d in G.degree()] # degree sequence
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
# 足球football
# Author: Aric Hagberg (hagberg@lanl.gov)
# Copyright (C) 2007-2019 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
try: # Python 3.x
import urllib.request as urllib
except ImportError: # Python 2.x
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) # 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(txt)
# print degree for each team - number of games
#for n, d in G.degree():
# print('%s %d' % (n, d))
options = {
'node_color': 'black',
'node_size': 50,
'line_color': 'grey',
'linewidths': 0,
'width': 0.1,
}
nx.draw(G, **options)
plt.show()
[python] NetworkX实例的更多相关文章
- python基础——实例属性和类属性
python基础——实例属性和类属性 由于Python是动态语言,根据类创建的实例可以任意绑定属性. 给实例绑定属性的方法是通过实例变量,或者通过self变量: class Student(objec ...
- python 发送邮件实例
留言板回复作者邮件提醒 -----------2016-5-11 15:03:58-- source:python发送邮件实例
- python Cmd实例之网络爬虫应用
python Cmd实例之网络爬虫应用 标签(空格分隔): python Cmd 爬虫 废话少说,直接上代码 # encoding=utf-8 import os import multiproces ...
- Python爬虫实例:爬取B站《工作细胞》短评——异步加载信息的爬取
很多网页的信息都是通过异步加载的,本文就举例讨论下此类网页的抓取. <工作细胞>最近比较火,bilibili 上目前的短评已经有17000多条. 先看分析下页面 右边 li 标签中的就是短 ...
- Python爬虫实例:爬取猫眼电影——破解字体反爬
字体反爬 字体反爬也就是自定义字体反爬,通过调用自定义的字体文件来渲染网页中的文字,而网页中的文字不再是文字,而是相应的字体编码,通过复制或者简单的采集是无法采集到编码后的文字内容的. 现在貌似不少网 ...
- Python爬虫实例:爬取豆瓣Top250
入门第一个爬虫一般都是爬这个,实在是太简单.用了 requests 和 bs4 库. 1.检查网页元素,提取所需要的信息并保存.这个用 bs4 就可以,前面的文章中已经有详细的用法阐述. 2.找到下一 ...
- python 创建实例--待完善
今天好好琢磨一下 python 创建实例的先后顺序 一. 就定义一个普通类 Util (默认)继承自 object,覆写 new ,init 方法 class Util(object): def __ ...
- pcapng文件的python解析实例以及抓包补遗
为了弥补pcap文件的缺陷,让抓包文件可以容纳更多的信息,pcapng格式应运而生.关于它的介绍详见<PCAP Next Generation Dump File Format> 当前的w ...
- 生产消费者模式与python+redis实例运用(中级篇)
上一篇文章介绍了生产消费者模式与python+redis实例运用(基础篇),但是依旧遗留了一个问题,就是如果消费者消费的速度跟不上生产者,依旧会浪费我们大量的时间去等待,这时候我们就可以考虑使用多进程 ...
随机推荐
- MinGW配置C语言编译器gcc和g++
首先,在 https://sourceforge.net/projects/mingw/files/latest/download 下载安装MinGW,如下图所示: 点Installation-> ...
- 【JavaWeb】学习笔记——Tomcat集成
简介 Tomcat是基于Java的一个开放源代码.运行servlet和JSP Web应用的Web应用软件容器,又称servlet容器 安装 官方网站:https://tomcat.apache.org ...
- JAVA系列之JVM内存调优
一.前提 JVM性能调优牵扯到各方面的取舍与平衡,往往是牵一发而动全身,需要全盘考虑各方面的影响.在优化时候,切勿凭感觉或经验主义进行调整,而是需要通过系统运行的客观数据指标,不断找到最优解.同时,在 ...
- KNN算法之集美大学
在本篇文章中,我即将以在集美大学收集到的一些数据集为基础,使用KNN算法进行一系列的操作 一.KNN算法 首先,什么是KNN算法呢,这得用到老祖宗说的一句话"近朱者赤近墨者黑", ...
- 安装zabbix-agent2之ansible-playbook
zabbix被监控端安装zabbix-agent2之ansible-playbook --- - name: install agent hosts: all vars: server_host: & ...
- 【题解】CF1215C Swap Letters
题面传送门 解决思路 首先容易得知,两个字符串中 \(b\)(或 \(a\)) 的个数为偶数时,一定有解.为奇数则一定无解. 其次考虑怎么交换.对照样例三: in: 8 babbaabb ababab ...
- perl哈希嵌套和引用的使用
数组,哈希嵌套 数组,哈希的引用 1.哈希的嵌套和引用 %hash = ( 'group1', {'fruit', 'banana', 'drink', 'orange juice', 'vegeta ...
- requests模块/openpyxl模块/简单爬虫实战
内容概要 第三方模块的下载及使用 网络爬虫及requests模块 网络爬虫实战爬取二手房信息 自动化办公领域模块openpyxl 练习题及答案 第三方模块的下载 第三方模块就类似与别人写好的模块,我们 ...
- Linux配置篇 - Vmware网络配置
网络配置 VM 网络详解 vmware提供了三种网络工作模式,Bridged(桥接模式).NAT(网络地址转换模式).Host-Only(仅主机模式): vmware网络配置步骤:编辑 -> 虚 ...
- win 10 玩红警/黑边,不能全屏,闪退
win 10玩红警黑边问题 1.下载ddraw.dll,放在游戏目录 下载链接:ddraw.dll 如果提示 选择保留就行了 2.Win 键+S键,搜索注册表,打开这个 进去按这个路径 计算机\ ...