我正在尝试在matplotlib中实现一个简单的鼠标单击事件。我希望绘制一个图,然后使用鼠标选择集成的下限和上限。 到目前为止,我能够将坐标打印到屏幕,但不能存储它们以供以后在程序中使用。我想在第二次鼠标点击后退出与图的连接。
下面是当前绘制然后打印坐标的代码。
我的问题:
如何将图中的坐标存储到列表中?即click = [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()
答案 0 :(得分:25)
mpl_connect只需调用一次即可将事件连接到事件处理程序。它将开始侦听单击事件,直到您断开连接。你可以使用
fig.canvas.mpl_disconnect(cid)
断开事件挂钩。
你想要做的是:
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)
答案 1 :(得分:6)
感谢otterb提供答案!我在这里添加了一个小函数... Find nearest value in numpy array
在所有这些代码中将绘制,等待选择x点,然后返回任何积分,求和等所需的x数组的索引。
钽,
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import trapz
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
# Simple mouse click function to store coordinates
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
# print 'x = %d, y = %d'%(
# ix, iy)
# assign global variable to access outside of function
global coords
coords.append((ix, iy))
# Disconnect after 2 clicks
if len(coords) == 2:
fig.canvas.mpl_disconnect(cid)
plt.close(1)
return
x = np.arange(-10,10)
y = x**2
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x,y)
coords = []
# Call click func
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show(1)
# limits for integration
ch1 = np.where(x == (find_nearest(x, coords[0][0])))
ch2 = np.where(x == (find_nearest(x, coords[1][0])))
# Calculate integral
y_int = trapz(y[ch1[0][0]:ch2[0][0]], x = x[ch1[0][0]:ch2[0][0]])
print ''
print 'Integral between '+str(coords[0][0])+ ' & ' +str(coords[1][0])
print y_int
答案 2 :(得分:0)
我也有类似的需求,但是这段代码对我不起作用。我已经直接复制/粘贴了它(Anaconda 2.7),但是它似乎fig.canvas.mpl_connect('button_press_event',onclick)从未等待输入,这会触发紧随其后的coords [n] [m]调用中的错误。有建议吗?
> Traceback (most recent call last):
>
> File "<ipython-input-5-d074e6221b24>", line 1, in <module>
> runfile('C:/Users/xxx/Documents/Python/test/untitled0.py', wdir='C:/Users/xxx/Documents/Python/test')
>
> File
> "C:\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py",
> line 705, in runfile
> execfile(filename, namespace)
>
> File
> "C:\Anaconda2\lib\site-packages\spyder\utils\site\sitecustomize.py",
> line 87, in execfile
> exec(compile(scripttext, filename, 'exec'), glob, loc)
>
> File "C:/Users/xxx/Documents/Python/test/untitled0.py", line
> 45, in <module>
> ch1 = np.where(x == (find_nearest(x, coords[0][0])))
>
> IndexError: list index out of range