ABCD
ABCD

Reputation: 153

Matplotlib event picker - Inside a class

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

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

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.

Upvotes: 1

Related Questions