我正在尝试为一系列圆圈设置动画,以便它们随着时间的推移而改变颜色。以下代码生成单帧的示例:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
nx = 20
ny = 20
fig = plt.figure()
plt.axis([0,nx,0,ny])
ax = plt.gca()
ax.set_aspect(1)
for x in range(0,nx):
for y in range(0,ny):
ax.add_patch( plt.Circle((x+0.5,y+0.5),0.45,color='r') )
plt.show()
如何定义函数init()和animate(),以便我可以使用例如:。生成动画:
animation.FuncAnimation(fig, animate, initfunc=init,interval=200, blit=True)
答案 0 :(得分:5)
您可以在动画中更改为圆圈的颜色,如下所示:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
nx = 20
ny = 20
fig = plt.figure()
plt.axis([0,nx,0,ny])
ax = plt.gca()
ax.set_aspect(1)
def init():
# initialize an empty list of cirlces
return []
def animate(i):
# draw circles, select to color for the circles based on the input argument i.
someColors = ['r', 'b', 'g', 'm', 'y']
patches = []
for x in range(0,nx):
for y in range(0,ny):
patches.append(ax.add_patch( plt.Circle((x+0.5,y+0.5),0.45,color=someColors[i % 5]) ))
return patches
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=10, interval=20, blit=True)
plt.show()