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

Posted zhangphil

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了networkx网络拓扑节点图和树,python相关的知识,希望对你有一定的参考价值。

首先需要安装networkx:

pip install networkx

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

pip install matplotlib

一个代码例子:

import networkx as nx
import matplotlib.pyplot as plt


def my_grap():
    G = nx.Graph(my_seq='first_graph')
    G.add_node('a', my_index='NO-1')
    G.add_nodes_from(['b', 'c'], my_index='NO-2/3')
    G.add_nodes_from(['d', 'e', 'f'])
    nx.add_cycle(G, ['d', 'e', 'f'])

    G.add_edge('c', 'd', weight=3)
    G.add_edges_from([('a', 'b', {'weight': 1}),
                      ('a', 'd', {'weight': 2}),
                      ('d', 'e', {'weight': 2}),
                      ('d', 'f', {'weight': 2}),
                      ('e', 'f', {'weight': 2})],
                     my_len=3)

    G.nodes['e']['my_index'] = 'NO-4'

    print('所有节点', G.nodes(data=True))
    print('所有边', G.edges(data=True))
    print('节点数', G.number_of_nodes())

    # 打印所有边
    for u, v, w in G.edges(data='weight'):
        print((u, v, w))

    pos = nx.spring_layout(G)
    nx.draw(G, pos,
            node_color='red',
            node_size=300,
            font_size=10,
            font_color='blue',
            with_labels=True)

    weights = nx.get_edge_attributes(G, 'weight')
    nx.draw_networkx_edge_labels(G, pos, edge_labels=weights)
    plt.show()


if __name__ == '__main__':
    my_grap()

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

 

输出的日志为:

所有节点 [('a', {'my_index': 'NO-1'}), ('b', {'my_index': 'NO-2/3'}), ('c', {'my_index': 'NO-2/3'}), ('d', {}), ('e', {'my_index': 'NO-4'}), ('f', {})]
所有边 [('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})]
节点数 6
('a', 'b', 1)
('a', 'd', 2)
('c', 'd', 3)
('d', 'e', 2)
('d', 'f', 2)
('e', 'f', 2)

以上是关于networkx网络拓扑节点图和树,python的主要内容,如果未能解决你的问题,请参考以下文章

根据节点值为networkx中的节点绘制不同的颜色

graphviz绘制图和树,python

python 使用networkx绘制带权无向图和带权有向图,以及标注特定路径

python学习(32)---networkx

存储和访问节点属性 python networkx

NetworkX 中的节点与边