NetworkX实例

代码下载地址
NetworkX 2.4版本的通用示例性示例。本教程介绍了约定和基本的图形操作。具体章节内容如下:

  1. 基础Basic
  2. 绘图Drawing
  3. 图标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实例的更多相关文章

  1. python基础——实例属性和类属性

    python基础——实例属性和类属性 由于Python是动态语言,根据类创建的实例可以任意绑定属性. 给实例绑定属性的方法是通过实例变量,或者通过self变量: class Student(objec ...

  2. python 发送邮件实例

    留言板回复作者邮件提醒 -----------2016-5-11 15:03:58-- source:python发送邮件实例

  3. python Cmd实例之网络爬虫应用

    python Cmd实例之网络爬虫应用 标签(空格分隔): python Cmd 爬虫 废话少说,直接上代码 # encoding=utf-8 import os import multiproces ...

  4. Python爬虫实例:爬取B站《工作细胞》短评——异步加载信息的爬取

    很多网页的信息都是通过异步加载的,本文就举例讨论下此类网页的抓取. <工作细胞>最近比较火,bilibili 上目前的短评已经有17000多条. 先看分析下页面 右边 li 标签中的就是短 ...

  5. Python爬虫实例:爬取猫眼电影——破解字体反爬

    字体反爬 字体反爬也就是自定义字体反爬,通过调用自定义的字体文件来渲染网页中的文字,而网页中的文字不再是文字,而是相应的字体编码,通过复制或者简单的采集是无法采集到编码后的文字内容的. 现在貌似不少网 ...

  6. Python爬虫实例:爬取豆瓣Top250

    入门第一个爬虫一般都是爬这个,实在是太简单.用了 requests 和 bs4 库. 1.检查网页元素,提取所需要的信息并保存.这个用 bs4 就可以,前面的文章中已经有详细的用法阐述. 2.找到下一 ...

  7. python 创建实例--待完善

    今天好好琢磨一下 python 创建实例的先后顺序 一. 就定义一个普通类 Util (默认)继承自 object,覆写 new ,init 方法 class Util(object): def __ ...

  8. pcapng文件的python解析实例以及抓包补遗

    为了弥补pcap文件的缺陷,让抓包文件可以容纳更多的信息,pcapng格式应运而生.关于它的介绍详见<PCAP Next Generation Dump File Format> 当前的w ...

  9. 生产消费者模式与python+redis实例运用(中级篇)

    上一篇文章介绍了生产消费者模式与python+redis实例运用(基础篇),但是依旧遗留了一个问题,就是如果消费者消费的速度跟不上生产者,依旧会浪费我们大量的时间去等待,这时候我们就可以考虑使用多进程 ...

随机推荐

  1. GitHub 供应链安全已支持 Dart 开发者生态

    通过 Dart 和 GitHub 团队的共同努力,自 10 月 7 日起,GitHub 的 Advisory Database (安全咨询数据库).Dependency Graph (依赖项关系图) ...

  2. 运行eeui项目不出现 WiFI真机同步 IP地址

    从git上 clone项目之后,安装依赖  npm install eeui环境配置    npm install eeui-cli -g 问题:npm run dev  后项目一直不出现 WiFI真 ...

  3. 快速上手Spring项目

    通过maven依赖管理导入所需Jar包 注 : spring 需要导入commons-logging进行日志记录 . 我们利用maven , 他会自动下载对应的依赖项 . <dependency ...

  4. ssh端口映射 解决服务器使用tensorboard的问题

    有时会在服务器上使用tensorboard,然而本地无法直接访问tensorboard结果网页.这时候使用端口映射即可.比如tensorboard上占用的是 6006 端口,也就是说结果在服务器的 l ...

  5. win10设置或更改硬盘图标

    1.首先要找到".ico"的图标素材,存放在要更改图标的硬盘根目录,可命名为a.ico.图片素材大家可以去一些素材网找找,一般可以找到很多. 2.在该硬盘分区空白处鼠标右键新建一个 ...

  6. DevOps | 如何快速提升团队软件开发成熟度,快速提升研发效能?

    今天一个小伙伴问我,如何「快速提升」一个团队的软件开发成熟度?我犯难了.我个人理解一个团队的软件开发成熟度涉及的东西很多,但最简单最直接的方法就是发钱涨工资,可是估计很多公司不愿意,那就只有扣了. 快 ...

  7. 消息队列之RabbitMQ介绍与运用

    RabbitMQ 说明 本章,我们主要从RabbitMQ简介.RabbitMQ安装.RabbitMQ常用命令.RabbitMQ架构模式.RabbitMQ使用.Quick.RabbitMQPlus的使用 ...

  8. Kubeadm部署Kubernetes

    Kubeadm部署Kubernetes 1.环境准备 主机名 IP 说明 宿主机系统 k8s-master 10.0.0.101 Kubernetes集群的master节点 Ubuntu2004 k8 ...

  9. C# 9.0 添加和增强的功能【基础篇】

    一.记录(record) C# 9.0 引入了记录类型. 可使用 record 关键字定义一个引用类型,以最简的方式创建不可变类型.这种类型是线程安全的,不需要进行线程同步,非常适合并行计算的数据共享 ...

  10. 扫雷(哈希+bfs)

    扫雷 题目描述: 小明最近迷上了一款名为<扫雷>的游戏. 其中有一个关卡的任务如下: 在一个二维平面上放置着 n 个炸雷,第 i 个炸雷 (x\(_i\),y\(_i\),r\(_i\)) ...