Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách định hình lại (reshape) đồ thị networkx trong Python

Thay đổi cấu trúc đồ thị networkx bằng cách sửa danh sách cạnh (edges) trong DataFrame.

  • Tạo DataFrame cột 'from', 'to'.
  • G = nx.from_pandas_edgelist(df, 'from', 'to').
  • nx.draw(G, with_labels=True, node_size=150, alpha=0.5, linewidths=40).
  • show().

Ví dụ

import pandas as pd
import networkx as nx
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame({'from': ['A', 'B', 'C', 'A'], 'to': ['D', 'A', 'E', 'C']})
G = nx.from_pandas_edgelist(df, 'from', 'to')
nx.draw(G, with_labels=True, node_size=150, alpha=0.5, linewidths=40)
plt.show()

Kết quả

Đồ thị networkx 5 nút (A,B,C,D,E) 4 cạnh, vẽ với nhãn, node nhỏ, trong suốt.