我正在尝试在 matplotlib 中实现一个简单的鼠标单击事件。我希望绘制一个图形,然后使用鼠标选择积分的下限和上限。 到目前为止,我能够将坐标打印到屏幕上,但不能存储它们以供以后在程序中使用。我也想在第二次鼠标点击后退出与图的连接。
下面是当前绘制然后打印坐标的代码。
我的问题:
如何将图形中的坐标存储到列表中?即点击 = [xpos, ypos]
是否有可能获得两组 x 坐标以便对该段线进行简单的积分?
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10)
y = x**2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
print 'x = %d, y = %d'%(
ix, iy)
global coords
coords = [ix, iy]
return coords
for i in xrange(0,1):
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
最佳答案
mpl_connect 只需调用一次即可将事件连接到事件处理程序。它将开始监听点击事件,直到您断开连接。你可以使用
fig.canvas.mpl_disconnect(cid)
断开事件 Hook 。
你想做的是这样的:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10,10)
y = x**2
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)
coords = []
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
print 'x = %d, y = %d'%(
ix, iy)
global coords
coords.append((ix, iy))
if len(coords) == 2:
fig.canvas.mpl_disconnect(cid)
return coords
cid = fig.canvas.mpl_connect('button_press_event', onclick)
关于python - 使用 matplotlib 存储鼠标单击事件坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25521120/