networkx网络拓扑节点图和树,python

x33g5p2x  于2021-11-11 转载在 Python  
字(1.3k)|赞(0)|评价(0)|浏览(578)

首先需要安装networkx:

  1. pip install networkx

绘制图和树节点的拓扑图需要matplotlib,也需要安装:

  1. pip install matplotlib

一个代码例子:

  1. import networkx as nx
  2. import matplotlib.pyplot as plt
  3. def my_grap():
  4. G = nx.Graph(my_seq='first_graph')
  5. G.add_node('a', my_index='NO-1')
  6. G.add_nodes_from(['b', 'c'], my_index='NO-2/3')
  7. G.add_nodes_from(['d', 'e', 'f'])
  8. nx.add_cycle(G, ['d', 'e', 'f'])
  9. G.add_edge('c', 'd', weight=3)
  10. G.add_edges_from([('a', 'b', {'weight': 1}),
  11. ('a', 'd', {'weight': 2}),
  12. ('d', 'e', {'weight': 2}),
  13. ('d', 'f', {'weight': 2}),
  14. ('e', 'f', {'weight': 2})],
  15. my_len=3)
  16. G.nodes['e']['my_index'] = 'NO-4'
  17. print('所有节点', G.nodes(data=True))
  18. print('所有边', G.edges(data=True))
  19. print('节点数', G.number_of_nodes())
  20. # 打印所有边
  21. for u, v, w in G.edges(data='weight'):
  22. print((u, v, w))
  23. pos = nx.spring_layout(G)
  24. nx.draw(G, pos,
  25. node_color='red',
  26. node_size=300,
  27. font_size=10,
  28. font_color='blue',
  29. with_labels=True)
  30. weights = nx.get_edge_attributes(G, 'weight')
  31. nx.draw_networkx_edge_labels(G, pos, edge_labels=weights)
  32. plt.show()
  33. if __name__ == '__main__':
  34. my_grap()

绘制出来的网络节点图为:

输出的日志为:

  1. 所有节点 [('a', {'my_index': 'NO-1'}), ('b', {'my_index': 'NO-2/3'}), ('c', {'my_index': 'NO-2/3'}), ('d', {}), ('e', {'my_index': 'NO-4'}), ('f', {})]
  2. 所有边 [('a', 'b', {'my_len': 3, 'weight': 1}), ('a', 'd', {'my_len': 3, 'weight': 2}), ('c', 'd', {'weight': 3}), ('d', 'e', {'my_len': 3, 'weight': 2}), ('d', 'f', {'my_len': 3, 'weight': 2}), ('e', 'f', {'my_len': 3, 'weight': 2})]
  3. 节点数 6
  4. ('a', 'b', 1)
  5. ('a', 'd', 2)
  6. ('c', 'd', 3)
  7. ('d', 'e', 2)
  8. ('d', 'f', 2)
  9. ('e', 'f', 2)

相关文章