Matplotlib从图中删除补丁

Ide*_*ist 16 python interactive matplotlib

在我的情况下,我想在单击重置按钮时删除其中一个圆圈.但是,ax.clear()会清除当前数字上的所有圆圈.

有人能告诉我如何只删除部分补丁吗?

import matplotlib.patches as patches
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

fig = plt.figure()
ax = fig.add_subplot(111) 

circle1 = patches.Circle((0.3, 0.3), 0.03, fc='r', alpha=0.5)
circle2 = patches.Circle((0.4, 0.3), 0.03, fc='r', alpha=0.5)
button = Button(plt.axes([0.8, 0.025, 0.1, 0.04]), 'Reset', color='g', hovercolor='0.975')
ax.add_patch(circle1)
ax.add_patch(circle2)

def reset(event):
    '''what to do here'''
    ax.clear()

button.on_clicked(reset)
plt.show()
Run Code Online (Sandbox Code Playgroud)

Alv*_*tes 17

试试这个:

def reset(event):
    circle1.remove()
Run Code Online (Sandbox Code Playgroud)

也许您更喜欢:

def reset(event):
    circle1.set_visible(False)
Run Code Online (Sandbox Code Playgroud)


zwe*_*wep 7

不同的选项是这个

def reset(event):
    ax.patches = []
Run Code Online (Sandbox Code Playgroud)

它会删除所有补丁。此选项适用于 Matplotlib < 3.5.0。使用 Matplotlib 3.5.0 你会得到错误AttributeError: can't set attribute

在这种情况下,您可以使用以下选项

def reset(event):
    ax.patches.pop()
    # Statement below is optional
    fig.canvas.draw()
Run Code Online (Sandbox Code Playgroud)