plot_mst.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """
  2. =====================
  3. Minimum Spanning Tree
  4. =====================
  5. A minimum spanning tree (MST) is a subset of edges in a weighted,
  6. connected graph that connects all vertices together with the
  7. minimum possible total edge weight. The `minimum_spanning_tree`
  8. function is used to compare the original graph with its MST.
  9. """
  10. import networkx as nx
  11. import matplotlib.pyplot as plt
  12. # Create a graph
  13. G = nx.Graph()
  14. G.add_edges_from(
  15. [
  16. (0, 1, {"weight": 4}),
  17. (0, 7, {"weight": 8}),
  18. (1, 7, {"weight": 11}),
  19. (1, 2, {"weight": 8}),
  20. (2, 8, {"weight": 2}),
  21. (2, 5, {"weight": 4}),
  22. (2, 3, {"weight": 7}),
  23. (3, 4, {"weight": 9}),
  24. (3, 5, {"weight": 14}),
  25. (4, 5, {"weight": 10}),
  26. (5, 6, {"weight": 2}),
  27. (6, 8, {"weight": 6}),
  28. (7, 8, {"weight": 7}),
  29. ]
  30. )
  31. # Find the minimum spanning tree
  32. T = nx.minimum_spanning_tree(G)
  33. # Visualize the graph and the minimum spanning tree
  34. pos = nx.spring_layout(G)
  35. nx.draw_networkx_nodes(G, pos, node_color="lightblue", node_size=500)
  36. nx.draw_networkx_edges(G, pos, edge_color="grey")
  37. nx.draw_networkx_labels(G, pos, font_size=12, font_family="sans-serif")
  38. nx.draw_networkx_edge_labels(
  39. G, pos, edge_labels={(u, v): d["weight"] for u, v, d in G.edges(data=True)}
  40. )
  41. nx.draw_networkx_edges(T, pos, edge_color="green", width=2)
  42. plt.axis("off")
  43. plt.show()