1

Regards, I would like to ask about Python's FuncAnimation.

In the full code, I was trying to animate bar plots (for integral illustration). The animated output from

ani = FuncAnimation(fig, update, frames=Iter, init_func = init, blit=True);
plt.show(ani);

looks fine.

But the output video from

ani.save("example_new.mp4", fps = 5)

gives a slightly different version from the animation showed in Python. The output gives a video of 'superposition version' compared to the animation. Unlike the animation : in the video, at each frame, the previous plots kept showing together with the current one.

Here is the full code :

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation


fig, ax = plt.subplots()
Num = 20
p = plt.bar([0], [0], 1, color = 'b')
Iter = tuple(range(2, Num+1))
xx = list(np.linspace(0, 2, 200)); yy = list(map(lambda x : x**2,xx));

def init(): 
    ax.set_xlim(0, 2)
    ax.set_ylim(0, 4)
    return (p)

def update(frame):
    w = 2/frame;
    X = list(np.linspace(0, 2-w, frame+1));
    Y = list(map(lambda x: x**2, X));
    X = list(map(lambda x: x + w/2,X));
    C = (0, 0, frame/Num); 
    L = plt.plot(xx , yy, 'y', animated=True)[0]
    p = plt.bar(X, Y, w, color = C, animated=True)
    P = list(p[:]); P.append(L)   
    return P

ani = FuncAnimation(fig, update, frames=Iter, init_func = init, interval = 0.25, blit=True)
ani.save("examplenew.mp4", fps = 5)
plt.show(ani)

Any constructive inputs on this would be appreciated. Thanks. Regards, Arief.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • When I save it this way and try to open the .mp4 on a mac I get a "QuickTime Player can't open" error. – PlsWork Jul 02 '19 at 13:30

1 Answers1

0

When saving the animation, no blitting is used. You can turn off blitting, i.e. blit=False and see the animation the same way as it is saved.

What is happening is that in each iteration a new plot is added without the last one being removed. You basically have two options:

  1. Clear the axes in between, ax.clear() (then remember to set the axes limits again)
  2. update the data for the bars and the plot. Examples to do this:
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Regards @User. Thanks for the input. The code `ax.clear()` works fine and does not produce superpositions to the output video. The bars and plots are already updated inside the `update` function, since this is the function called at each frame. Inside the `update` function, i also put axes limits from the `init` after the `ax.clear()`. –  May 25 '17 at 09:31