Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving matplotlib animation as mp4

I want to save the output animation of the following program in mp4. The program does create a mp4 file, but the file is a blank file it does not contain the animation I wanted. What am I doing wrong here?

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()
like image 387
Eular Avatar asked Feb 26 '26 06:02

Eular


2 Answers

As I learn up to know, you should write like this:

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

I learned this from this site1

like image 195
Marziyeh Askari Avatar answered Feb 27 '26 19:02

Marziyeh Askari


Add this line at the end of your function

return line,

so a complete function should look like:

def animate(i):
    line.set_data(x[:i],y[:i])
    line.set_3d_properties(z[:i])
    return line,
like image 31
Engr1hmh Avatar answered Feb 27 '26 20:02

Engr1hmh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!