Matplotlib从图中删除所有补丁

Nyp*_*yps 3 python matplotlib

我试图在图像流的顶部绘制各种矩形。在显示下一个图像之前,应再次删除所有以前的矩形。

通过这个问题,我找到了第一个可能的解决方案。下面是我目前正在做的简化示例。

fig, ax = plt.subplots(1)
im = ax.imshow(np.zeros((800, 800, 3)))

for i in range(100):
    img = plt.imread('my_image_%03d.png' % i)
    im.set_data(img)

    rect_lst = getListOfRandomRects(n='random', dim=img.shape[0:2])
    patch_lst = [patches.Rectangle((r[0], r[1]), r[2], r[3],
                                   linewidth=1, facecolor='none')
                 for r in rect_lst]
    [ax.add_patch(p) for p in patch_lst]
    plt.pause(0.1)
    plt.draw()
    [p.remove() for p in patch_lst]
Run Code Online (Sandbox Code Playgroud)

我对此不满意的是,我必须跟踪patch_lst以便再次删除它们。我宁愿简单地删除所有补丁并获得如下信息:

for i in range(100):
    [...]

    rect_lst = getListOfRandomRects(n='random', dim=img.shape[0:2])
    [ax.add_patch(patches.Rectangle((r[0], r[1]), r[2], r[3],
                                    linewidth=1, facecolor='none'))
                 for r in rect_lst]

    plt.pause(0.1)
    plt.draw()
    ax.clear_all_patches()       # <-- this is what I am looking for
Run Code Online (Sandbox Code Playgroud)

我确实尝试过ax.clear(),但是这也会删除基础图像。有什么建议么?

Dav*_*idG 6

一种可能的方法是使用来获取补丁列表ax.patches。因此,您可以使用现有的列表理解功能来删除列表中的补丁,而可以将列表替换为ax.patches()

for i in range(100):
    [...]

    rect_lst = getListOfRandomRects(n='random', dim=img.shape[0:2])
    [ax.add_patch(patches.Rectangle((r[0], r[1]), r[2], r[3],
                                    linewidth=1, facecolor='none'))
                 for r in rect_lst]

    plt.pause(0.1)
    plt.draw()
    [p.remove() for p in reversed(ax.patches)]
Run Code Online (Sandbox Code Playgroud)