plot_simple_graph.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """
  2. ============
  3. Simple graph
  4. ============
  5. Draw simple graph with manual layout.
  6. """
  7. import networkx as nx
  8. import matplotlib.pyplot as plt
  9. G = nx.Graph()
  10. G.add_edge(1, 2)
  11. G.add_edge(1, 3)
  12. G.add_edge(1, 5)
  13. G.add_edge(2, 3)
  14. G.add_edge(3, 4)
  15. G.add_edge(4, 5)
  16. # explicitly set positions
  17. pos = {1: (0, 0), 2: (-1, 0.3), 3: (2, 0.17), 4: (4, 0.255), 5: (5, 0.03)}
  18. options = {
  19. "font_size": 36,
  20. "node_size": 3000,
  21. "node_color": "white",
  22. "edgecolors": "black",
  23. "linewidths": 5,
  24. "width": 5,
  25. }
  26. nx.draw_networkx(G, pos, **options)
  27. # Set margins for the axes so that nodes aren't clipped
  28. ax = plt.gca()
  29. ax.margins(0.20)
  30. plt.axis("off")
  31. plt.show()
  32. # %%
  33. # A directed graph
  34. G = nx.DiGraph([(0, 3), (1, 3), (2, 4), (3, 5), (3, 6), (4, 6), (5, 6)])
  35. # group nodes by column
  36. left_nodes = [0, 1, 2]
  37. middle_nodes = [3, 4]
  38. right_nodes = [5, 6]
  39. # set the position according to column (x-coord)
  40. pos = {n: (0, i) for i, n in enumerate(left_nodes)}
  41. pos.update({n: (1, i + 0.5) for i, n in enumerate(middle_nodes)})
  42. pos.update({n: (2, i + 0.5) for i, n in enumerate(right_nodes)})
  43. nx.draw_networkx(G, pos, **options)
  44. # Set margins for the axes so that nodes aren't clipped
  45. ax = plt.gca()
  46. ax.margins(0.20)
  47. plt.axis("off")
  48. plt.show()