Networkx
1.介绍
“用于复杂网络高生产力软件”的分析模块
- 可以表示各种网络(有向、无向、多图)的数据结构
- 极高的灵活性:节点可以是python中任意对象,边可以包含任意数据
- 图形算法的宝库
- 多平台,易于使用
2.安装
pip install networkx
3.无向图
import networkx as nx
g = nx.Graph()
# 添加结点
for i in range(1,6):
g.add_node(i)
print(g.nodes()) # 输出结点
[1, 2, 3, 4, 5]
# 添加边
g.add_edges_from([(1,2),(1,4),(2,3),(2,4),(3,4),(4,5)])
print(g.edges()) # 输出边
print(g.degree(4)) # 输出结点的度
print(list(g.neighbors(4))) #输出邻居结点
[(1, 2), (1, 4), (2, 3), (2, 4), (3, 4), (4, 5)]
4
[1, 2, 3, 5]
# 字典
g2 = nx.Graph()
# 可以在节点处添加字典信息
g2.add_node(1, time='10am', location='school')
print(g2.nodes[1])
print(g2.nodes[1]['location'])
{'time': '10am', 'location': 'school'}
school
## 也可以在边上添加字典信息,如边的权重等
g2.add_node(2)
g2.add_edge(1,2, weight = 4.0)
print(g2[1][2])
# 更改权重
g2[1][2]['weight'] = 5.0
print(g2[1][2]['weight'])
{'weight': 4.0}
5.0
# 结点、边的迭代
g2.add_edge(1, 3, weight=3.7)
# 迭代输出结点和结点的度
for node in g2.nodes():
print(node, g2.degree(node))
# 输出两节点及两节点之间的权重
for n1, n2, attr in g2.edges(data=True):
print(n1, n2, attr['weight'])
1 2
2 1
3 1
1 2 5.0
1 3 3.7
3. 有向图
dg = nx.DiGraph()
# 添加带权有向边
dg.add_weighted_edges_from([(1, 4, 0.5), (3, 1, 0.75),(1, 2, 0.4)])
# 出度,输出出度之和
print(dg.out_degree(1, weight='weight'))
# 入度,输出入度之和
print(dg.in_degree(1, weight='weight'))
# 后继结点
print(list(dg.successors(1)))
# 前驱结点
print(list(dg.predecessors(1)))
0.9
0.75
[4, 2]
[3]
有些算法只适用于无向图,而对无向图没有很多好的定义。
如果需要将有向图视为没有测量值的无向图,则可以使用Graph.to_undirected()来转换。
4.图操作
subgraph(G, nbunch)
# 生成n个结点(nbunch)的子图union(G1, G2)
# 图的并集,G1,G2必须不相交cartesian_product(G1, G2)
# 返回笛卡尔积图compose(G1, G2)
# 组合图来识别两者的公共结点complement(G)
# 图的补图creat_empty_copy(G)
# 返回同一个图类的空副本convert_to_undirected(G)
# 返回图G的无向图convert_to_directed(G)
# 返回图G的有向图
5.图生成器
#(1)著名小图
petersen = nx.petersen_graph() #彼得森图
tutte = nx.tutte_graph()
maze = nx.sedgewick_maze_graph()
tet = nx.tetrahedral_graph()
#(2)经典图
K_5 = nx.complete_graph(5)
K_3_5 = nx.complete_bipartite_graph(3, 5)
barbell = nx.barbell_graph(10, 10)
lollipop = nx.lollipop_graph(10, 20)
#(3)随机图
er = nx.erdos_renyi_graph(100, 0.15)
ws = nx.watts_strogatz_graph(30, 3, 0.1)
ba = nx.barabasi_albert_graph(100, 5)
red = nx.random_lobster(10, 0.9, 0.9)
nx.draw(K_3_5)
print(K_3_5.nodes())
[0, 1, 2, 3, 4, 5, 6, 7]
5.输入输出
参考链接:https://networkx.org/documentation/stable/reference/readwrite/index.html
# 输出
nx.write_gexf(K_3_5, 'k_3_5.gexf')
nx.write_edgelist(K_3_5, 'K_3_5.txt')
# 读取
k35 = nx.read_gexf('K_3_5.gexf')
nx.draw(k35)
### 6.画图
import pylab as plt
g = nx.watts_strogatz_graph(100, 8, 0.1)
nx.draw(g)
nx.draw_random(g)
nx.draw_circular(g)
nx.draw_spectral(g)