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

Python Matplotlib: วาด Lattice และ Graph ด้วย NetworkX

บทนำ

NetworkX เป็น library สำหรับสร้างและวิเคราะห์กราฟ (graph theory) สามารถวาดกราฟได้โดยตรงผ่าน Matplotlib ใช้ nx.draw() ร่วมกับ nx.grid_2d_graph() สำหรับ lattice grid

ตัวอย่างโค้ด: 2D Grid Graph (Lattice)


import networkx as nx
import matplotlib.pyplot as plt

# กำหนดขนาดรูป
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# สร้าง 2D grid graph 3x3
# แต่ละ node เชื่อมกับเพื่อนบ้าน 4 ทิศ (up, down, left, right)
G = nx.grid_2d_graph(3, 3)

# วาดกราฟ
nx.draw(G, node_size=100, with_labels=True, font_size=8)

plt.title("3x3 Grid Graph (Lattice)")
plt.show()

ผลลัพธ์

กริด 3x3 = 9 nodes, แต่ละ node เชื่อมกับเพื่อนบ้าน (ยกเว้นขอบ) รวม 12 edges

กราฟประเภทอื่นๆ ใน NetworkX


# Complete graph (ทุกคู่เชื่อมกัน)
K5 = nx.complete_graph(5)

# Cycle graph
C6 = nx.cycle_graph(6)

# Star graph
S5 = nx.star_graph(5)

# Path graph
P5 = nx.path_graph(5)

# Random graph (Erdos-Renyi)
ER = nx.erdos_renyi_graph(20, 0.3)

# Barabasi-Albert (scale-free)
BA = nx.barabasi_albert_graph(50, 2)

# วาดทุกกราฟ
graphs = {
    'Complete K5': K5,
    'Cycle C6': C6,
    'Star S5': S5,
    'Path P5': P5,
    'Erdos-Renyi': ER,
    'Barabasi-Albert': BA
}

fig, axes = plt.subplots(2, 3, figsize=(12, 8))
for (name, G), ax in zip(graphs.items(), axes.flat):
    nx.draw(G, ax=ax, node_size=50, with_labels=False)
    ax.set_title(name)
plt.tight_layout()
plt.show()

การปรับแต่งการวาด (Customization)


import networkx as nx
import matplotlib.pyplot as plt

G = nx.grid_2d_graph(4, 4)

# Layout ต่างๆ
pos = nx.spring_layout(G, seed=42)        # Force-directed
pos = nx.circular_layout(G)                # วงกลม
pos = nx.spectral_layout(G)                # Spectral
pos = nx.kamada_kawai_layout(G)            # Kamada-Kawai

# วาดแบบกำหนดเอง
nx.draw(G, pos=pos,
        node_color='lightblue',
        node_size=200,
        edge_color='gray',
        width=1.5,
        with_labels=True,
        font_size=8,
        font_weight='bold')

# Node attributes
node_colors = [G.degree(n) for n in G.nodes()]
nx.draw(G, pos=pos, node_color=node_colors, cmap=plt.cm.viridis, node_size=200)

Graph Analysis พื้นฐาน


G = nx.grid_2d_graph(3, 3)

print(f"Nodes: {G.number_of_nodes()}")        # 9
print(f"Edges: {G.number_of_edges()}")        # 12
print(f"Degree: {dict(G.degree())}")          # degree ของแต่ละ node
print(f"Clustering: {nx.average_clustering(G)}")  # clustering coefficient
print(f"Shortest path (0,0) to (2,2): {nx.shortest_path_length(G, (0,0), (2,2))}")  # 4

สรุป

NetworkX + Matplotlib = โซลูชันครบวงจรสำหรับ Graph Visualization ใช้ nx.grid_2d_graph(m, n) สร้าง lattice grid ใช้ nx.draw() วาด รองรับ layout หลากหลายและการปรับแต่งสไตล์เต็มรูปแบบ