NetworkX绘制A→B→…→H有向图混乱,如何实现环形布局?
解决NetworkX有向图环形布局混乱的问题
问题说明
需要将A→B→C→D→E→F→G→H的链式有向图呈现为环形布局,但使用spring_layout绘制出的图混乱,且尝试过Stack Overflow相关方案无效。
原代码如下:
import pandas as pd import networkx as nx import numpy as np import matplotlib.pyplot as plt import pylab refJourney = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] edgelis=[] for i in range(len(refJourney)): edgesValue = refJourney[i:i+2] if len(edgesValue)>1: edgelis.append((edgesValue[0],edgesValue[1])) G = nx.DiGraph() G.add_edges_from(edgelis, weight=0, length = 1) val_map = {refJourney[0]: 1.0, refJourney[-1]: 0.5} values = [val_map.get(node, 0) for node in G.nodes()] edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)]) plt.figure(3,figsize=(24,24)) pos=nx.spring_layout(G) nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels) nx.draw(G,pos,node_shape = 'D', node_color = values, node_size=15000,edge_cmap=plt.cm.Reds, font_color="whitesmoke", with_labels = True, font_size=10) pylab.show()
原输出图:
解决方案
核心问题是**spring_layout是力导向布局,无法保证链式节点的顺序**,改用circular_layout并指定节点顺序,就能强制实现环形布局:
- 将布局方式从
spring_layout替换为circular_layout,并传入refJourney作为节点顺序参数,确保A到H按环形依次排列; - 调整箭头样式让流向更清晰。
修改后的完整代码:
import pandas as pd import networkx as nx import numpy as np import matplotlib.pyplot as plt import pylab refJourney = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] edgelis=[] for i in range(len(refJourney)): edgesValue = refJourney[i:i+2] if len(edgesValue)>1: edgelis.append((edgesValue[0],edgesValue[1])) G = nx.DiGraph() G.add_edges_from(edgelis, weight=0, length = 1) val_map = {refJourney[0]: 1.0, refJourney[-1]: 0.5} values = [val_map.get(node, 0) for node in G.nodes()] edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)]) plt.figure(3,figsize=(24,24)) # 关键改动:使用circular_layout并指定节点顺序 pos=nx.circular_layout(G, refJourney) nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels) # 添加arrowstyle参数优化箭头显示 nx.draw(G,pos,node_shape = 'D', node_color = values, node_size=15000, edge_cmap=plt.cm.Reds, font_color="whitesmoke", with_labels = True, font_size=10, arrowstyle='->', arrowsize=20) pylab.show()
效果说明
修改后,节点会严格按照A→B→C→…→H的顺序在圆周上排列,箭头沿着环形方向指向后续节点,完美呈现预期的环形流向布局。
内容的提问来源于stack exchange,提问作者SoKu
相关产品推荐
相关产品推荐

