我试图在类中插入这个python文档中显示的事件选择器示例
http://matplotlib.org/users/event_handling.html
代码是这样的
import numpy as np
import matplotlib.pyplot as plt
class Test:
def __init__(self,line):
self.line = line
self.cidpress = self.line.figure.canvas.mpl_connect('button_press_event', self.onpick)
def onpick(self, event):
thisline = event.artist
xdata = thisline.get_xdata()
ydata = thisline.get_ydata()
ind = event.ind
points = tuple(zip(xdata[ind], ydata[ind]))
print('onpick points:', points)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')
line, = ax.plot(np.random.rand(10), 'o', picker=5) # 5 points tolerance
a = Test(line)
plt.show()
但我得到这个错误时,鼠标点击一个点。在
^{pr2}$这可能是什么原因? 当不在类中时,代码可以完美地工作
多谢了
我怀疑这些代码在类之外是否有效。您在这里面临的问题是使用
'button_press_event'
,它没有artist
属性。无论是在课堂内外,这都不会改变。在如果要使用
event.artist
,则需要使用'pick_event'
。这显示在matplotlib页面的event picking example中。如果要使用
'button_press_event'
,则不能使用event.artist
,而是需要通过查询某个艺术家是否包含该事件(例如if line.contains(event)[0]: ...
)来查找已单击的元素。参见例如这个问题:How to check if click is on scatter plot point with multiple markers (matplotlib)相关问题 更多 >
编程相关推荐