plot_weighted_graph.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """
  2. ==============
  3. Weighted Graph
  4. ==============
  5. An example using Graph as a weighted network.
  6. """
  7. import matplotlib.pyplot as plt
  8. import networkx as nx
  9. G = nx.Graph()
  10. G.add_edge("a", "b", weight=0.6)
  11. G.add_edge("a", "c", weight=0.2)
  12. G.add_edge("c", "d", weight=0.1)
  13. G.add_edge("c", "e", weight=0.7)
  14. G.add_edge("c", "f", weight=0.9)
  15. G.add_edge("a", "d", weight=0.3)
  16. elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] > 0.5]
  17. esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] <= 0.5]
  18. pos = nx.spring_layout(G, seed=7) # positions for all nodes - seed for reproducibility
  19. # nodes
  20. nx.draw_networkx_nodes(G, pos, node_size=700)
  21. # edges
  22. nx.draw_networkx_edges(G, pos, edgelist=elarge, width=6)
  23. nx.draw_networkx_edges(
  24. G, pos, edgelist=esmall, width=6, alpha=0.5, edge_color="b", style="dashed"
  25. )
  26. # node labels
  27. nx.draw_networkx_labels(G, pos, font_size=20, font_family="sans-serif")
  28. # edge weight labels
  29. edge_labels = nx.get_edge_attributes(G, "weight")
  30. nx.draw_networkx_edge_labels(G, pos, edge_labels)
  31. ax = plt.gca()
  32. ax.margins(0.08)
  33. plt.axis("off")
  34. plt.tight_layout()
  35. plt.show()