0

I am trying to plot the animation of bar plots updating their values in colab using matplotlib animations.

def barlist(n): 
     return val[n]

fig=plt.figure()

n=100 #Number of frames
x=range(16)
barcollection = plt.bar(x, barlist(0))

def animate(i):
    y = barlist(i+1)
    for i, b in enumerate(barcollection):
        b.set_height(y[i])

anim=animation.FuncAnimation(fig,animate,blit=False,repeat=False,frames=100, interval=10)

anim.save('movie.mp4',writer=animation.FFMpegWriter(fps=10))

Here is sample of first 5 of 142 values of val array. The range of y values is 0 to -25 and the range of x values range from 0 to 15.

[array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),
 array([ 0.       , -1.       , -1.25     , -1.3125   , -1.       ,
        -1.5      , -1.6875   , -1.75     , -1.25     , -1.6875   ,
        -1.84375  , -1.8984375, -1.3125   , -1.75     , -1.8984375,
         0.       ]),
 array([ 0.        , -1.9375    , -2.546875  , -2.73046875, -1.9375    ,
        -2.8125    , -3.23828125, -3.40429688, -2.546875  , -3.23828125,
        -3.56835938, -3.21777344, -2.73046875, -3.40429688, -3.21777344,
         0.        ]),
 array([ 0.        , -2.82421875, -3.83496094, -4.17504883, -2.82421875,
        -4.03125   , -4.7097168 , -4.87670898, -3.83496094, -4.7097168 ,
        -4.96374512, -4.26455688, -4.17504883, -4.87670898, -4.26455688,
         0.        ]),
 array([ 0.        , -3.67260742, -5.0980835 , -5.58122253, -3.67260742,
        -5.19116211, -6.03242493, -6.18872833, -5.0980835 , -6.03242493,
        -6.14849091, -5.15044403, -5.58122253, -6.18872833, -5.15044403,
         0.        ])]

Pastebin link to all 142 values. Tried all the solutions from similar SO questions 1 and 2.

image

The problem is the mp4 video just shows 1 plot shown above and it does not update the values of bar plot in subsequent frames.

SupposeXYZ
  • 374
  • 5
  • 15

1 Answers1

0

I'm not sure why the method you're using fails to produce the expected output, but clearing and redrawing the plot seems to work correctly:

def barlist(n): 
    return val[n]

fig=plt.figure()
n=100 #Number of frames
x=range(16)
ylim = [-10, 0]
barcollection = plt.bar(x, barlist(0))
plt.ylim(ylim)

def animate(i):
    y = barlist(i+1)
    plt.cla()
    bar = plt.gca().bar(x, barlist(i))
    plt.ylim(ylim)

anim=animation.FuncAnimation(fig,animate, blit=False, repeat=False, frames=4)
anim.save('movie.mp4', writer=animation.FFMpegWriter(fps=1))

enter image description here

William Miller
  • 9,839
  • 3
  • 25
  • 46