Python uses networks to read txt files and draw a directed graph

class demo():
    def __init__(self):
        self.file_path='test.txt'#图文件    
    def draw_graph(self):

        G2 = nx.DiGraph()  # 创建:空的 有向图
        f = open(self.file_path)
        lines = [l.split() for l in f.readlines() if l.strip()]
        # print(lines)
        for i in lines:
            G2.add_edge(i[0],i[1],weight=i[2])

        pos = nx.random_layout(G2)  # 用 FR算法排列节点
        nx.draw(G2, pos, with_labels=True, alpha=0.5)
        labels = nx.get_edge_attributes(G2, 'weight')
        nx.draw_networkx_edge_labels(G2, pos, edge_labels=labels)
        plt.show()

The format of the txt file is as follows: start and end point weights are separated by spaces. As for the library, let’s guide it by ourselves

 

Guess you like

Origin blog.csdn.net/weixin_63676550/article/details/130183623