如何在 matplotlib 动画中跟踪 patches.Rectangle 对象的路径?

How to trace the path of a patches.Rectangle object in matplotlib animation?

我正在尝试使用 matplotlib 为一个简单的 patches.Rectangle 对象制作动画。我想在动画中绘制由所述对象(或其滑动的区域)追踪的路径。我可以看到人们通过将单个粒子的所有先前位置附加到列表来追踪单个粒子的路径,但我不确定如何为 Rectangle 执行此操作。

一种方法(我猜)是在新位置绘制矩形,而不从之前的帧中清除矩形。但是我不知道该怎么做。

我正在使用以下代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import animation

# x and y go from 0 to 1 in 100 steps
x = [i/100 for i in range(100)]
y = [i/100 for i in range(100)]

# Angle goes from 0 to pi/2 in 100 steps
orientation = [(1.57)*i/100 for i in range(100)]

fig = plt.figure()
plt.axis('equal')
plt.grid()
ax = fig.add_subplot(111)
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)

patch = patches.Rectangle((0, 0), 0, 0, fc='r')


def init():
    ax.add_patch(patch)
    return patch,


def animate(i):
    patch.set_width(5.0)
    patch.set_height(2.0)
    patch.set_xy([x[i], y[i]])
    patch.angle = np.rad2deg(orientation[i])
    return patch,


anim = animation.FuncAnimation(fig, animate, init_func=init, frames=len(x),
                               interval=5, blit=True, repeat_delay=500)

plt.show()

换句话说,除了矩形移动之外,我还想看到矩形移动时的轨迹。理想情况下,该解决方案也应该很容易适用于其他面片对象(多边形、椭圆等)。

要保持​​动画中的对象,不需要初始化,只需将对象添加到一个空列表中,指定为Patch_collection,并设置为add_collection( ).我相信这也可以转移到其他对象上;可以找到 PatchCollection 的参考示例 here.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import animation
from matplotlib.collections import PatchCollection

# x and y go from 0 to 1 in 100 steps
x = [i/100 for i in range(100)]
y = [i/100 for i in range(100)]

# Angle goes from 0 to pi/2 in 100 steps
orientation = [(1.57)*i/100 for i in range(100)]

fig = plt.figure()
plt.axis('equal')
plt.grid()
ax = fig.add_subplot(111)
ax.set_xlim(-10, 10)
ax.set_ylim(-10, 10)

patch = patches.Rectangle((0, 0), 0, 0, fc='r')

def init():
    ax.add_patch(patch)
    return patch,

items = []
def animate(i):
    patch.set_width(5.0)
    patch.set_height(2.0)
    patch.set_xy([x[i], y[i]])
    patch.angle = np.rad2deg(orientation[i])
    items.append(patch)
    fig = ax.add_collection(PatchCollection(items, fc='r', ec='white', alpha=x[i]))
    return fig,

anim = animation.FuncAnimation(fig, animate, frames=len(x), interval=200, blit=True, repeat=False)

plt.show()