我是slowly learning如何使用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
应为[1; 10]中的每个i
添加一个新栏,从10个柱开始,然后是11个,......,最后是20个。
问题:我该怎么办?
由于
答案 0 :(得分: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()