cjorssen
cjorssen

Reputation: 1007

Add new bins at each iteration of a bar plot animation

I'm slowly learning how to animate figures with matplotlib. Now, I have a bar plot, and I'd like to add a new bin every new frame (and adapt the width and height of the others).

Here is what I've done so far.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

fig = plt.figure()

ax = plt.subplot(1,1,1)

N = 10

plt.xlim(0,10)
plt.ylim(0,10)

x = np.arange(N)
y = np.zeros(N)

bars = plt.bar(x,y,1)

for bar in bars:
    ax.add_patch(bar)

def init():
    for bar in bars:
        bar.set_height(0.)
    return [bar for bar in bars]

# animation function.  This is called sequentially
def animate(i):
    for j, bar in enumerate(bars):
        bar.set_height(j+i)
        bar.set_width(bar.get_width()/float(i+1))
    return [bar for bar in bars]

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames = 10, interval=200, blit=True)
plt.show()

So, in the code above, animate should add a new bar for every i in [1;10], starting with 10 bars, then 11, ... , and finally 20.

Question: How can I do?

Thanks

Upvotes: 1

Views: 282

Answers (1)

Alvaro Fuentes
Alvaro Fuentes

Reputation: 17475

You can do something like this:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

fig = plt.figure()

ax = plt.subplot(1,1,1)

N = 10
M = 10

plt.xlim(0,N+M)
plt.ylim(0,N+M)

x = np.arange(N+M)
y = np.arange(N+M)

bars = [b for b in plt.bar(x[:N],y[:N],1)]

def init():
    return bars

# animation function.  This is called sequentially
def animate(i):
    if i<M:
        bars.append(plt.bar(x[N+i],y[N+i],1)[0]) 
    return bars
    
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames = 10, interval=200, blit=True)
plt.show()

enter image description here

Upvotes: 3

Related Questions