Python 使用 matplotlib 存储鼠标点击事件坐标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25521120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:20:20  来源:igfitidea点击:

Store mouse click event coordinates with matplotlib

pythonmatplotlibonclickmouseevent

提问by smashbro

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.

我正在尝试在 matplotlib 中实现一个简单的鼠标点击事件。我想绘制一个图形,然后使用鼠标选择积分的下限和上限。到目前为止,我能够将坐标打印到屏幕上,但不能存储它们以供以后在程序中使用。我还想在第二次单击鼠标后退出与图形的连接。

Below is the code which currently plots and then prints the coordinates.

下面是当前绘制然后打印坐标的代码。

My Question(s):

我的问题:

How can I store coordinates from the figure to list? i.e. click = [xpos, ypos]

如何将图形中的坐标存储到列表中?即点击 = [xpos, ypos]

Is it possible to get two sets of x coordinates in order to do a simple integration over that section of line?

是否有可能获得两组 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()

采纳答案by otterb

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

mpl_connect 只需调用一次即可将事件连接到事件处理程序。它将开始侦听单击事件,直到您断开连接。你可以使用

fig.canvas.mpl_disconnect(cid)

to disconnect the event hook.

断开事件挂钩。

What you want to do is something like:

你想要做的是:

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)

回答by smashbro

Thanks to otterb for providing the answer! I've added in a little function taken from here... Find nearest value in numpy array

感谢 otterb 提供答案!我添加了一个从这里获取的小函数...... 在 numpy 数组中找到最近的值

In all this code will plot, wait for selection of x points and then return the indices of the x array needed for any integration, summations etc.

在所有这些代码中,等待选择 x 点,然后返回任何积分、求和等所需的 x 数组的索引。

Ta,

塔,

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