我使用matplotlib制作的动画图不动

rta7y2nd  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(290)

我有一个形状为(18,101)的数组X_trj要在3D中绘制(它们是三个不同车辆的轨迹),我尝试通过执行以下操作来动画绘制:

#animate the plot:
import matplotlib.animation as animation

# First, create a function that updates the scatter plot for each frame
def update_plot(n,X_trj,scatters):
    # Set the data for each scatter plot
    scatters[0].set_offsets(np.stack((X_trj[0, :n], X_trj[1, :n], X_trj[2, :n]), axis=1))
    scatters[1].set_offsets(np.stack((X_trj[6, :n], X_trj[7, :n], X_trj[8, :n]), axis=1))
    scatters[2].set_offsets(np.stack((X_trj[12,:n], X_trj[13, :n], X_trj[14,:n]), axis=1))
    return scatters

# Create the figure and axis
fig = plt.figure()
ax = plt.axes(projection='3d')

# Create the scatter plots
scatters = []
scatters.append(ax.scatter(X_trj[0,:], X_trj[1,:], X_trj[2,:]))
scatters.append(ax.scatter(X_trj[6,:], X_trj[7,:], X_trj[8,:]))
scatters.append(ax.scatter(X_trj[12,:], X_trj[13,:], X_trj[14,:]))

# Set the title
ax.set_title('Trajectory from one-shot optimization (human + drones)')

ani = animation.FuncAnimation(fig, update_plot, frames=range(X_trj.shape[1]), fargs=(X_trj, scatters))

plt.show()
ani.save('animation.mp4')

在运行代码后,我得到了下面的图:

然而,当我打开mp4文件时,我的动画没有移动。它和我得到的静态图完全一样。任何帮助都非常感谢!

41zrol4v

41zrol4v1#

不清楚您从哪里复制了起始代码。大多数示例使用ax.plot而不是ax.scatter。旧代码可能会在更新的matplotlib版本中过时。
无论如何,你在初始化时已经填充了完整的最终轨迹。相反,你应该创建一个空的图,并手动设置x,y和z的限制。

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

# first, fill X_trj with some test data
n = 2000
X_trj = np.random.randn(15, n).cumsum(axis=1)

# second, create a function that updates the scatter plot for each frame
def update_plot(k, X_trj, scatters):
     # Set the data for each scatter plot
     scatters[0]._offsets3d = X_trj[0:3, :k]
     scatters[1]._offsets3d = X_trj[6:9, :k]
     scatters[2]._offsets3d = X_trj[12:15, :k]
     return scatters

# Create the figure and axis
fig = plt.figure()
ax = plt.axes(projection='3d')

# Create the scatter plots
scatters = []
scatters.append(ax.scatter([], [], []))
scatters.append(ax.scatter([], [], []))
scatters.append(ax.scatter([], [], []))

# set the axis limits
ax.set_xlim3d(X_trj[[0, 6, 12], :].min(), X_trj[[0, 6, 12], :].max())
ax.set_ylim3d(X_trj[[1, 7, 13], :].min(), X_trj[[1, 7, 13], :].max())
ax.set_zlim3d(X_trj[[2, 8, 14], :].min(), X_trj[[2, 8, 14], :].max())

# Set the title
ax.set_title('Trajectory from one-shot optimization (human + drones)')

ani = animation.FuncAnimation(fig, update_plot, frames=n, fargs=(X_trj, scatters))

ani.save('animation.mp4')
plt.show()

相关问题