8

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()
Eular
  • 1,707
  • 4
  • 26
  • 50
  • Check this question: http://stackoverflow.com/questions/15443879/saving-scatterplot-animations-with-matplotlib-produces-blank-video-file – armatita May 10 '16 at 20:45
  • Duplicate of http://stackoverflow.com/questions/42258439/saving-matplotlib-animation-outputs-a-0-second-video – ImportanceOfBeingErnest May 18 '17 at 23:22
  • Does this answer your question? [Saving matplotlib.animation outputs a 0 second video](https://stackoverflow.com/questions/42258439/saving-matplotlib-animation-outputs-a-0-second-video) – ClimateUnboxed Dec 16 '21 at 15:54

2 Answers2

4

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

abarry
  • 425
  • 3
  • 16
Marziyeh Askari
  • 175
  • 1
  • 8
1

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,
Engr1hmh
  • 41
  • 3