我试图单击 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/