I want to create an animated, stacked bar chart.
There is a great tutorial, which shows how to animate line graphs.
However, for animating bar charts, the BarContainer object, does not have any attribute to 'set_data'. I am therefore forced to clear the figure axes each time, e.g. ,
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)
Is there an alternative option, following the style of the link, such that I do not have to clear the axes each time? Thanks.
You'll want to call plt.bar
outside of animation()
, update the height of each bar with Rectangle.set_height
as new data comes in.
In practice, loop through each incoming set of y_heights zipped with the list of Rectangles returned by plt.bar() as seen below.
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)
You might want to put p1
in your init()
but that's up to you!
All credit for this answer goes to unutbu's answer in the related question Updating a matplotlib bar graph?. I would've added in a comment but I'm obviously quite new.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With