为了播放动画,我重新构建了您的代码。
首先,您需要定义一个函数update,您想要从一帧更改为下一帧的内容将被更新。在我们的例子中,在update 函数中,我根据t 参数更新x、y 和z 坐标。然后我清除以前的图并用更新的坐标绘制一个新的图。最后,设置坐标轴范围很方便,以保持动画帧固定。
def update(t):
ax.cla()
x = np.cos(t/10)
y = np.sin(t/10)
z = 5
ax.scatter(x, y, z, s = 100, marker = 'o')
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_zlim(-1, 10)
然后创建一个图形和一个FuncAnimation 实例,将播放动画的图形、update 函数和其他重要参数传递给该实例,如帧数、它们之间的间隔等.请参阅documentation 了解更多信息。
fig = plt.figure(dpi=100)
ax = fig.add_subplot(projection='3d')
ani = FuncAnimation(fig = fig, func = update, frames = 100, interval = 100)
plt.show()
完整代码
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
def update(t):
ax.cla()
x = np.cos(t/10)
y = np.sin(t/10)
z = 5
ax.scatter(x, y, z, s = 100, marker = 'o')
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_zlim(-1, 10)
fig = plt.figure(dpi=100)
ax = fig.add_subplot(projection='3d')
ani = FuncAnimation(fig = fig, func = update, frames = 100, interval = 100)
plt.show()
如果你还想跟踪粒子轨迹,可以添加X、Y和Z列表来保存粒子坐标:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
X = []
Y = []
Z = []
def update(t):
ax.cla()
x = np.cos(t/10)
y = np.sin(t/10)
z = t/10
X.append(x)
Y.append(y)
Z.append(z)
ax.scatter(x, y, z, s = 100, marker = 'o')
ax.plot(X, Y, Z)
ax.set_xlim(-2, 2)
ax.set_ylim(-2, 2)
ax.set_zlim(-1, 10)
fig = plt.figure(dpi=100)
ax = fig.add_subplot(projection='3d')
ani = FuncAnimation(fig = fig, func = update, frames = 100, interval = 100, repeat = False)
plt.show()