Note
Go to the end to download the full example code.
DAG - 拓扑布局#
此示例结合了 topological_generations
生成器与 multipartite_layout
,展示了如何以拓扑排序的顺序可视化有向无环图(DAG)。
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph(
[
("f", "a"),
("a", "b"),
("a", "e"),
("b", "c"),
("b", "d"),
("d", "e"),
("f", "c"),
("f", "g"),
("h", "f"),
]
)
for layer, nodes in enumerate(nx.topological_generations(G)):
# `multipartite_layout` 期望将层作为节点属性,因此添加
# 将数值层作为节点属性
for node in nodes:
G.nodes[node]["layer"] = layer
# 使用“layer”节点属性计算多部分布局
pos = nx.multipartite_layout(G, subset_key="layer")
fig, ax = plt.subplots()
nx.draw_networkx(G, pos=pos, ax=ax)
ax.set_title("DAG layout in topological order")
fig.tight_layout()
plt.show()
Total running time of the script: (0 minutes 0.053 seconds)