문제

In my case, I want to remove one of the circle when clicking reset button. However, ax.clear() would clear all circles on the current figure.

Can someone tell me how to remove only part of the patches?

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()
도움이 되었습니까?

해결책

Try this:

def reset(event):
    circle1.remove()

Also maybe you prefer:

def reset(event):
    circle1.set_visible(False)

다른 팁

Different options is this

def reset(event):
    ax.patches = []

it removes all the patches. This option was viable for Matplotlib < 3.5.0. With Matplotlib 3.5.0 you get the error AttributeError: can't set attribute

In that case, you can use the following option

def reset(event):
    ax.patches.pop()
    # Statement below is optional
    fig.canvas.draw()

I tried answer 1 as well, while it does work in this context it didn't work in my own code. What worked was to remove the patch object after adding the patch to the axis, rather than the original patch object, like this:

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')
c1=ax.add_patch(circle1)
c2=ax.add_patch(circle2)

def reset(event):
    c1.remove()

button.on_clicked(functools.partial(reset,patch=c1))
plt.show()

otherwise I got NotImplementedError('cannot remove artist') error.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top