【问题标题】:Animate multiple shapes in python3 using matplotlib使用matplotlib在python3中为多个形状制作动画
【发布时间】:2017-01-12 09:35:53
【问题描述】:

尝试在 python3 中使用 matplotlib 动画功能一次为多个对象设置动画。

下面写的代码是我到目前为止的位置。我能够创建多个对象并将它们显示在图中。我通过使用包含矩形补丁函数的 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' object has no attribute 'set_animated''。

【问题讨论】:

  • 你确定它必须是set_XY = temp - 而不是set_XY(temp)
  • 放示例链接。并且总是对完整的错误信息(Traceback)提出质疑——不仅仅是最后一部分。还有其他有用的信息。 IE。哪一行有问题。

标签: python python-3.x animation matplotlib


【解决方案1】:

你必须使用

 RB[i].set_xy(temp)

而不是set_XY = temp

【讨论】:

  • 成功了,谢谢。现在正在制作动画。虽然看起来它并没有一下子动起来。但我可能会使用我设置的帧和间隔。
【解决方案2】:

RB 中的索引实际上是错误的。您应该将动画功能更改为:

def animate(i):
    for a in range(bars):
        temp = RB[a].get_x() + 3
        RB[a].set_x(temp)
    return RB

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 2011-01-07
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多