บทนำ
Masked surface plot คือ 3D surface plot ที่ซ่อนบางส่วนของพื้นผิวด้วย masked array ใช้ numpy.ma.masked_where() สร้าง mask แล้ววาดด้วย ax.plot_surface()
ตัวอย่างโค้ด
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# สร้าง figure และ 3D axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# สร้าง grid ของ pi และ theta
pi_vals = np.arange(1, 10, 2) * np.pi / 4
theta_vals = np.arange(1, 10, 2) * np.pi / 4
pi_grid, theta_grid = np.meshgrid(pi_vals, theta_vals)
# คำนวณ x, y, z
x = np.cos(pi_grid) * np.sin(theta_grid)
y = np.sin(pi_grid) * np.sin(theta_grid)
z = np.ma.masked_where(x >= 0.01, y) # mask ที่ x >= 0.01
# วาด surface plot
surf = ax.plot_surface(x, y, z, color='red', alpha=0.8)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Masked Surface Plot')
plt.show()
คำอธิบาย Mask
# masked_where(condition, array)
# condition=True → mask (ซ่อน)
# condition=False → แสดง
z = np.ma.masked_where(x >= 0.01, y)
# ซ่อนส่วนที่ x >= 0.01 แสดงเฉพาะ x < 0.01
การสร้าง Mask แบบต่างๆ
# 1. masked_where: ซ่อนที่ condition True
z1 = np.ma.masked_where(x > 0, y)
# 2. masked_greater: ซ่อนที่ > value
z2 = np.ma.masked_greater(y, 0.5)
# 3. masked_less: ซ่อนที่ < value
z3 = np.ma.masked_less(y, -0.5)
# 4. masked_inside: ซ่อนในช่วง [v1, v2]
z4 = np.ma.masked_inside(y, -0.2, 0.2)
# 5. masked_outside: ซอยนอกช่วง
z5 = np.ma.masked_outside(y, -0.5, 0.5)
# 6. Manual mask assignment
z6 = np.ma.array(y, mask=(x > 0))
การปรับแต่ง Surface Plot
surf = ax.plot_surface(
x, y, z,
color='red', # สีคงที่
# cmap='viridis', # หรือใช้ colormap
alpha=0.8, # ความโปร่งใส
rstride=1, # row stride
cstride=1, # col stride
linewidth=0, # ขอบเส้น
antialiased=True, # anti-aliasing
shade=True # เงา
)
# เพิ่ม colorbar (ถ้าใช้ cmap)
# fig.colorbar(surf, ax=ax, shrink=0.5)
กรณีใช้งานจริง
- แสดงฟังก์ชันคณิตศาสตร์ที่ไม่มีค่าบางโดเมน
- Visualize ข้อมูลภูมิศาสตร์ที่มีช่องว่าง
- Simulation results ที่มี invalid regions
สรุป
ใช้ np.ma.masked_where(condition, data) สร้าง masked array แล้วส่งให้ ax.plot_surface() ส่วนที่ masked จะไม่ถูกวาด ทำให้เห็นโครงสร้างภายในหรือตัดพื้นที่ไม่ต้องการได้