[python] NetworkX实例
文章目录
- NetworkX实例
- 1. 基础Basic
- 2. 绘图Drawing
- 3. 图标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
## 读写图 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 nxG = 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] += 1else:dist[p] = 1print('')
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.86length #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 Pathimport matplotlib.pyplot as plt
import networkx as nxG = 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 nxG = 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 nxG = 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 nxG = 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 pydotimport matplotlib.pyplot as plt
import networkx as nx
import pydot
from networkx.drawing.nx_pydot import graphviz_layoutG = 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 pltG = 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 Embeddingimport matplotlib.pyplot as plt
import networkx as nxoptions = {'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 itemgetterimport matplotlib.pyplot as plt
import networkx as nxif __name__ == '__main__':# Create a BA model graphn = 1000m = 2G = nx.generators.barabasi_albert_graph(n, m)# find node with largest degreenode_and_degree = G.degree()(largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[-1]# Create ego graph of main hubhub_ego = nx.ego_graph(G, largest_hub)# Draw graphpos = nx.spring_layout(hub_ego)nx.draw(hub_ego, pos, node_color='b', node_size=50, with_labels=False)# Draw ego as large and rednx.draw_networkx_nodes(hub_ego, pos, nodelist=[largest_hub], node_size=300, node_color='r')plt.show()
## 度直方图Degree histogramimport collections
import matplotlib.pyplot as plt
import networkx as nxG = 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 Graphimport matplotlib.pyplot as plt
import networkx as nxG = 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)**2if d < dmin:ncenter = ndmin = 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 nxG = 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 nxG = 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 mathimport matplotlib.pyplot as plt
import networkx as nxtry:import pygraphvizfrom networkx.drawing.nx_agraph import graphviz_layoutlayout = graphviz_layout
except ImportError:try:import pydotfrom networkx.drawing.nx_pydot import graphviz_layoutlayout = graphviz_layoutexcept ImportError:print("PyGraphviz and pydot not found;\n""drawing with spring layout;\n""will be slow.")layout = nx.spring_layoutn = 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 += 1plt.subplot(region)plt.title("p = %6.3f" % (p))nx.draw(G, pos,with_labels=False,node_size=10)# identify largest connected componentGcc = 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 componentsfor 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 randomtry:import pygraphvizfrom networkx.drawing.nx_agraph import graphviz_layout
except ImportError:try:import pydotfrom networkx.drawing.nx_pydot import graphviz_layoutexcept ImportError:raise ImportError("This example needs Graphviz and either ""PyGraphviz or pydot.")import matplotlib.pyplot as pltimport networkx as nx
from networkx.algorithms.isomorphism.isomorph import graph_could_be_isomorphic as isomorphic
from networkx.generators.atlas import graph_atlas_gdef 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 leftU = nx.Graph() # graph for union of all graphs in atlasfor 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 componentsC = (U.subgraph(c) for c in nx.connected_components(U))UU = nx.Graph()# do quick isomorphic-like check, not a true isomorphism checkernlist = [] # list of nonisomorphic graphsfor G in C:# check against all nonisomorphic graphs so farif not iso(G, nlist):nlist.append(G)UU = nx.disjoint_union(UU, G) # union the nonisomorphic graphsreturn UUdef iso(G1, glist):"""Quick and dirty nonisomorphism checker used to check isomorphisms."""for G2 in glist:if isomorphic(G1, G2):return Truereturn Falseif __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 neatopos = graphviz_layout(G, prog="neato")# color nodes the same in each connected subgraphC = (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 Clubimport 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 nxn = 10 # 10 nodes
m = 20 # 20 edgesG = 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 nxz = [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] += 1else: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.ximport urllib.request as urllib
except ImportError: # Python 2.ximport urllib
import io
import zipfileimport matplotlib.pyplot as plt
import networkx as nxurl = "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 networkx绘制图
python networkx绘制图 1. 效果图 2. 安装 3. 源码 参考 这篇博客将介绍如何使用python,networkx绘制图. 1. 效果图 可调整点的大小,点是否有label,点的颜 ...
- 用python实现视频换脸_超简单使用Python换脸实例
换脸! 这段时间,deepfakes搞得火热,比方说把<射雕英雄传>里的朱茵换成了杨幂,看下面的图!毫无违和感! 其实早在之前,基于AI换脸的技术就得到了应用,比方说<速度与激情7& ...
- python简单编程例子-python简单实例训练(21~30)
注意:我用的python2.7,大家如果用Python3.0以上的版本,请记得在print()函数哦!如果因为版本问题评论的,不做回复哦!! 21.题目:将一个正整数分解质因数.例如:输入90,打印出 ...
- python脚本实例手机端-python链接手机用Python实现命令行闹钟脚本实例
前言: 这篇文章给大家介绍了怎样用python创建一个简单的报警,它可以运行在命令行终端,它需要分钟做为命令行参数,在这个分钟后会打印"wake-up"消息,并响铃报警,你可以用0 ...
- python爬虫实例-记录一次简单的Python爬虫实例
本次的这篇文章主要是和大家分享了一篇关于记录一次简单的Python爬虫实例 ,有需要的小伙伴可以看一下. 主要流程分为: 爬取.整理.存储 1.其中用到几个包,包括 requests 用于向网站发送请 ...
- python经典案例-Python经典实例
本书是Python经典实例解析,采用基于实例的方法编写,每个实例都会解决具体的问题和难题.主要内容有:数字.字符串和元组,语句与语法,函数定义,列表.集.字典,用户输入和输出等内置数据结构,类和对象, ...
- python程序格式框架的描述_python 程序语言设计(嵩天)-学习笔记(第二章python 程序实例解析)...
第 2 章 python 程序实例解析 学习目标: 掌握解决计算问题的一般方法. 掌握python语言的基本语法,包括缩进.变量.命名等. 掌握python语言绘制图形的一般方法. 了解python标 ...
- 涵盖 14 大主题!最完整的 Python 学习实例集来了!
机器学习.深度学习最简单的入门方式就是基于 Python 开始编程实战.最近闲逛 GitHub,发现了一个非常不错的 Python 学习实例集,完全是基于 Python 来实现包括 ML.DL 等领域 ...
- python组成不重复的三位数是多少_超星Python 练习实例1-组成多少个互不相同且无重复的三位数字...
数字:1.2.3.4,能组成多少个互不相同且无重复数字的三位数?各是多少? 程序分析:可填在百位.十位.个位的数字都是1.2.3.4.组成所有的排列后再去 掉不满足条件的排列. 程序源代码: #!/u ...
最新文章
- HTML的标签描述16
- php中可以实现多态的是继承,PHP设计模式通过继承实现多态
- Boost:bind绑定和或||的测试程序
- GreenPlum的并行查询优化策略
- Openshift:使用Java 8在Wildfly 8.2.0上构建Spring Boot应用程序
- VS2017社区版30天到期无法使用的激活方法
- 支付宝接口调试经验总结
- 评中级工程师职称计算机,评中级工程师职称及注意事项
- 学习外挂 -------- 成长过程(经典推荐)
- wiki(维基)系统
- 欧姆字符的编码c语言,欧姆符号怎么打
- 在线重建索引 oracle,ORACLE重建索引详解
- python xlrd pandas_Python:Pandas pd.read_excel提供ImportError:为Excel supp安装xlrd = 0.9.0
- [QT_015]Qt学习之基于条目控件的自定义特性(拖拽+右键菜单+样式)
- 安利个神器, Python 脚本可轻松打包为 exe
- [弱电工程] 视频监控存储空间的计算方法
- matlab积分泛函,泛函积分的数学方法概观.pdf
- cover letter and response letter
- 华为Java编码规范
- 计算机重装系统的作用,经常重装系统对电脑有影响吗?听听专家怎么说!