Daniel
Daniel

Reputation: 450

Python Matplotlib FuncAnimation + Saving

I am new to python and I'm trying to make an animation and save it into some video format using matplotlibs FuncAnimation. 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 an error that says:

ValueError: outfile must be *.htm or *.html

As this seems to have something to do with the ffmpeg files - these are located in

/anaconda3/bin/ffmpeg

I have been on this for quite some time now but can't seem to figure out a solution though it seems to be common issue. Thankful for any suggestions.

Upvotes: 3

Views: 12600

Answers (1)

dudakl
dudakl

Reputation: 302

I have never worked with FuncAnimation bevore, but the matplotlib-example states, you have to initialize ffmpeg first. 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)

Maybe, you could give this a try.

Upvotes: 3

Related Questions