Matlab surf(x,y,z,c) สร้าง Surface Plot 3D ที่สี (C) แสดงค่าเพิ่มเติม ใน Matplotlib ใช้ ax.plot_surface() พร้อม facecolors หรือ cmap
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้าง Figure และ 3D Axes
- สร้างข้อมูล Sphere (u, v → x, y, z)
- วาด Surface Plot พร้อม Colormap
- แสดงผล
ตัวอย่างโค้ด
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
r = 0.05
u, v = np.mgrid[0:2*np.pi:30j, 0:np.pi:20j]
x = np.cos(u) * np.sin(v)
y = np.sin(u) * np.sin(v)
z = np.cos(v)
# ใช้ Colormap แทน C data
ax.plot_surface(x, y, z, cmap=plt.cm.YlGnBu_r)
plt.show()
การ Map Color Data (C) แบบกำหนดเอง
# สมมติ C เป็นข้อมูลอีกชุดหนึ่งขนาดเท่า Z
C = np.sin(x) * np.cos(y)
# Normalize C
from matplotlib.colors import Normalize
norm = Normalize(vmin=C.min(), vmax=C.max())
colors = plt.cm.YlGnBu_r(norm(C))
# ใช้ facecolors
ax.plot_surface(x, y, z, facecolors=colors, rstride=1, cstride=1)
การเพิ่ม Colorbar
# สำหรับ cmap
surf = ax.plot_surface(x, y, z, cmap='viridis')
fig.colorbar(surf, ax=ax, shrink=0.5, aspect=10)
# สำหรับ facecolors ต้องสร้าง ScalarMappable
from matplotlib.cm import ScalarMappable
m = ScalarMappable(cmap=plt.cm.YlGnBu_r, norm=norm)
m.set_array([])
fig.colorbar(m, ax=ax)
ผลลัพธ์
Surface Plot 3D รูปทรงคล้าย Sphere ใช้ Colormap YlGnBu_r แสดงความสูง/ค่า