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

Vẽ surface plot 3D từ DataFrame trong Matplotlib

Để vẽ surface plot 3D, dữ liệu cần ở dạng lưới 2D (meshgrid), không phải DataFrame 1D. Ta tạo dữ liệu 2D từ NumPy.

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo figure và thêm axes 3D bằng add_subplot(111, projection='3d').
  • Khởi tạo số mẫu n.
  • Tạo dữ liệu x, y, z ngẫu nhiên (z phải là ma trận 2D n×n).
  • Vẽ bề mặt bằng plot_surface() với colormap.
  • Tắt axes và hiển thị bằng show().

Ví dụ

import numpy as np
from matplotlib import pyplot as plt

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 50
x = np.random.rand(n)
y = np.tan(x)
z = np.random.rand(n, n)
surf = ax.plot_surface(y, x, z, rstride=1, cstride=1, cmap='copper', linewidth=0, antialiased=False)
ax.axis('off')
plt.show()

Kết quả

Vẽ surface plot 3D từ DataFrame trong Matplotlib