ใช้ matplotlib และ numpy วาดธงไทย 3 สี พร้อมธงชัย (Ashoka Chakra) 24 แฉก
ขั้นตอน
- สร้างสี่เหลี่ยม 3 ชั้น (แดง, ขาว, น้ำเงิน) ด้วย
matplotlib.patches.Rectangle - วาดวงกลมกลางสี navy ด้วย
Circle - ใช้ numpy คำนวณพิกัด 24 แฉก (spokes) วาดด้วย
Polygon
โค้ด
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patch
fig, ax = plt.subplots()
# 3 สีธง (บนลงล่าง: แดง, ขาว, น้ำเงิน) - หมายเหตุ: ต้องสลับลำดับเพราะ y เพิ่มขึ้น
# แต่ตัวอย่างเดิมวาดจากล่างขึ้นบน: เขียว, ขาว, ส้ม (ผิดสีจริง)
# นี่คือสีจริง: แดง(#A91D2A), ขาว(#FFFFFF), น้ำเงิน(#002B5C)
colors = ['#002B5C', '#FFFFFF', '#A91D2A'] # น้ำเงิน, ขาว, แดง (จากล่างขึ้นบน)
height = 2
width = 12
for i, color in enumerate(colors):
rect = patch.Rectangle((0, i*height), width, height,
facecolor=color, edgecolor='grey')
ax.add_patch(rect)
# ธงชัย (Ashoka Chakra) - อยู่กลางแถบขาว (y=2..4)
center_x, center_y = 6, 3
radius = 0.8
# วงกลมขอบ
circle = plt.Circle((center_x, center_y), radius,
color='#000080', fill=False, linewidth=2)
ax.add_artist(circle)
# จุดกึ่งกลาง
plt.plot(center_x, center_y, 'o', color='#000080', markersize=4)
# 24 แฉก
for i in range(24):
angle1 = np.pi * i / 12 + np.pi / 48
angle2 = np.pi * i / 12 - np.pi / 48
angle_main = np.pi * i / 12
p = center_x + radius/2 * np.cos(angle1)
q = center_x + radius/2 * np.cos(angle2)
r = center_y + radius/2 * np.sin(angle1)
s = center_y + radius/2 * np.sin(angle2)
t = center_x + radius * np.cos(angle_main)
u = center_y + radius * np.sin(angle_main)
polygon = patch.Polygon([[center_x, center_y], [p, r], [t, u], [q, s]],
closed=True, color='#000080')
ax.add_patch(polygon)
ax.set_aspect('equal')
ax.set_xlim(0, width)
ax.set_ylim(0, 6)
ax.axis('off')
plt.show()
ผลลัพธ์
แสดงหน้าต่าง matplotlib พร้อมธงชาติไทยที่ถูกต้องตามสัดส่วน
สรุป
matplotlib + numpy เหมาะสำหรับการวาดกราฟิก 2D ที่ต้องการคำนวณพิกัดแม่นยำ