user1887919
user1887919

Reputation: 923

How to animate a bar char being updated in Python

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.

Upvotes: 7

Views: 4561

Answers (2)

T. Hoyt
T. Hoyt

Reputation: 51

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.

Upvotes: 5

hugke729
hugke729

Reputation: 351

plt.bar returns a list of Rectangles. The length of the list is equal to the number of bars. If you wanted to change the height of say the first bar, you can do p1[0].set_height(new_height) and similarly for width and a bunch of other Rectangle properties.

As noted here, the output of [x for x in dir(p1[0]) if 'set_' in x] will give you all the potential properties you can set.

Upvotes: 0

Related Questions