Networkx基本用法
1.网络的初始化
1.1 四种基本网络模型的创建
规则网络
import networkx as nx
import matplotlib.pyplot as plt
def CreateRGGraph(k,N):
RG=nx.random_graphs.random_regular_graph(k,N)
pos=nx.spectral_layout(RG) #图形样式:根据图的拉普拉斯特征向量排列节点的
plt.subplot(111)
nx.draw(RG,pos,with_labels=False,node_size=10)
plt.show()
return RG
CreateRGGraph(8,100)
<networkx.classes.graph.Graph at 0x18b95634548>
ER随机网络
import networkx as nx
import matplotlib.pyplot as plt
def CreateERGraph(N,p):
ER = nx.random_graphs.erdos_renyi_graph(N, p)
pos = nx.shell_layout(ER) #图形样式:这里是节点在同心圆上分布
plt.subplot(111)
nx.draw(ER, pos, with_labels=False, node_size=10)
plt.show()
return ER
ER=CreateERGraph(100,0.1)
WS小世界网路
import networkx as nx
import matplotlib.pyplot as plt
def CreateWSGraph(N,k,p):
WS = nx.random_graphs.watts_strogatz_graph(N, k, p)
pos = nx.circular_layout(WS) # 图形样式:这里是节点在一个圆环上均匀分布
plt.subplot(111)
nx.draw(WS, pos, with_labels=False, node_size=10)
plt.show()
return WS
WS=CreateWSGraph(100,8,0.4)
BA无标度网络
import networkx as nx
import matplotlib.pyplot as plt
def CreateBAGraph(N,m):
BA = nx.random_graphs.barabasi_albert_graph(N, m)
pos = nx.spring_layout(BA) # 图形的样式:这里是中心放射状
plt.subplot(111)
nx.draw(BA, pos, with_labels=False, node_size=10)
plt.show()
return BA
BA=CreateBAGraph(100,1)
1.2 网络图的绘制
参考链接:https://blog.csdn.net/shanshanhi/article/details/55192884
各个布局的源代码:
https://blog.csdn.net/ztf312/article/details/50834463
netwokx绘图参数
参数 | 用法 |
---|---|
node_size | 指定节点的尺寸大小 |
node_color | 指定节点的颜色 |
node_shape | 节点形状(默认为圆形,用’o’表示) |
alpha | 透明度(默认为1.0) |
width | 边的宽度(默认为1.0) |
edge_color | 边的颜色 |
style | 边的样式 |
with_labels | 节点是否带标签 |
font_size | 节点标签字体大小 |
font_color | 节点标签字体颜色 |
布局方式
- circular_layout:节点在一个圆环上均匀分布
- random_layout:节点随机分布
- shell_layout:节点在同心圆上分布
- spring_layout:用Fruchterman-Reingold算法排列节点
- spectral_layout:根据图的拉普拉斯特征向量排列节
2. 基本操作
2.1 网络的存储与读取
邻接矩阵存储
import numpy as np
import networkx as nx
def SaveGraph(G,type):
matrix=nx.to_numpy_matrix(G)
np.savetxt("%s.txt"%type,matrix,fmt="%d",delimiter=" ")
#fmt为指定保存的文件格式,delimiter表示分隔符
网络的读取
def loadGraph():
matrix=np.loadtxt("G.txt")
G=nx.Graph()
for i in range(len(matrix)):
for j in range(len(matrix)):
if matrix[i][j]==1: #针对无权图
G.add_edge(i,j)
return G
2.2 节点、边的增删改查
参考链接:https://blog.csdn.net/qq_34107425/article/details/104085551
添加节点
import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_node('a')
G.add_nodes_from(['b','c','d','e'])
nx.draw(G,with_labels=True)
plt.show()
访问节点
print("图中节点:",G.nodes())
print("节点数目:",G.number_of_nodes())
图中节点: ['a', 'b', 'c', 'd', 'e']
节点数目: 5
删除节点
G.remove_node('a')
G.remove_nodes_from(['c','d'])
nx.draw(G,with_labels=True)
plt.show()
添加边
G=nx.Graph()
G.add_nodes_from(['a','b','c','d','e'])
G.add_edge('a','b')
G.add_edges_from([('a','c'),('b','d')])
nx.draw(G,with_labels=True)
plt.show()
访问边
print("图中所有的边:",G.edges())
print("图中的边数:",G.number_of_edges())
图中所有的边: [('a', 'b'), ('a', 'c'), ('b', 'd')]
图中的边数: 3
遍历边
#有权重的边遍历
for u,v,d in G.edges(data='weight'):
print((u,v,d))
('a', 'b', None)
('a', 'c', None)
('b', 'd', None)
#无权重的边的遍历
for n, nbrs in G.adjacency():
for nbr, eattr in nbrs.items():
print('({},{})'.format(n,nbr))
(a,b)
(a,c)
(b,a)
(b,d)
(c,a)
(d,b)
3. 网络的参数
参考链接:https://blog.csdn.net/weixin_29157361/article/details/112804517
import networkx as nx
import matplotlib.pyplot as plt
def CreateERGraph(N,p):
ER = nx.random_graphs.erdos_renyi_graph(N, p)
pos = nx.shell_layout(ER)
plt.subplot(111)
nx.draw(ER, pos, with_labels=False, node_size=10)
plt.show()
return ER
ER=CreateERGraph(100,0.1)
网络度值
- nx.degree()返回值为列表,列表中存储由节点序号和度值构成的元组
degrees=nx.degree(ER)
DegreeView({0: 10, 1: 7, 2: 8, 3: 12, 4: 6, 5: 9, 6: 9, 7: 9, 8: 7, 9: 10, 10: 6, 11: 11, 12: 15, 13: 12, 14: 9, 15: 11, 16: 8, 17: 10, 18: 11, 19: 8, 20: 11, 21: 12, 22: 13, 23: 7, 24: 12, 25: 8, 26: 11, 27: 13, 28: 9, 29: 9, 30: 13, 31: 10, 32: 7, 33: 12, 34: 12, 35: 10, 36: 6, 37: 8, 38: 10, 39: 12, 40: 11, 41: 11, 42: 4, 43: 7, 44: 17, 45: 7, 46: 11, 47: 10, 48: 6, 49: 15, 50: 13, 51: 15, 52: 10, 53: 13, 54: 8, 55: 6, 56: 9, 57: 12, 58: 18, 59: 11, 60: 12, 61: 6, 62: 11, 63: 9, 64: 11, 65: 18, 66: 5, 67: 11, 68: 15, 69: 8, 70: 11, 71: 11, 72: 7, 73: 13, 74: 10, 75: 9, 76: 9, 77: 5, 78: 6, 79: 11, 80: 16, 81: 8, 82: 9, 83: 11, 84: 10, 85: 7, 86: 4, 87: 13, 88: 14, 89: 8, 90: 8, 91: 8, 92: 9, 93: 10, 94: 15, 95: 12, 96: 8, 97: 6, 98: 8, 99: 13})
- nx.degree_histogram()返回度值的列表
degree=nx.degree_histogram(ER)
[0, 0, 0, 0, 2, 2, 8, 8, 13, 12, 11, 16, 10, 8, 1, 5, 1, 1, 2]
聚集系数
- nx.clustering()以字典的形式返回各节点的聚集系数
clustering=nx.clustering(ER)
- 平均聚类系数
nx.average_clustering(ER)
0.08843764895235477
其他
- 节点度中心系数:通过节点的度表示节点在图中的重要性
degree_centrality=nx.degree_centrality(ER)
- 节点距离中心系数:通过距离来表示节点在图中的重要性
closeness_centrality=nx.closeness_centrality(ER)
- 节点介数中心系数
betweenness_centrality=nx.betweenness_centrality(ER)
- 网络直径
d=nx.diameter(ER)
- 网络平均最短路径
r=nx.average_shortest_path_length(ER)