plot_spectral_grid.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """
  2. ==================
  3. Spectral Embedding
  4. ==================
  5. The spectral layout positions the nodes of the graph based on the
  6. eigenvectors of the graph Laplacian $L = D - A$, where $A$ is the
  7. adjacency matrix and $D$ is the degree matrix of the graph.
  8. By default, the spectral layout will embed the graph in two
  9. dimensions (you can embed your graph in other dimensions using the
  10. ``dim`` argument to either :func:`~drawing.nx_pylab.draw_spectral` or
  11. :func:`~drawing.layout.spectral_layout`).
  12. When the edges of the graph represent similarity between the incident
  13. nodes, the spectral embedding will place highly similar nodes closer
  14. to one another than nodes which are less similar.
  15. This is particularly striking when you spectrally embed a grid
  16. graph. In the full grid graph, the nodes in the center of the
  17. graph are pulled apart more than nodes on the periphery.
  18. As you remove internal nodes, this effect increases.
  19. """
  20. import matplotlib.pyplot as plt
  21. import networkx as nx
  22. options = {"node_color": "C0", "node_size": 100}
  23. G = nx.grid_2d_graph(6, 6)
  24. plt.subplot(332)
  25. nx.draw_spectral(G, **options)
  26. G.remove_edge((2, 2), (2, 3))
  27. plt.subplot(334)
  28. nx.draw_spectral(G, **options)
  29. G.remove_edge((3, 2), (3, 3))
  30. plt.subplot(335)
  31. nx.draw_spectral(G, **options)
  32. G.remove_edge((2, 2), (3, 2))
  33. plt.subplot(336)
  34. nx.draw_spectral(G, **options)
  35. G.remove_edge((2, 3), (3, 3))
  36. plt.subplot(337)
  37. nx.draw_spectral(G, **options)
  38. G.remove_edge((1, 2), (1, 3))
  39. plt.subplot(338)
  40. nx.draw_spectral(G, **options)
  41. G.remove_edge((4, 2), (4, 3))
  42. plt.subplot(339)
  43. nx.draw_spectral(G, **options)
  44. plt.show()