将点击事件添加到 pyplot 中的注释

kab*_*nus 2 annotations matplotlib

我正在寻找一种方法将“点击”事件添加到注释中matplotlib.pyplot以销毁它。相关代码:

import matplotlib.pyplot as plt
plt.ion()
plt.plot()
plt.annotate("Kill me",xy=(0,0))
Run Code Online (Sandbox Code Playgroud)

现在我们需要找到注解,一种方法是迭代:

plt.gca().texts
Run Code Online (Sandbox Code Playgroud)

虽然可能有更好的方法。到目前为止,我还没有找到如何使用此获取小部件/添加事件。这是可能使用mpl_connect的的plt数字画布,但我不知道,这将需要边框,我想尽量避免前往,但如果没有其他的解决方案是可用的罚款。

Imp*_*est 6

您确实可以使用mpl_connect将选择器事件连接到画布中的对象。在这种情况下,annotate可以给对的调用提供一个picker参数,该参数指定应触发事件的对象周围的半径。

然后,您可以直接对触发事件的对象进行操作,该对象在事件槽中作为event.artist.

import matplotlib.pyplot as plt

fig = plt.figure()
ax=fig.add_subplot(111)
plt.plot([0,5],[0,6], alpha=0)
plt.xlim([-1,6])
plt.ylim([-1,6])

for i in range(6):
    for j in range(6):
        an = plt.annotate("Kill me",xy=(j,i), picker=5)


def onclick(event):
    event.artist.set_text("I'm killed")
    event.artist.set_color("g")
    event.artist.set_rotation(20)
    # really kill the text (but too boring for this example;-) )
    #event.artist.set_visible(False) 
    # or really REALLY kill it with:
    #event.artist.remove()
    fig.canvas.draw()


cid = fig.canvas.mpl_connect('pick_event', onclick)

plt.show()
Run Code Online (Sandbox Code Playgroud)