Python NetworkX使用2——基础绘图及遍历
文章目录
1. import package
import networkx as nx
import matplotlib.pyplot as plt
2. Traverse points and corresponding neighbors and edgs
# 创建一个带权重的无向图
G.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
# 多重遍历
for n, nbrs in MG.adjacency():
print(n, nbrs) # n是点, nbrs是n的邻居
"""
1 {2: {0: {'weight': 0.5}, 1: {'weight': 0.75}}}
2 {1: {0: {'weight': 0.5}, 1: {'weight': 0.75}}, 3: {0: {'weight': 0.5}}}
3 {2: {0: {'weight': 0.5}}}
"""
# 对于图的邻居继续遍历
for n, nbrs in MG.adjacency():
for nbr, edict in nbrs.items():
print(nbr, edict) # 对于每一个邻居输出其边的信息
"""
2 {0: {'weight': 0.5}, 1: {'weight': 0.75}}
1 {0: {'weight': 0.5}, 1: {'weight': 0.75}}
3 {0: {'weight': 0.5}}
2 {0: {'weight': 0.5}}
"""
3. Simple drawing
nx.draw(G, pos, **options)
# 3-5完全二分图
K_3_5 = nx.complete_bipartite_graph(3, 5)
nx.draw(K_3_5, with_labels = True)
# 3-5完全二分图
K_3_5 = nx.complete_bipartite_graph(3, 5)
nx.draw(K_3_5, with_labels = True)
# babell_graph
barbell = nx.barbell_graph(10, 10)
nx.draw(barbell, with_labels = True)
4. Advanced ploting
G = nx.star_graph(20)
pos = nx.spring_layout(G)
colors = range(20)
options = {
"node_color": "#A0CBE2",
"edge_color": colors,
"width": 4,
"edge_cmap": plt.cm.Blues,
"with_labels": False,
}
nx.draw(G, pos, **options)
plt.show()