使用matplotlib存储鼠标点击事件坐标
我正在尝试在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()
3 个回答
6
感谢otterb提供的答案!我在这里添加了一个小函数,来源于这里……
总的来说,这段代码会绘制图形,等待你选择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
7
我想在这里提供一个不同的答案,因为我最近尝试处理事件时,发现这里的解决方案没有区分缩放、平移和点击,导致我的情况变得很混乱。我找到一个叫做 mpl_point_clicker 的扩展,它在我这里效果很好,可以通过 pip 安装(适用于 Python 3.X)。以下是他们文档中的基本用法:
import numpy as np
import matplotlib.pyplot as plt
from mpl_point_clicker import clicker
fig, ax = plt.subplots(constrained_layout=True)
ax.plot(np.sin(np.arange(200)/(5*np.pi)))
klicker = clicker(ax, ["event"], markers=["x"])
plt.show()
print(klicker.get_positions())
这个图形经过三次点击后,输出结果看起来是这样的:
输出结果:
{'event': array([[ 24.22415481, 1.00237796],
[ 74.19892948, -0.99140661],
[123.23078387, 1.00237796]])}
57
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 (f'x = {ix}, y = {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)