Computer >> Máy Tính >  >> Lập trình >> Python

Làm thế nào để tạo đồ thị đa phân tử bằng cách sử dụng networkx và Matplotlib?

Để tạo biểu đồ nhiều bên trong networkx, chúng ta có thể thực hiện các bước sau -

  • Đặt kích thước hình và điều chỉnh phần đệm giữa và xung quanh các ô con.

  • Tạo danh sách các kích thước và màu sắc của tập hợp con.

  • Xác định một phương thức cho đồ thị nhiều lớp có thể trả về một đối tượng đồ thị nhiều lớp.

  • Đặt màu của các nút.

  • Định vị các nút trong các lớp đường thẳng.

  • Vẽ biểu đồ G với Matplotlib.

  • Đặt thuộc tính trục bằng nhau.

  • Để hiển thị hình này, hãy sử dụng show () phương pháp.

Ví dụ

import itertools
import matplotlib.pyplot as plt
import networkx as nx

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

subset_sizes = [5, 5, 4, 3, 2, 4, 4, 3]
subset_color = [
   "gold",
   "violet",
   "violet",
   "violet",
   "violet",
   "limegreen",
   "limegreen",
   "darkorange",
]

def multilayered_graph(*subset_sizes):
   extents = nx.utils.pairwise(itertools.accumulate((0,) + subset_sizes))
   layers = [range(start, end) for start, end in extents]
   G = nx.Graph()
   for (i, layer) in enumerate(layers):
      G.add_nodes_from(layer, layer=i)
   for layer1, layer2 in nx.utils.pairwise(layers):
      G.add_edges_from(itertools.product(layer1, layer2))
   return G

G = multilayered_graph(*subset_sizes)
color = [subset_color[data["layer"]] for v, data in G.nodes(data=True)]
pos = nx.multipartite_layout(G, subset_key="layer")
nx.draw(G, pos, node_color=color, with_labels=False)

plt.axis("equal")

plt.show()

Đầu ra

Làm thế nào để tạo đồ thị đa phân tử bằng cách sử dụng networkx và Matplotlib?