Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib remove all patches from figure

I am trying to plot various rectangles on top of an image stream. Before displaying the next image, all former rectangles should be removed again.

From this question I found a first possible solution. Below is a simplified example of what I am doing at the moment.

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]

What I don't like about this is that I have to keep track of of the patch_lst in order to remove them again. I would prefer to simply remove all patches and get something like this:

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

I did try ax.clear(), however this also removes the underlying image. Any suggestions?

like image 860
Nyps Avatar asked Apr 12 '18 08:04

Nyps


1 Answers

One possible way is to get a list of the patches using ax.patches. Therefore, you can use the existing list comprehension that you use to remove the patches using your list, but instead replace the list with 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)]
like image 83
DavidG Avatar answered Oct 14 '22 05:10

DavidG