ใช้ axes.set_aspect(1) หรือ 'equal' เพื่อทำให้ Aspect Ratio เท่ากัน ทำให้ Contourf กลมเป็นวงกลม
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้าง Meshgrid X, Y
- คำนวณ Z = X² + Y² - 0.2 (สมการวงกลม)
- สร้าง Figure และ Axes
- วาด Contourf
- ตั้ง Aspect Ratio = 1
- แสดงผล
ตัวอย่างโค้ด
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-0.5, 0.5, 100)
y = np.linspace(-0.5, 0.5, 100)
a, b = np.meshgrid(x, y)
c = a ** 2 + b ** 2 - 0.2
figure, axes = plt.subplots()
axes.contourf(a, b, c)
axes.set_aspect(1) # หรือ 'equal'
plt.show()
คำอธิบาย
c = a² + b² - 0.2: สมการวงกลม รัศมี √0.2 ≈ 0.447set_aspect(1): ทำให้ 1 หน่วย X = 1 หน่วย Y (ไม่บีบอัด)- โดยไม่ตั้งค่า Aspect Ratio วงกลมจะกลายเป็น Ellipse
ตัวอย่างเพิ่มเติม: Multiple Circles
# หลายวงกลม
c1 = a**2 + b**2 - 0.04 # รัศมี 0.2
c2 = a**2 + b**2 - 0.16 # รัศมี 0.4
c3 = a**2 + b**2 - 0.36 # รัศมี 0.6
axes.contourf(a, b, c1, levels=[0, 1], colors='red', alpha=0.3)
axes.contourf(a, b, c2, levels=[0, 1], colors='blue', alpha=0.3)
axes.contourf(a, b, c3, levels=[0, 1], colors='green', alpha=0.3)
axes.set_aspect('equal')
ผลลัพธ์
Filled Contour Plot รูปวงกลมสมบูรณ์ (ไม่ใช่ Ellipse) แสดงพื้นที่ที่ a²+b² ≤ 0.2