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

วิธีตั้งค่า NetworkX edge labels offset ใน Matplotlib


เพื่อตั้งค่า networkx edge labels offset

  • ตั้งค่าขนาดรูปและ padding ระหว่าง subplots
  • สร้างกราฟพร้อม edges, name หรือ attributes
  • เพิ่มโหนดหลายตัว
  • เพิ่ม edges ทั้งหมดด้วย add_edge_from()
  • จัดตำแหน่งโหนดด้วยอัลกอริทึม Fruchterman-Reingold force-directed
  • วาดกราฟ G ด้วย Matplotlib
  • วาด edge labels
  • แสดงรูปด้วย show()

ตัวอย่าง

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'] = 3

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

nx.draw_networkx_edge_labels(
    G, pos,
    {(1, 2): "x", (2, 3): "y", (3, 4): "w",
     (4, 1): "z", (1, 3): "v"},
    label_pos=0.75
)
plt.show()

ผลลัพธ์

วิธีตั้งค่า NetworkX edge labels offset ใน Matplotlib