Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Vẽ ảnh imshow() 3D trong Matplotlib

Để vẽ ảnh imshow() trong 3D với Matplotlib:

  • Tạo xx và yy bằng numpy
  • Lấy dữ liệu data (2D) từ X, Y, Z
  • Tạo figure mới
  • Thêm ax1 cho subplot 2D
  • Hiển thị dữ liệu như ảnh 2D raster
  • Thêm ax2 cho subplot 3D
  • Tạo contour plot 3D
  • Hiển thị bằng show()

Ví dụ mã nguồn

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()
ax1 = fig.add_subplot(121)
ax1.imshow(data, cmap="plasma", interpolation='nearest', origin='lower', extent=[0, 1, 0, 1])
ax2 = fig.add_subplot(122, projection='3d')
ax2.contourf(X, Y, data, 100, zdir='z', offset=0.5, cmap="plasma")
plt.show()

Kết quả

Bên trái: imshow 2D. Bên phải: contourf 3D projection với zdir='z', offset=0.5.

Vẽ ảnh imshow() 3D trong Matplotlib

Lưu ý: contourf vẽ contour filled (tô màu), contour vẽ đường contour lines. zdir và offset đặt vị trí mặt phẳng 2D trong không gian 3D.