2014-02-27 83 views
1

我是slowlylearning如何用matplotlib動畫數字。現在,我有一個條形圖,我想在每個新框架中添加一個新框(並調整其他框的寬度和高度)。在matplotlib動畫的每次迭代中添加新的箱子

這是我到目前爲止所做的。

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() 

所以,在上面的代碼中,animate應添加每i一個新的條[1; 10],從10巴,然後11,...,以及最後20

問題:我該怎麼辦?

感謝

回答

2

你可以做這樣的事情:

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() 
相關問題