Để thay đổi thuộc tính vẽ đồ thị networkx/matplotlib, thực hiện các bước sau:
Các bước
- Thiết lập kích thước hình và điều chỉnh padding giữa các subplot.
- Khởi tạo đồ thị với các cạnh, tên hoặc thuộc tính đồ thị.
- Thêm thuộc tính đồ thị. Thêm cạnh giữa u và v.
- Lấy thuộc tính cạnh từ đồ thị.
- Định vị các nút bằng layout tròn.
- Vẽ đồ thị G với Matplotlib.
- Hiển thị hình bằng phương thức show().
Ví dụ
import matplotlib.pyplot as plt
import networkx as nx
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
G = nx.Graph()
G.add_edge(0, 1, color='r', weight=2)
G.add_edge(1, 2, color='g', weight=4)
G.add_edge(2, 3, color='b', weight=6)
G.add_edge(3, 4, color='y', weight=3)
G.add_edge(4, 0, color='m', weight=1)
colors = nx.get_edge_attributes(G, 'color').values()
weights = nx.get_edge_attributes(G, 'weight').values()
pos = nx.circular_layout(G)
nx.draw(G, pos,
edge_color=colors,
width=list(weights),
with_labels=True,
node_color='lightgreen')
plt.show()
Kết quả
Sẽ tạo ra đồ thị có các cạnh màu sắc và độ dày khác nhau, nút màu xanh nhạt.