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

การพล็อต imshow() แบบ 3D ใน Matplotlib

แสดงภาพ 2D (imshow) และ Contour Plot 3D พร้อมกัน เพื่อเปรียบเทียบมุมมอง

ขั้นตอน

  1. สร้าง Meshgrid XX, YY
  2. คำนวณ Data 2D จากฟังก์ชัน
  3. สร้าง Figure และ Subplots 1x2
  4. Subplot ซ้าย: imshow() 2D
  5. Subplot ขวา: contourf() 3D
  6. แสดงผล

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


import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

xx, yy = np.meshgrid(np.linspace(0, 1, 10), np.linspace(0, 1, 10))
X = xx
Y = yy
Z = 10 * np.ones(X.shape)
data = np.cos(xx) * np.cos(xx) + np.sin(yy) * np.sin(yy)

fig = plt.figure()

# Subplot ซ้าย: 2D imshow
ax1 = fig.add_subplot(121)
ax1.imshow(data, cmap="plasma", interpolation='nearest', 
           origin='lower', extent=[0, 1, 0, 1])

# Subplot ขวา: 3D Contourf
ax2 = fig.add_subplot(122, projection='3d')
ax2.contourf(X, Y, data, 100, zdir='z', offset=0.5, cmap="plasma")

plt.show()

คำอธิบายพารามิเตอร์

  • zdir='z': ใส่ Contour บนแกน Z
  • offset=0.5: ตำแหน่ง Z ของ Contour Plane
  • extent: กำหนดขอบเขตข้อมูลใน imshow
  • origin='lower': 0,0 อยู่มุมซ้ายล่าง

ผลลัพธ์

Figure 2 ส่วน: ซ้าย = 2D Heatmap, ขวา = 3D Contour Plot แสดงผิวในพื้นที่ Z=0.5