首页 > 解决方案 > 在 Matplotlib 中:我想单击图形的特定部分并将这些坐标保存到一个空数组中

问题描述

我正在使用 matplotlib 并从堆栈社区中的先前问题中获取了大部分代码。

链接在这里:使用 matplotlib 存储鼠标单击事件坐标

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]

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))

#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(2)
ax = fig.add_subplot(111)
ax.plot(x,y)

coords = []

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

plt.show()

#integration limits

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

我认为这会保存坐标并且确实如此。关闭绘图后,它会在我的终端中保存最后的点击。

我希望在图表上单击多次,并可能将这些单击的位置保存到一个空数组中以供以后使用。任何要导入以提供帮助的建议或不同的模块都很棒。

标签: pythonmatplotlibplotconnection

解决方案


推荐阅读