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

Thiết lập tỷ lệ khung hình (aspect ratio) cho đồ thị 3D trong Matplotlib

Đặt aspect ratio cho axes 3D bằng set_aspect('auto').

  • Tạo figure, lấy axes với projection='3d'.
  • Tạo lưới R, Y bằng meshgrid.
  • Tính z = 0.1 * |sin(R/40) * sin(Y/6)|.
  • Vẽ surface plot với cmap=cm.rainbow.
  • ax.set_aspect('auto'), đặt azim=-160, elev=30.
  • Lưu figure bằng savefig(), hiển thị show().

Ví dụ

from matplotlib import pyplot as plt
from matplotlib import cm
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.gca(projection='3d')
R, Y = np.meshgrid(np.arange(0, 100, 1), np.arange(0, 60, 1))
z = 0.1 * np.abs(np.sin(R / 40) * np.sin(Y / 6))
ax.plot_surface(R, Y, z, cmap=cm.rainbow, linewidth=0)
ax.set_aspect('auto')
ax.azim = -160
ax.elev = 30
fig.savefig('data.png')
plt.show()

Kết quả

Đồ thị bề mặt 3D với aspect ratio tự động, góc nhìn tùy chỉnh.