python 从 matplotlib click 返回 ydata

标签 python matplotlib

我试图单击 matplotlib 中的绘图并将单击位置的 y 值返回给变量。我使用了 matplotlib 中的示例,它从 event.ydata 打印出位置,但无法弄清楚如何返回它!

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))

def onclick(event):
    print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(event.button, event.x, event.y, event.xdata, event.ydata)

cid = fig.canvas.mpl_connect('button_press_event', onclick)

最佳答案

如果我理解正确的话,您想要弹出一个图并等待用户单击其中的一个点,然后再继续。据我所知,没有预先打包的方法可以做到这一点,但下面的代码应该可以满足您的要求。完全披露:它确实使用了全局变量。

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))

retval = -1
def onclick(event):
    print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(event.button, event.x, event.y, event.xdata, event.ydata)
    # Record the x location of the user's click in the global variable and close the figure
    global retval
    retval = event.xdata
    plt.close()

cid = fig.canvas.mpl_connect('button_press_event', onclick)
# Bring up the figure (and wait)
plt.show()

print 'User selected point {0}'.format( retval )

关于python 从 matplotlib click 返回 ydata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26070157/

相关文章:

python - 有没有更快的方法从 scipy.sparse.dok_matrix 提取行/列子矩阵?

python - 何时使用 cla()、clf() 或 close() 清除绘图

matplotlib - 如何使用 matplotlib 绘制点,使它们出现在脊柱顶部?

python - 如何在 GAE 上将类方法作为 deferred.defer 的参数传递

python - sympy 矩阵真的那么慢吗?

Python-凯撒密码

python - 已弃用警告 - mataplotlib 库中的 where 参数

matplotlib - 绘制 Budyko 曲线 (1974)

python - IPython 笔记本不会显示绘图

python - char python 之间的大写