python - Multiple pick events interfering -
i have several data series scattered in figure , want able toggle annotations them. problem is, there 2 pick events triggered (when user clicks on spot within both annotation , dot). "annotation" pick event clears annotation, "dot" pick event puts right back, effect toggle doesn't work.
df = pd.dataframe({'a': np.random.rand(25)*1000, 'b': np.random.rand(25)*1000, 'c': np.random.rand(25)}) def handlepick(event): artist = event.artist if isinstance(artist, matplotlib.text.annotation): artist.set_visible(not artist.get_visible()) else: x = event.mouseevent.xdata y = event.mouseevent.ydata if artist.get_label() == 'a': ann = matplotlib.text.annotation('blue', xy=(x,y), picker=5) else: # label == 'b' ann = matplotlib.text.annotation('red', xy=(x,y), picker=5) plt.gca().add_artist(ann) plt.figure() plt.scatter(data=df, x='a', y='c', c='blue', s='a', alpha=0.5, picker=5, label='a') plt.scatter(data=df, x='b', y='c', c='red', s='b', alpha=0.5, picker=5, label='b') plt.gcf().canvas.mpl_connect('pick_event', handlepick) plt.show()
how can separate annotate , dot pick events , tell not annotate if dot has annotation? i'm using labels decide scatter series picked.
thanks much.
you create annotation every scatter point beforehands , set of invisible. click on scatterpoint toggle visibility of respective annotation. click on annotation nothing.
import matplotlib.pyplot plt import numpy np import pandas pd df = pd.dataframe({'a': np.random.rand(25)*1000, 'b': np.random.rand(25)*1000, 'c': np.random.rand(25)}) def handlepick(event): artist = event.artist lab = artist.get_label() if lab in d: ind in event.ind: ann = d[lab][ind] ann.set_visible(not ann.get_visible() ) plt.gcf().canvas.draw() plt.figure() plt.scatter(data=df, x='a', y='c', c='blue', s='a', alpha=0.5, picker=5, label='a') plt.scatter(data=df, x='b', y='c', c='red', s='b', alpha=0.5, picker=5, label='b') d = {"a" : [], "b": []} in range(len(df)): ann = plt.annotate("blue", xy=(df["a"].iloc[i], df["c"].iloc[i]), visible=false) d["a"].append(ann) ann = plt.annotate("red", xy=(df["b"].iloc[i], df["c"].iloc[i]), visible=false) d["b"].append(ann) plt.gcf().canvas.mpl_connect('pick_event', handlepick) plt.show()
Comments
Post a Comment