使用matplotlib存储鼠标单击事件坐标 [英] Store mouse click event coordinates with matplotlib

查看:538
本文介绍了使用matplotlib存储鼠标单击事件坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在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)

断开事件挂钩.

您要执行的操作类似于:

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)

这篇关于使用matplotlib存储鼠标单击事件坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆