ขั้นตอนการทำงาน
กำหนดขนาดรูปภาพและปรับระยะห่างรอบๆ subplots
สร้างรายการ Tuple (x, y, z)
แยก x, y, z จาก Tuple
สร้าง Coordinate Matrices ด้วย np.meshgrid()
คำนวณค่า h สำหรับ Surface Plot
สร้าง Figure ใหม่หรือเปิดใช้งาน Figure ที่มีอยู่
ดึง Axis แบบ 3D ของ Figure
สร้าง Surface Plot
แสดงรูปภาพด้วยเมธอด show()
ตัวอย่างโค้ด
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# รายการ Tuple (x, y, z)
data = [(1, 3, 2), (3, 5, 2), (4, 7, 4), (8, 7, 4),
(3, 6, 1), (3, 9, 0), (3, 9, 0)]
# แยก x, y, z
x, y, z = zip(*data)
x, y = np.meshgrid(x, y)
h = x ** 2 + y ** 2
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(x, y, h, cmap='plasma')
plt.show()
ผลลัพธ์
Surface Plot 3D จากข้อมูล Tuple คำนวณ h = x² + y² ใช้ Colormap 'plasma' แสดงความสูง
หมายเหตุ: ข้อมูล Tuple ต้องมีโครงสร้าง Grid ที่สมบูรณ์ (x, y ครบทุกคู่) มิฉะนั้น Meshgrid จะสร้าง Grid ที่ไม่ตรงกับข้อมูลจริง ควรใช้ griddata สำหรับข้อมูล Scattered