如何在 Matplotlib 中为 3D plot_surface 制作动画?
pythonserver side programmingprogramming更新于 2025/8/7 22:36:17
要在 Matplotlib 中为 3D plot_surface 制作动画,我们可以采取以下步骤−
- 初始化网格数量(N)、每秒频率(fps)以调用函数以及帧数(frn)的变量。
- 为曲线创建 x、y 和 z 数组。
- 使用 lambda 函数创建一个函数来创建 z 数组。
- 要将函数传递到 动画类,请创建一个用户定义的函数,该函数删除前一个图并使用 x、y 和绘制曲面z 数组。
- 创建新图形或激活现有图形。
- 使用 subplots() 方法添加子图排列。
- 使用 set_zlim() 方法设置 Z 轴限制。
- 调用 animation 类 为表面图制作动画。
- 要显示图形,请使用 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"] =真
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()
输出

相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

