Understanding matplotlib event handling: what are

2020-07-22 10:49发布

问题:

I wanted to make it possible to show values when pressing a dot in my scatterplot. The solution was found here: Possible to make labels appear when hovering over a point in matplotlib?

Solution:

from matplotlib.pyplot import figure, show
import numpy as npy
from numpy.random import rand


# picking on a scatter plot (matplotlib.collections.RegularPolyCollection)

x, y, c, s = rand(4, 100)
def onpick3(event):
    ind = event.ind
    print 'onpick3 scatter:', ind, npy.take(x, ind), npy.take(y, ind)

fig = figure()
ax1 = fig.add_subplot(111)
col = ax1.scatter(x, y, 100*s, c, picker=True)
#fig.savefig('pscoll.eps')
fig.canvas.mpl_connect('pick_event', onpick3)

show()

And it solved my problem. But I don't understand how, I've been googling around without any luck. I know how to plot with matplotlib, so that's not where my knowledge is lacking.

One thing I don't understand is the onpick3(event) function. What is this event parameter? Because the function itself is called upon further down without any given arguments: fig.canvas.mpl_connect('pick_event', onpick).

回答1:

mpl_connect connects a signal to a slot. The slot is in this case onpick3.
Note that the slot is not called, i.e. the syntax is

fig.canvas.mpl_connect('pick_event', onpick3)
and not
fig.canvas.mpl_connect('pick_event', onpick3())

It will only be called once the signal is triggered (mouse clicked on canvas). At this point the underlying event is provided as an argument in the function call.

You'll see that once you try to define the slot without argument. This would cause an error like onpick3 expects 0 arguments but got 1 or so.

You'll find details on the matplotlib event handling page. The event itself is an instance of matplotlib.backend_bases.PickEvent. The .ind attribute is not well documented, but that is mainly because not all artists actually register this attribute to the event.