plot_dag_layout.py 1011 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """
  2. ========================
  3. DAG - Topological Layout
  4. ========================
  5. This example combines the `topological_generations` generator with
  6. `multipartite_layout` to show how to visualize a DAG in topologically-sorted
  7. order.
  8. """
  9. import networkx as nx
  10. import matplotlib.pyplot as plt
  11. G = nx.DiGraph(
  12. [
  13. ("f", "a"),
  14. ("a", "b"),
  15. ("a", "e"),
  16. ("b", "c"),
  17. ("b", "d"),
  18. ("d", "e"),
  19. ("f", "c"),
  20. ("f", "g"),
  21. ("h", "f"),
  22. ]
  23. )
  24. for layer, nodes in enumerate(nx.topological_generations(G)):
  25. # `multipartite_layout` expects the layer as a node attribute, so add the
  26. # numeric layer value as a node attribute
  27. for node in nodes:
  28. G.nodes[node]["layer"] = layer
  29. # Compute the multipartite_layout using the "layer" node attribute
  30. pos = nx.multipartite_layout(G, subset_key="layer")
  31. fig, ax = plt.subplots()
  32. nx.draw_networkx(G, pos=pos, ax=ax)
  33. ax.set_title("DAG layout in topological order")
  34. fig.tight_layout()
  35. plt.show()