Contour Plot พร้อม Logarithmic Color Scale
ใช้ contourf() พร้อม ticker.LogLocator() และ colormap
ขั้นตอนหลัก
- ตั้งค่าขนาดรูปและ padding
- กำหนด N และสร้าง meshgrid X, Y
- คำนวณ Z = Z1 + 50*Z2 (หลาย scales)
- Mask ค่าที่ <= 0 (log ไม่รับค่า <= 0)
- สร้าง figure และ axes
- พล็อต contourf() พร้อม locator=ticker.LogLocator()
- เพิ่ม colorbar
- แสดงผลด้วย show()
ตัวอย่างโค้ด
import matplotlib.pyplot as plt
import numpy as np
from numpy import ma
from matplotlib import ticker, cm
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
N = 100
x = np.linspace(-3.0, 3.0, N)
y = np.linspace(-2.0, 2.0, N)
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
z = Z1 + 50 * Z2
z[:5, :5] = -1
z = ma.masked_where(z <= 0, z)
fig, ax = plt.subplots()
cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.PuBu_r)
cbar = fig.colorbar(cs)
plt.show()
คำอธิบาย
- LogLocator: วาง contour levels ใน log scale
- masked_where: ซ่อนค่า <= 0 เพราะ log ไม่กำหนด
- cm.PuBu_r: colormap Purple-Blue reversed