問題描述
我正在嘗試在 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 存儲鼠標單擊事件坐標的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!