Python: networkx绘图
Python networkx库
1.有向图
# 1.创建一个空的有向图
G = nx.DiGraph()
nodes = ['A','B','C','D']
# 2.添加节点
for node in nodes:
G.add_node(node)
# 3.添加边
edges = [('A','B'),('B','C'),('C','D')]
for edge in edges:
G.add_edge(edge[0],edge[1])
# 4.使用spring布局C
pos = nx.spring_layout(G)
# 5.绘制图
nx.draw(G,pos,with_labels=True,node_color='skyblue',node_size=700,edge_color='k',linewidths=2,font_weight='bold',arrows=True)
# 6.显示图
plt.show()
2.无向图
# 1.创建一个空的有向图
G = nx.Graph()
nodes = ['A','B','C','D']
# 2.添加节点
for node in nodes:
G.add_node(node)
# 3.添加边
edges = [('A','B'),('B','C'),('C','D')]
for edge in edges:
G.add_edge(edge[0],edge[1])
# 4.使用spring布局C
pos = nx.spring_layout(G)
# 5.绘制图
nx.draw(G,pos,with_labels=True,node_color='skyblue',node_size=700,edge_color='k',linewidths=2,font_weight='bold',arrows=True)
# 6.显示图
plt.show()