Python NetworkX使用2——基础绘图及遍历

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()

在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值