【Python学习系列二十五】数据结构-有向图绘制
生活随笔
收集整理的这篇文章主要介绍了
【Python学习系列二十五】数据结构-有向图绘制
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
1、场景:从文件中读取节点、有向边,然后绘制。
2、参考代码:
# -*- coding: utf-8 -*-import networkx as nx import matplotlib.pyplot as plt#读取文件,获取节点和边 f = open("D:\\tmp\\gy_contest_link_top.txt", "r") nodelist=[] edgelist=[] while True: line = f.readline() if line: pass # do something here line=line.strip()node=line.split(';')[0]#获取图节点nodelist.append(node)in_nodes=line.split(';')[1].split('#')#获取图边,该节点是终点for ins in range( len(in_nodes) ) :if in_nodes[ins].strip() !='': in_edge=(in_nodes[ins],node)if in_edge not in edgelist:edgelist.append(in_edge)out_nodes=line.split(';')[2].split('#')#获取图边,该节点是起点 for ins in range( len(out_nodes) ) :if out_nodes[ins].strip() !='': out_edge=(node,out_nodes[ins])if out_edge not in edgelist:edgelist.append(out_edge)else: break f.close() del nodelist[0] #删除表头生成的节点 del edgelist[0] del edgelist[0] #删除表头生成的边 #print len(nodelist) #图节点 #print len(edgelist) #边数#有向图绘制 G=nx.DiGraph() G.add_nodes_from(nodelist) G.add_edges_from(edgelist) nx.draw_networkx(G, pos=None, arrows=True, with_labels=True) #plt.savefig('D:\\tmp\\it.png') plt.show()效果图:
笔者没有对节点名做简易处理,所以看起来有点乱。
总结
以上是生活随笔为你收集整理的【Python学习系列二十五】数据结构-有向图绘制的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 【Python学习系列二十四】sciki
- 下一篇: 【Python学习系列二十六】netwo