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

การเพิ่ม Contour Lines เสริมใน Matplotlib 2D Contour Plot

ใช้ plt.contour() กับพารามิเตอร์ levels เพื่อกำหนดระดับ Contour Lines ที่ต้องการเพิ่ม

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้างฟังก์ชัน f(x,y) คืนค่า Z
  3. สร้าง Meshgrid X, Y
  4. กำหนด Levels ด้วย np.arange
  5. วาด Contour และ Label
  6. แสดงผล

ตัวอย่างโค้ด


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
contourfFilled 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 ค่า