使用matplotlib的条形图动画

2024-09-29 17:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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))

下面是val数组142个值中的前5个的示例。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.        ])]

link粘贴到所有142个值。尝试了类似SO问题12的所有解决方案

image

问题是mp4视频只显示了上面显示的1个绘图,它不会在后续帧中更新条形图的值


Tags: falseframesdeffig动画pltvalarray
1条回答
网友
1楼 · 发布于 2024-09-29 17:15:54

我不确定为什么您使用的方法无法产生预期的输出,但清除和重新绘制绘图似乎工作正常:

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

相关问题 更多 >

    热门问题