networkx画有向图和无向图

 代码和结果如下所示:

from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
import networkx as nx

myfont = FontProperties(fname=r"C:\Windows\Fonts\STXINGKA.TTF",size=20)  #fname指定字体文件  选简体显示中文

# 定义图的节点和边
nodes = ['0', '1', '2', '3', '4', '5', 'a', 'b', 'c']
edges = [('0', '0', 1), ('0', '1', 1), ('0', '5', 1), ('0', '5', 2), ('1', '2', 3), ('1', '4', 5), ('2', '1', 7),
         ('2', '4', 6), ('a', 'b', 0.5), ('b', 'c', 0.5), ('c', 'a', 0.5)]

plt.subplots(1, 2, figsize=(10, 3))

# 定义一个无向图和有向图
G1 = nx.Graph()
G1.add_nodes_from(nodes)
G1.add_weighted_edges_from(edges)

G2 = nx.DiGraph()
G2.add_nodes_from(nodes)
G2.add_weighted_edges_from(edges)

pos1 = nx.circular_layout(G1) # 圆形布局 起到美化作用
pos2 = nx.circular_layout(G2)

# 画出无向图和有向图
plt.subplot(121)
nx.draw(G1, pos1, with_labels=True, font_weight='bold')
plt.title('无向图', fontproperties=myfont)
# plt.axis('on')
plt.xticks([])
plt.yticks([])

plt.subplot(122)
nx.draw(G2, pos2, with_labels=True, font_weight='bold')
plt.title('有向图', fontproperties=myfont)
# plt.axis('on')
plt.xticks([])
plt.yticks([])

plt.show()

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值