Python Matplotlib FuncAnimation + save … here is a solution to the problem.
Python Matplotlib FuncAnimation + save
I’m new to python and I’m trying to animate using matplotlibs FuncAnimation and save it in some kind of video format. If I run the following code:
import numpy as np
import matplotlib.animation as ani
import matplotlib.pyplot as plt
azimuths = np.radians(np.linspace(0, 360, 360))
zeniths = np.arange(0, 8, 0.2)
rho, psi = np.meshgrid(zeniths, azimuths)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, polar=True)
ax.set_yticks([])
plt.grid()
def frame(i):
values_i = prob_density(rho ** 2, psi, i)
ax.contourf(psi, rho, values_i)
animation = ani. FuncAnimation(fig, frame, np.linspace(0, 1000, 10))
animation.save('video.mp4', writer='ffmpeg')
There is a bug that says:
ValueError: outfile must be *.htm or *.html
Because this seems to be related to ffmpeg files – these files are located
/anaconda3/bin/ffmpeg
I’ve been looking into this for a long time now but can’t seem to find a solution, although it seems to be a common problem. Thank you for any suggestions.
Solution
I’ve never used FuncAnimation before, but matplotlib-example state, you must first initialize ffmpeg. Like this:
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_line(num, data, line):
line.set_data(data[..., :num])
return line,
# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
fig1 = plt.figure()
data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation. FuncAnimation(fig1, update_line, 25, fargs=(data, l),
interval=50, blit=True)
line_ani.save('lines.mp4', writer=writer)
Perhaps, you can try this.