Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การระบายสีขอบ (Edges) ตามน้ำหนัก (Weight) ใน NetworkX (Matplotlib)


เพื่อระบายสีขอบตามน้ำหนักใน networkx

  • ตั้งค่าขนาดรูปและ padding ระหว่าง subplots
  • สร้างกราฟพร้อม edges, name หรือ attributes
  • เพิ่มโหนด
  • เพิ่ม edges
  • วนลูป edges กำหนด weight แบบสุ่ม
  • วาดกราฟด้วย weights สำหรับ edge color
  • แสดงรูปด้วย show()

ตัวอย่าง

import random as rd
import matplotlib.pylab as plt
import networkx as nx

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

G = nx.DiGraph()
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (1, 3)])

for u, v, d in G.edges(data=True):
    d['weight'] = rd.random()

edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items())
nx.draw(G, node_color='b', edge_color=weights, width=2, with_labels=True)
plt.show()

ผลลัพธ์

การระบายสีขอบ (Edges) ตามน้ำหนัก (Weight) ใน NetworkX (Matplotlib)