如何在交互式绘图 (Python) 中用鼠标指向 (x,y) 位置?

How to get a (x,y) position pointing with mouse in a interactive plot (Python)?

我用ipython记事本(有魔法%matplotlib nbagg)。我正在审查 matplotlib.widget.Cursor 但光标只被查看 widgets.Cursor. So I'd like to select two points clicking in the plot and get the initial and final x,y-position (e.g. time vs Temperature, selecting to points must return initial and final time). I need it for selecting manually an arbitrary interval. I think it's similar to get global x,y position,但我在 post.

中没有很好地理解

如何在交互式绘图 (Python) 中使用鼠标指向 (x,y) 位置?

观察。类似于 IDL

中的 CURSOR Procedure

Event handling 应该可以。

import matplotlib.pylab as plt
import numpy as np

f,a = plt.subplots()
x = np.linspace(1,10,100)
y = np.sin(x)
a.plot(x,y)
pos = []
def onclick(event):
    pos.append([event.xdata,event.ydata])
f.canvas.mpl_connect('button_press_event', onclick)
f.show()

每次单击时,当前光标位置都会附加到 pos.