【问题标题】:Matplotlib remove patches from figureMatplotlib 从图中删除补丁
【发布时间】:2014-03-08 09:30:20
【问题描述】:

就我而言,我想在单击重置按钮时删除其中一个圆圈。但是, 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()

【问题讨论】:

    标签: python matplotlib interactive


    【解决方案1】:

    不同的选项是这个

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

    它会删除所有补丁。这个选项对于 Matplotlib AttributeError: can't set attribute

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

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

    【讨论】:

    • 不知道为什么,但对我来说,patch.remove() 没有工作,而这工作得很好。谢谢!
    【解决方案2】:

    我也尝试了答案 1,虽然它在这种情况下确实有效,但在我自己的代码中却不起作用。有效的是在将补丁添加到轴后删除补丁对象,而不是原始补丁对象,如下所示:

    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()
    

    否则我得到 NotImplementedError('cannot remove artist') 错误。

    【讨论】:

      【解决方案3】:

      试试这个:

      def reset(event):
          circle1.remove()
      

      也许你更喜欢:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-28
        • 2020-12-11
        • 2019-04-20
        • 1970-01-01
        • 2019-02-20
        • 1970-01-01
        • 1970-01-01
        • 2011-10-19
        相关资源
        最近更新 更多