使用 matplotlib 存储鼠标单击事件坐标

Store mouse click event coordinates with matplotlib(使用 matplotlib 存储鼠标单击事件坐标)
本文介绍了使用 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)

断开事件挂钩.

你想做的是这样的:

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 存储鼠标单击事件坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reading *.mhd/*.raw format in python(在 python 中读取 *.mhd/*.raw 格式)
Count number of cells in the image(计算图像中的单元格数)
How to detect paragraphs in a text document image for a non-consistent text structure in Python OpenCV(如何在 Python OpenCV 中检测文本文档图像中的段落是否存在不一致的文本结构)
How to get the coordinates of the bounding box in YOLO object detection?(YOLO物体检测中如何获取边界框的坐标?)
Divide an image into 5x5 blocks in python and compute histogram for each block(在 python 中将图像划分为 5x5 块并计算每个块的直方图)
Extract cow number from image(从图像中提取奶牛编号)