plot_degree.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """
  2. ===============
  3. Degree Analysis
  4. ===============
  5. This example shows several ways to visualize the distribution of the degree of
  6. nodes with two common techniques: a *degree-rank plot* and a
  7. *degree histogram*.
  8. In this example, a random Graph is generated with 100 nodes. The degree of
  9. each node is determined, and a figure is generated showing three things:
  10. 1. The subgraph of connected components
  11. 2. The degree-rank plot for the Graph, and
  12. 3. The degree histogram
  13. """
  14. import networkx as nx
  15. import numpy as np
  16. import matplotlib.pyplot as plt
  17. G = nx.gnp_random_graph(100, 0.02, seed=10374196)
  18. degree_sequence = sorted((d for n, d in G.degree()), reverse=True)
  19. dmax = max(degree_sequence)
  20. fig = plt.figure("Degree of a random graph", figsize=(8, 8))
  21. # Create a gridspec for adding subplots of different sizes
  22. axgrid = fig.add_gridspec(5, 4)
  23. ax0 = fig.add_subplot(axgrid[0:3, :])
  24. Gcc = G.subgraph(sorted(nx.connected_components(G), key=len, reverse=True)[0])
  25. pos = nx.spring_layout(Gcc, seed=10396953)
  26. nx.draw_networkx_nodes(Gcc, pos, ax=ax0, node_size=20)
  27. nx.draw_networkx_edges(Gcc, pos, ax=ax0, alpha=0.4)
  28. ax0.set_title("Connected components of G")
  29. ax0.set_axis_off()
  30. ax1 = fig.add_subplot(axgrid[3:, :2])
  31. ax1.plot(degree_sequence, "b-", marker="o")
  32. ax1.set_title("Degree Rank Plot")
  33. ax1.set_ylabel("Degree")
  34. ax1.set_xlabel("Rank")
  35. ax2 = fig.add_subplot(axgrid[3:, 2:])
  36. ax2.bar(*np.unique(degree_sequence, return_counts=True))
  37. ax2.set_title("Degree histogram")
  38. ax2.set_xlabel("Degree")
  39. ax2.set_ylabel("# of Nodes")
  40. fig.tight_layout()
  41. plt.show()