在matplotlib中获取矩形选择的数据

2024-05-19 14:42:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解matplotlib中矩形选择器的用法。基本上我用imshow绘制一个2D数组,然后我想用鼠标选择一个矩形部分,并保存矩形的一角,以便以后在脚本中使用。我阅读了matplotlib文档中使用的矩形选择器,但无法获取数据。 我现在所做的是

import matplotlib as mpl
import bumpy as np
from matplotlib.widgets import RectangleSelector
# let z be my 2D array
z=np.ones((100,1000))
def onselect(eclick, erelease):
  'eclick and erelease are matplotlib events at press and release'
   print ' startposition : (%f, %f)' % (eclick.xdata, eclick.ydata)
   print ' endposition   : (%f, %f)' % (erelease.xdata, erelease.ydata)
   print ' used button   : ', eclick.button

fig=mpl.pylab.figure()
ax=fig.add_subplot(111)
ax.imshow(z,aspect='auto',origin='lower',extent=((0,100,0,1000)))
toggle_selector.RS=RectangleSelector(ax,onselect,drawtype='box',useblit=True,button=[1,3])

现在有了onselect函数,我打印出矩形最小值和最大值的(x,y)坐标值。但我想存储这些值以备以后使用。 我怎样才能做到这一点?在


Tags: importmatplotlibasnp选择器buttonaxmpl
3条回答

为了给Navdeep的答案增加细节。。。在

rect_selection_coords = toggle_selector.RS.extents
print(rect_selection_coords)
x1, x2, y1, y2 = rect_selection_coords

其他属性可以在github/matplotlib/lib/matplotlib的source中找到/小工具.py2296号线。在

如果您通读文档,您会发现返回的对象具有诸如范围、几何体等属性,其中包含有关选择的所有信息。我迟到了3年,希望能有所帮助。在

我只创建了几个全局变量并存储了扩展数据, 艾瑞克.ydata, erelease.扩展数据以及erelease.ydata公司在全局变量中。在

def onselect(eclick, erelease):
    global index
    global startpos
    global endpos
    print ' startposition : (%f, %f)' % (eclick.xdata, eclick.ydata)
    print ' endposition   : (%f, %f)' % (erelease.xdata, erelease.ydata)
    print ' used button   : ', eclick.button
    startpos[index] = [eclick.xdata, eclick.ydata]
    endpos[index]   = [erelease.xdata, erelease.ydata]

不确定这是否是“最好”的方式,但它奏效了:)

相关问题 更多 >