问题描述
我正在尝试在 matplotlib 中实现一个简单的鼠标单击事件.我希望绘制一个图形,然后使用鼠标选择积分的下限和上限.到目前为止,我能够将坐标打印到屏幕上,但不能存储它们以供以后在程序中使用.我也想在第二次鼠标点击后退出与图的连接.
I am trying to implement a simple mouse click event in matplotlib. I wish to plot a figure then use the mouse to select the lower and upper limits for integration. So far I am able to print the coordinates to screen but not store them for later use in the program. I would also like to exit the connection to the figure after the second mouse click.
下面是当前绘制然后打印坐标的代码.
Below is the code which currently plots and then prints the coordinates.
我的问题:
如何将图形中的坐标存储到列表中?即点击 = [xpos, ypos]
How can I store coordinates from the figure to list? i.e. click = [xpos, ypos]
是否有可能获得两组 x 坐标以便对该段线进行简单的积分?
Is it possible to get two sets of x coordinates in order to do a simple integration over that section of line?
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 只需调用一次即可将事件连接到事件处理程序.它将开始监听点击事件,直到您断开连接.你可以使用
mpl_connect needs to be called just once to connect the event to event handler. It will start listening to click event until you disconnect. And you can use
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)
这篇关于使用 matplotlib 存储鼠标单击事件坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!