如何在 Matplotlib 中動態顯示 3D 繪製表面?


要在 Matplotlib 中動態顯示 3D 繪製表面,我們可採取以下步驟:

  • 初始化網格數量 (N)、每秒呼叫函式的頻率 (fps) 和幀數 (frn) 的變數。
  • 針對曲線建立 x、y 和 z 陣列。
  • 使用 lambda 函式建立一個函式來生成 z 陣列。
  • 要將函式傳遞到動畫類中,建立一個自定義函式,以使用 x、y 和 z 陣列移除上一個繪圖,並繪製一個曲面。
  • 建立一個新繪圖或啟用一個現有繪圖。
  • 使用 subplots() 方法新增一個子圖佈置。
  • 使用 set_zlim() 方法設定 Z 軸限制。
  • 呼叫動畫類以顯示曲面繪圖的動態效果。
  • 要顯示繪圖,請使用 show() 方法。

示例

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

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

N = 50
fps = 250
frn = 75

x = np.linspace(-4, 4, N + 1)
x, y = np.meshgrid(x, x)
zarray = np.zeros((N + 1, N + 1, frn))

f = lambda x, y, sig: 1 / np.sqrt(sig) * np.exp(-(x ** 2 + y ** 2) / sig ** 2)

for i in range(frn):
   zarray[:, :, i] = f(x, y, 1.5 + np.sin(i * 2 * np.pi / frn))

def change_plot(frame_number, zarray, plot):
   plot[0].remove()
   plot[0] = ax.plot_surface(x, y, zarray[:, :, frame_number], cmap="afmhot_r")

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

plot = [ax.plot_surface(x, y, zarray[:, :, 0], color='0.75', rstride=1, cstride=1)]

ax.set_zlim(0, 1.1)
ani = animation.FuncAnimation(fig, change_plot, frn, fargs=(zarray, plot), interval=1000 / fps)

ax.axis('off')

plt.show()

輸出

更新於:07-Jul-2021

2 千次瀏覽

開啟你的 職業生涯

完成該課程以獲得認證

入門
廣告
© . All rights reserved.