如何为在 Python 中更新的条形字符设置动画

use*_*919 5 python animation matplotlib

我想创建一个动画的堆积条形图。

有一个很棒的教程,它展示了如何为折线图制作动画。

但是,对于动画条形图,BarContainer 对象没有“set_data”的任何属性。因此,我每次都被迫清除图形轴,例如,

fig=plt.figure()

def init():
    plt.cla()

def animate(i):

    p1 = plt.bar(x_points,y_heights,width,color='b')

return p1


anim = animation.FuncAnimation(fig,animate,init_func=init,frames=400,interval=10,blit=False)
Run Code Online (Sandbox Code Playgroud)

是否有另一种选择,遵循链接的样式,这样我就不必每次都清除轴?谢谢。

小智 5

您需要plt.bar在 之外调用,并在新数据传入时animation()更新每个条形的高度。Rectangle.set_height

在实践中,循环遍历每个传入的 y_heights 集合,这些 y_heights 与 plt.bar() 返回的矩形列表压缩在一起,如下所示。

p1 = plt.bar(x_points,y_heights,width,color='b')

def animate(i):
    for rect, y in zip(p1, y_heights):
        rect.set_height(y)

anim = animation.FuncAnimation(fig,animate,init_func=init,frames=400,interval=10,blit=False)
Run Code Online (Sandbox Code Playgroud)

您可能想放入p1您的init(),但这取决于您!

这个答案的所有功劳都归功于unutbu在相关问题Updating a matplotlib bar graph?中的答案。。我本来会添加评论,但我显然是个新人。


小智 0

plt.bar返回矩形列表。列表的长度等于条的数量。如果您想更改第一个条形的高度,您可以对其他矩形属性进行p1[0].set_height(new_height)类似的操作。width

如此处所述的输出[x for x in dir(p1[0]) if 'set_' in x]将为您提供可以设置的所有潜在属性。