将matplotlib动画保存为mp4

时间:2016-05-10 18:38:03

标签: python animation matplotlib

我想在mp4中保存以下程序的输出动画。该程序确实创建了一个mp4文件,但该文件是一个空白文件,它不包含我想要的动画。我在这里做错了什么?

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.animation as animation

plt.rcParams['animation.ffmpeg_path'] ='C:\\ffmpeg\\bin\\ffmpeg.exe'
fig=plt.figure()
ax=fig.add_subplot(111,projection="3d")

x=np.linspace(100,150,100)
t=(x-100)/0.5
y=-.01*np.cos(t)+.5*np.sin(t)+100.01
z=.01*np.sin(t)+.5*np.cos(t)+99.5

def animate(i):
    line.set_data(x[:i],y[:i])
    line.set_3d_properties(z[:i])

ax.set_xlim3d([min(x),max(x)])
ax.set_ylim3d([min(y),max(y)])
ax.set_zlim3d([min(z),max(z)])
ax.set_title("Particle in magnetic field") 
ax.set_xlabel("X")
ax.set_xlabel("Y")
ax.set_xlabel("Z")
line,=ax.plot([],[],[])
lin_ani=animation.FuncAnimation(fig,animate)
plt.legend()

FFwriter = animation.FFMpegWriter()
lin_ani.save('animation.mp4', writer = FFwriter, fps=10)
# plt.show()

1 个答案:

答案 0 :(得分:0)

在函数末尾添加这一行

return line,

所以一个完整的函数应该是这样的:

def animate(i):
    line.set_data(x[:i],y[:i])
    line.set_3d_properties(z[:i])
    return line,
相关问题