简体   繁体   English

Matplotlib 从图中删除补丁

[英]Matplotlib remove patches from figure

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.但是, ax.clear() 会清除当前图形上的所有圆圈。

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不同的选项是这个

ax.patches = []

it removes all the patches.它删除所有补丁。

I tried answer 1 as well, while it does work in this context it didn't work in my own code.我也尝试了答案 1,虽然它在这种情况下有效,但在我自己的代码中无效。 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.否则我会收到 NotImplementedError('cannot remove Artist') 错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM