ใช้ plt.contour() กับพารามิเตอร์ levels เพื่อกำหนดระดับ Contour Lines ที่ต้องการเพิ่ม
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้างฟังก์ชัน f(x,y) คืนค่า Z
- สร้าง Meshgrid X, Y
- กำหนด Levels ด้วย
np.arange - วาด Contour และ Label
- แสดงผล
ตัวอย่างโค้ด
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
# กำหนด Levels: -1.0 ถึง 1.5 ทุก 0.25
levels = np.arange(-1.0, 1.5, 0.25)
CS = plt.contour(X, Y, Z, levels=levels)
plt.clabel(CS, inline=1, fontsize=10)
plt.title('levels = {}'.format(levels.tolist()))
plt.show()
Contour vs Contourf
| Function | ลักษณะ |
|---|---|
contour | เฉพาะเส้น Contour Lines |
contourf | Filled Contour (เติมสีระหว่างเส้น) |
การเพิ่ม Contour Lines บน Contourf
# วาด Filled Contour ก่อน
cf = plt.contourf(X, Y, Z, levels=20, cmap='viridis')
# วาด Contour Lines ทับด้านบน
cs = plt.contour(X, Y, Z, levels=levels, colors='black', linewidths=0.5)
plt.clabel(cs, inline=True, fontsize=8)
plt.colorbar(cf)
ผลลัพธ์
Contour Plot แสดงเส้นระดับ (Levels) ตามที่กำหนด -1.0 ถึง 1.5 ช่วง 0.25 พร้อม Label ค่า