在使用 matplotlib 动画功能时尝试在 python3 中同时为多个对象设置动画。
下面写的代码是我到目前为止的地方。我能够创建多个对象并将它们显示在图中。我通过使用包含矩形补丁函数的 for 循环来完成此操作。从这里开始,我希望通过使用动画功能将所有单个矩形移动一定量。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.animation as animation
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim(-100, 100)
plt.ylim(-100, 100)
width = 5
bars = 25
RB = [] # Establish RB as a Python list
for a in range(bars):
RB.append(patches.Rectangle((a*15-140,-100), width, 200,
color="blue", alpha=0.50))
def init():
for a in range(bars):
ax.add_patch(RB[a])
return RB
def animate(i):
for a in range(bars):
temp = np.array(RB[i].get_xy())
temp[0] = temp[0] + 3;
RB[i].set_XY = temp
return RB
anim = animation.FuncAnimation(fig, animate,
init_func=init,
frames=15,
interval=20,
blit=True)
plt.show()
目前,一旦我运行代码,没有任何变化或发生任何事情。我试图按照 python 网站上的示例进行操作;但它通常会导致“AttributeError:‘list’对象没有属性‘set_animated’”。
请您参考如下方法:
你必须使用
RB[i].set_xy(temp)
代替 set_XY = temp
