我正在尝试使用python中的networks.draw()函数绘制图形。尽管它不是有向图,但按拓扑排序的顺序显示了图的边缘。我想打印看起来像依赖项DAG的图,以获得更好的可见性。目标是这样的:
我应该怎么做?
答案 0 :(得分:2)
使用如下示例边列表,并构建无向图:
edges = [[1,3], [1,4], [1,5], [5,7], [5,8] ,[5,9],
[9,11], [9,12], [9,13], [2,4], [6,8] ,[10,12]]
G = nx.Graph()
G.add_edges_from(edges)
我们可以使用节点名称来定义将节点名称映射到行的字典,其中x
坐标与节点名称相同。现在获得带有弯曲边缘的精美布局是棘手的部分。尽管有必要,否则边缘将相互重叠。可以使用matplotlib.axes.Axes.annotate
完成。
请注意,我假设源为偶数的边的边缘具有正的符号弧,否则为负,如果不是这样,应该为足够简单以适应:
pos = {node:(node,0) for node in G.nodes()}
plt.figure(figsize=(15,5))
ax = plt.gca()
for edge in edges:
source, target = edge
rad = 0.8
rad = rad if source%2 else -rad
ax.annotate("",
xy=pos[source],
xytext=pos[target],
arrowprops=dict(arrowstyle="-", color="black",
connectionstyle=f"arc3,rad={rad}",
alpha=0.6,
linewidth=1.5))
nx.draw_networkx_nodes(G, pos=pos, node_size=500, node_color='black')
nx.draw_networkx_labels(G, pos=pos, font_color='white')
plt.box(False)
plt.show()