所有这些都可以在函数或类中隐藏起来:# import stuff
import matplotlib.pyplot as plt
import numpy as np
# create dictionary we will close over (twice)
label_dict = dict()
# helper function to do the scatter plot + shove data into label_dict
def lab_scatter(ax, x, y, label_list, *args, **kwargs):
if 'picker' not in kwargs:
kwargs['picker'] = 3
sc = ax.scatter(x, y, *args, **kwargs)
label_dict[sc] = label_list
return sc
# call back function which also closes over label_dict, should add more sanity checks
# (that artist is actually in the dict, deal with multiple hits in ind ect)
def cb_fun(event):
# grab list of labels from the dict, print the right one
print label_dict[event.artist][event.ind[0]]
# create the figure and axes to use
fig, ax = plt.subplots(1, 1)
# loop over 5 synthetic data sets
for j in range(5):
# use our helper function to do the plotting
lab_scatter(ax,
np.ones(10) * j,
np.random.rand(10),
# give each point a unique label
label_list = ['label_{s}_{f}'.format(s=j, f=k) for k in range(10)])
# connect up the call back function
cid = fig.canvas.mpl_connect('pick_event', cb_fun)