Reputation: 153
I am trying to insert the event picker example shown in this python documentation, inside a class
http://matplotlib.org/users/event_handling.html
The code goes like this
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()
But Im getting this error when mouse is clicked on a point.
AttributeError: 'MouseEvent' object has no attribute 'artist'
What could be the reason for this ? When not inside the class the code works perfectly
thanks much
Upvotes: 0
Views: 3006
Reputation: 339052
I doubt that the code works outside a class. The problem you face here is that you use a 'button_press_event'
, which does not have an artist
attribute. This will not change whether in or outside a class.
If you want to use the event.artist
you would need to use a 'pick_event'
. This is shown in the event picking example on the matplotlib page.
If you want to use a 'button_press_event'
, you cannot use event.artist
but would rather need to find out the element which has been clicked upon by querying whether some artist contains the event, e.g. if line.contains(event)[0]: ...
. See e.g. this question: How to check if click is on scatter plot point with multiple markers (matplotlib)
Upvotes: 1