Skip to content Skip to sidebar Skip to footer

Multiple Pick Events Interfering

I have several data series scattered in a figure and want to be able to toggle annotations for them. The problem is, sometimes there are two pick events triggered (when the user cl

Solution 1:

You could create an annotation for every scatter point beforehands and set all of those invisible. A click on the scatterpoint would toggle visibility of the respective annotation. A click on the annotation would simply do nothing.

import matplotlib.pyplot as plt
import numpy as np
import pandas as 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:
        for 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": []}
for i  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()

Post a Comment for "Multiple Pick Events Interfering"