使用matplotlib和python从pick事件中获取子图

问题描述:

我有一个包含四个子图的图形,其中两个绑定在一个选择事件上,通过执行 canvas.mpl_connect('pick_event', onpick) 其中 onpick 是 onpick(event) 处理程序.

I have a figure with four subplots, two of which are binded on a pick event, by doing canvas.mpl_connect('pick_event', onpick) where onpick is onpick(event) handler.

现在,基于单击进入的两个支持中的哪个,我必须激活不同的行为(即,如果选择来自第一个子图,则执行此操作,否则,如果它来自第二个子图,则执行此操作),但是知道怎么做.有人可以帮我吗?

Now, based on which of the two suplot the click come in, I must activate a different behaviour (ie if pick come from 1st subplot do this, else if it come from second suplot do that), but I don't know how to do it. Can anyone help me?

这是一个简短的例子:

import matplotlib.pyplot as plt
from random import random

def onpick(event):
    if event.artist == plt1:
        print("Picked on top plot")
    elif event.artist == plt2:
        print("Picked on bottom plot")

first = [random()*i for i in range(10)]
second = [random()*i for i in range(10)]

fig = plt.figure(1)
plt1 = plt.subplot(211)
plt.plot(range(10), first)

plt2 = plt.subplot(212)
plt.plot(range(10), second)

plt1.set_picker(True)
plt2.set_picker(True)
fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

请注意,您必须在应该触发该事件的子图中调用 set_picker(True)!如果不这样做,即使将事件设置在画布上也不会发生任何事情.

Note that you have to call set_picker(True) on the subplots that should fire this event! If you don't, nothing will happen even though you've set the event on the canvas.

如需进一步阅读,请参阅PickEvent 文档 和来自 matplotlib 站点的 pick 处理演示.

For further reading, here's the PickEvent documentation and an pick handling demo from the matplotlib site.