Search code examples
pythonmatplotlibhighlightpicker

Using matplotlib set_pickradius correctly


I had a previous question on how to highlight data points in matplotlib using a pick_event (this one here). The solution worked fine until matplotlib changed the usage of the keyword picker. Now I can't get it work anymore. Here is the MWE that worked before:

import matplotlib.pyplot as plt

class MyPlot(object):

    def makePlot(self):
        self.fig = plt.figure('Test', figsize=(10, 8))
        ax = plt.subplot(111)
        x = range(0, 100, 10)
        y = (5,)*10
        ax.plot(x, y, '-', color='red')
        ax.plot(x, y, 'o', color='blue', picker=5)
        self.highlight, = ax.plot([], [], 'o', color='yellow')
        self.cid = plt.connect('pick_event', self.onPick)
        plt.show()

    def onPick(self, event=None):
        this_point = event.artist
        x_value = this_point.get_xdata()
        y_value = this_point.get_ydata()
        ind = event.ind
        self.highlight.set_data(x_value[ind][0],y_value[ind][0])
        self.fig.canvas.draw_idle()

if __name__ == '__main__':
    app = MyPlot()
    app.makePlot()

Now I changed this line:

        ax.plot(x, y, 'o', color='blue', picker=5)

to this:

        ax.xaxis.set_pickradius(5.)
        ax.yaxis.set_pickradius(5.)

according to the documentation, but the highlighting does not work anymore. What else do I have to change?


Solution

  • Ok, after some wild random testing I just found the solution. Instead of

    ax.plot(x, y, 'o', color='blue', picker=5)
    

    I must use

    ax.plot(x, y, 'o', color='blue', picker=True)
    ax.xaxis.set_pickradius(5.)
    ax.yaxis.set_pickradius(5.)
    

    Looks like the keyword picker only accepts bools or functions, but not floats anymore. And yes, it is actually in the documentation, was just looking at the wrong place.