plot_directed.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """
  2. ==============
  3. Directed Graph
  4. ==============
  5. Draw a graph with directed edges using a colormap and different node sizes.
  6. Edges have different colors and alphas (opacity). Drawn using matplotlib.
  7. """
  8. import matplotlib as mpl
  9. import matplotlib.pyplot as plt
  10. import networkx as nx
  11. seed = 13648 # Seed random number generators for reproducibility
  12. G = nx.random_k_out_graph(10, 3, 0.5, seed=seed)
  13. pos = nx.spring_layout(G, seed=seed)
  14. node_sizes = [3 + 10 * i for i in range(len(G))]
  15. M = G.number_of_edges()
  16. edge_colors = range(2, M + 2)
  17. edge_alphas = [(5 + i) / (M + 4) for i in range(M)]
  18. cmap = plt.cm.plasma
  19. nodes = nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color="indigo")
  20. edges = nx.draw_networkx_edges(
  21. G,
  22. pos,
  23. node_size=node_sizes,
  24. arrowstyle="->",
  25. arrowsize=10,
  26. edge_color=edge_colors,
  27. edge_cmap=cmap,
  28. width=2,
  29. )
  30. # set alpha value for each edge
  31. for i in range(M):
  32. edges[i].set_alpha(edge_alphas[i])
  33. pc = mpl.collections.PatchCollection(edges, cmap=cmap)
  34. pc.set_array(edge_colors)
  35. ax = plt.gca()
  36. ax.set_axis_off()
  37. plt.colorbar(pc, ax=ax)
  38. plt.show()