簡體   English   中英

Matplotlib從圖中刪除所有補丁

[英]Matplotlib remove all patches from figure

我試圖在圖像流的頂部繪制各種矩形。 在顯示下一個圖像之前,應再次刪除所有以前的矩形。

這個問題我發現了第一個可能的解決方案。 以下是我目前所做工作的簡化示例。

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]

我不喜歡這個是我必須跟蹤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

我確實嘗試過ax.clear() ,但這也刪除了底層圖像。 有什么建議?

一種可能的方法是使用ax.patches獲取補丁列表。 因此,您可以使用現有的列表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)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM