plot_degree_histogram.py 987 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/usr/bin/env python
  2. """
  3. ================
  4. Degree histogram
  5. ================
  6. Draw degree histogram with matplotlib.
  7. Random graph shown as inset
  8. """
  9. import collections
  10. import matplotlib.pyplot as plt
  11. import networkx as nx
  12. G = nx.gnp_random_graph(100, 0.02)
  13. degree_sequence = sorted([pen_weight for n, pen_weight in G.degree()], reverse=True) # degree sequence
  14. # print "Degree sequence", degree_sequence
  15. degreeCount = collections.Counter(degree_sequence)
  16. deg, cnt = zip(*degreeCount.items())
  17. fig, ax = plt.subplots()
  18. plt.bar(deg, cnt, width=0.80, color='b')
  19. plt.title("Degree Histogram")
  20. plt.ylabel("Count")
  21. plt.xlabel("Degree")
  22. ax.set_xticks([pen_weight + 0.4 for pen_weight in deg])
  23. ax.set_xticklabels(deg)
  24. # draw graph in inset
  25. plt.axes([0.4, 0.4, 0.5, 0.5])
  26. Gcc = G.subgraph(sorted(nx.connected_components(G), key=len, reverse=True)[0])
  27. pos = nx.spring_layout(G)
  28. plt.axis('off')
  29. nx.draw_networkx_nodes(G, pos, node_size=20)
  30. nx.draw_networkx_edges(G, pos, alpha=0.4)
  31. plt.show()