plot_printgraph.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """
  2. ===========
  3. Print Graph
  4. ===========
  5. Example subclass of the Graph class.
  6. """
  7. import matplotlib.pyplot as plt
  8. import networkx as nx
  9. from networkx import Graph
  10. class PrintGraph(Graph):
  11. """
  12. Example subclass of the Graph class.
  13. Prints activity log to file or standard output.
  14. """
  15. def __init__(self, data=None, name="", file=None, **attr):
  16. super().__init__(data=data, name=name, **attr)
  17. if file is None:
  18. import sys
  19. self.fh = sys.stdout
  20. else:
  21. self.fh = open(file, "w")
  22. def add_node(self, n, attr_dict=None, **attr):
  23. super().add_node(n, attr_dict=attr_dict, **attr)
  24. self.fh.write(f"Add node: {n}\n")
  25. def add_nodes_from(self, nodes, **attr):
  26. for n in nodes:
  27. self.add_node(n, **attr)
  28. def remove_node(self, n):
  29. super().remove_node(n)
  30. self.fh.write(f"Remove node: {n}\n")
  31. def remove_nodes_from(self, nodes):
  32. for n in nodes:
  33. self.remove_node(n)
  34. def add_edge(self, u, v, attr_dict=None, **attr):
  35. super().add_edge(u, v, attr_dict=attr_dict, **attr)
  36. self.fh.write(f"Add edge: {u}-{v}\n")
  37. def add_edges_from(self, ebunch, attr_dict=None, **attr):
  38. for e in ebunch:
  39. u, v = e[0:2]
  40. self.add_edge(u, v, attr_dict=attr_dict, **attr)
  41. def remove_edge(self, u, v):
  42. super().remove_edge(u, v)
  43. self.fh.write(f"Remove edge: {u}-{v}\n")
  44. def remove_edges_from(self, ebunch):
  45. for e in ebunch:
  46. u, v = e[0:2]
  47. self.remove_edge(u, v)
  48. def clear(self):
  49. super().clear()
  50. self.fh.write("Clear graph\n")
  51. G = PrintGraph()
  52. G.add_node("foo")
  53. G.add_nodes_from("bar", weight=8)
  54. G.remove_node("b")
  55. G.remove_nodes_from("ar")
  56. print("Nodes in G: ", G.nodes(data=True))
  57. G.add_edge(0, 1, weight=10)
  58. print("Edges in G: ", G.edges(data=True))
  59. G.remove_edge(0, 1)
  60. G.add_edges_from(zip(range(0, 3), range(1, 4)), weight=10)
  61. print("Edges in G: ", G.edges(data=True))
  62. G.remove_edges_from(zip(range(0, 3), range(1, 4)))
  63. print("Edges in G: ", G.edges(data=True))
  64. G = PrintGraph()
  65. nx.add_path(G, range(10))
  66. nx.add_star(G, range(9, 13))
  67. pos = nx.spring_layout(G, seed=225) # Seed for reproducible layout
  68. nx.draw(G, pos)
  69. plt.show()