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

วิธีเปลี่ยนแอตทริบิวต์ของการวาดกราฟ networkx/matplotlib ใน Python

ในการเปลี่ยนแอตทริบิวต์ของการวาดกราฟ networkx/matplotlib สามารถทำตามขั้นตอนดังนี้:

ขั้นตอน

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots

  • เริ่มต้นกราฟด้วย edges, name, หรือ graph attributes

  • เพิ่มแอตทริบิวต์ของกราฟ เพิ่ม edge ระหว่าง u และ v

  • ดึง edge attributes จากกราฟ

  • จัดตำแหน่งโหนดด้วยวงกลม

  • วาดกราฟ G ด้วย Matplotlib

  • แสดงรูปด้วยเมธอด show()

ตัวอย่าง

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()

ผลลัพธ์

จะแสดงกราฟวงกลม 5 โหนด มี edge สีต่างกันและความหนาตาม weight

วิธีเปลี่ยนแอตทริบิวต์ของการวาดกราฟ networkx/matplotlib ใน Python