【问题标题】:Python and Remove annotation from figurePython并从图中删除注释
【发布时间】:2012-08-31 21:00:05
【问题描述】:

我在 wxpython GUI 中使用 matplotlib。简而言之,我绘制了一堆数据。然后我单击一个数据点(使用位于以下位置的 DataCursor:

Is there a matplotlib equivalent of MATLAB's datacursormode?

Pop up annotations on matplotlib within wxPython

第二个链接是我的实际实现。我从其他类中重新定义了 datacursor 类。我想知道,如何通过单击事件按钮来删除注释?例如,我有一个更新我的散点图的事件按钮(通过使用 plot_handle.set_data 而不是通过清除图形)。但是,无论该点是否存在,注释都会准确地保留在原来的位置。怎么去掉?

谢谢!

【问题讨论】:

    标签: python annotations matplotlib


    【解决方案1】:

    大多数 matplotlib 对象都有一个 remove() 函数(我认为它继承自 Artist)。只需在要删除的对象上调用它即可。

    编辑:

    如果你有

    dc = DataCursor(...) # what ever aruguements you give it
    # bunch of code
    dc.annotation.remove()
    del dc
    plt.draw() # need to redraw to make remove visible
    

    Python 没有“私有”属性的概念,因此您只需进入对象内部并在注释上调用 remove。见tutorial on classes for more details

    这样做的不利方面是,现在您拥有一个对象是一种奇怪的状态。如果您对它有任何其他引用,它们可能表现不佳。如果您想保留DataCursor 对象,可以使用set_* 函数修改annotation 对象或更改其可见性以暂时隐藏它(doc

    【讨论】:

    • 但是我如何确定对象的名称?这就是我似乎遇到的麻烦,因为它是在另一个类中创建的(另一个“自我”——如果有意义的话?)
    • @mcfly 我建议(重新)阅读docs.python.org/tutorial/classes.html
    【解决方案2】:

    你需要像艺术家一样添加它才能像艺术家一样删除它

    arrow2 = matplotlib.text.Annotation("I love it",xy=(0.5,0.5),xycoords='data',arrowprops=dict(arrowstyle="-")) 
    ax2.add_artist(arrow2) 
    arrow2.remove() 
    

    【讨论】:

      猜你喜欢
      • 2015-10-18
      • 2010-09-28
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      相关资源
      最近更新 更多