Furkan Toprak
Furkan Toprak

Reputation: 121

Saving matplotlib animation as movie; movie too short

I have an animation that I made with matplotlib that I'm saving using matplotlib.animation.Animation.save(). This works well, but my movie ends before my animation ends.

I've tried changing frame rate, interval, and movie format from .mp4 to .avi. Is there a frame or movie size limit? How could this be fixed?

Here is my code:

# Updates animation.
def update_line(num, data, line):
    line.set_data(data[..., :num])
    return line,


fig1 = plt.figure()
l, = plt.plot([], [], '-')
line_ani = animation.FuncAnimation(fig1, update_line, fargs=(np.array(trajectory), l), interval=25, blit=True)

line_ani.save(file_title + '.avi')
plt.show()

While the movie should be about 15 seconds long, it ends up being 3 seconds long. I also use plt.show(), and the animation is much longer on the matplotlib display window.

In case it matters, I'm running on Ubuntu, with matplotlib 3.03 and python 3.6.

Upvotes: 1

Views: 1571

Answers (2)

wcroughan
wcroughan

Reputation: 154

For anyone else who found this and OP's answer did not work, here's the solution that worked for me:

When creating the FuncAnimation object, add the named parameter save_count, which tells the animator how many frames to save when save() is called.

Here's the one from my code:

self.ani = anim.FuncAnimation(self.fig, lambda i: self.animate(i), frames=self.update_time, repeat=False, init_func=self.init_plot, interval=self._frame_len, save_count=self._max_frame)

A bonus is that this also lets you keep your frames argument as a function (i.e. for interactivity when you call plt.show() instead of save()).

Source: https://holypython.com/how-to-save-matplotlib-animations-the-ultimate-guide/

Upvotes: 1

Furkan Toprak
Furkan Toprak

Reputation: 121

Edit: I was able to fix this by making the parameter frames=len(trajectory[1]).

In short, if you can predict the length of your movie in frames, use repeat=False and frames=number_of_frames as parameters to .save().

Leaving this answer up for others to fix their bugs.

Upvotes: 0

Related Questions