简体   繁体   English

使用 matplotlib 的条形图动画

[英]Bar-plot animation using matplotlib

I am trying to plot the animation of bar plots updating their values in colab using matplotlib animations.我正在尝试绘制条形图的动画,使用 matplotlib 动画在 colab 中更新它们的值。

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.这是val数组的 142 个值中的前 5 个值的示例。 The range of y values is 0 to -25 and the range of x values range from 0 to 15. y 值的范围是 0 到 -25,x 值的范围是 0 到 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. Pastebin链接到所有 142 个值。 Tried all the solutions from similar SO questions 1 and 2 .尝试了类似 SO 问题12 中的所有解决方案。

图片

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.问题是 mp4 视频只显示上面显示的 1 个图,它不会更新后续帧中条形图的值。

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))

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM