ใช้ plt.contour() กำหนดจำนวน Levels และ plt.clabel() เพื่อแสดงค่าบนเส้น Contour
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้างฟังก์ชัน f(x,y) และ Meshgrid
- วาด Contour ระบุจำนวน Levels (3 ระดับ)
- เพิ่ม Label บนเส้น Contour
- แสดงผล
ตัวอย่างโค้ด
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)
# วาด Contour 3 ระดับ สีดำ
contours = plt.contour(X, Y, Z, 3, colors='black')
# เพิ่ม Label
plt.clabel(contours, inline=True, fontsize=8)
plt.show()
การระบุ Level เฉพาะเจาะจง
# ระบุ Levels ที่ต้องการพอดี
specific_levels = [0.0, 0.5, 1.0]
contours = plt.contour(X, Y, Z, levels=specific_levels, colors='red')
plt.clabel(contours, inline=True, fontsize=10, fmt='%.1f')
ผลลัพธ์
Contour Map แสดง 3 เส้นระดับ (Levels) สีดำ พร้อมตัวเลขแสดงค่าบนแต่ละเส้น