我正在尝试为 matplotlib 中的绘图编写点选择器。我希望它能告诉我我单击的绘制数组的 i、j 索引。似乎唯一的选择是 event.mouseevent.xdata,它是根据绘制的坐标值,或者 event.mouseevent.x,它是根据像素(从我所看到的“像素”不是与网格框相同,即我正在寻找的东西)。
我是不是误解了什么 xdata/x。有没有办法做我想做的事。
谢谢 尼尔
编辑:被点击的图像是二维数组图,例如 pcolormesh
请您参考如下方法:
你可以:
- 首先让您的艺术家(下例中的数组)可选取。
- 在点击操作时,检查点击是针对艺术家
- 使用
event.ind[0]属性获取索引。
更多文档 here .示例如下:
from numpy import linspace
from numpy import cos
from numpy import pi
import matplotlib.pyplot as plt
x = linspace(0,1,100)
y = cos(x*8*pi) # your array
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(x, y, 'b',picker=10)
def onpick(event):
if event.artist!=line: #check that you clicked on the object you wanted
return True
if not len(event.ind): #check the index is valid
return True
ind = event.ind[0]
ax.plot(x[ind],y[ind],'ro')
fig.canvas.draw()
return True
fig.canvas.mpl_connect('pick_event', onpick)
fig.show()
编辑:好的。然后你可以先在你的网格点精确地画一条线,然后在上面画你的 pcolormesh 对象,并隐藏线。这是代码
x = linspace(0,9,10)+.5
y = linspace(0,9,10)+.5 # your array
x,y=meshgrid(x,y)
x=x.flatten()
y=y.flatten()
fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(x, y, 'b',picker=10)
line.set_visible(False)
ax.pcolormesh(np.random.randn(10,10))
def onpick(event):
if event.artist!=line: #check that you clicked on the object you wanted
return True
if not len(event.ind): #check the index is valid
return True
ind = event.ind[0]
ax.plot(x[ind],y[ind],'ro')
fig.canvas.draw()
return True
fig.canvas.mpl_connect('pick_event', onpick)
fig.show()
