首先需要安装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)