0

I am trying to write a script to interactively plot a scatter plot using matplotlib. It is important to me to delete some points by mouse click event or delete button on the keyboard. My goal is to clean the plot from the undesired points and generate a new dataframe with the clean points. I spent the whole day trying to figure it out and could write this script.

I would appreciate any suggestions.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [2, 5, 6, 5]

def onpick(event):    

    this_artist = event.artist
    print(this_artist)
    plt.gca().picked_object = this_artist

def on_key(event):
    if event.key == u'delete':
        ax = plt.gca()
        if ax.picked_object:
            ax.picked_object.remove()
            ax.picked_object = None
            ax.figure.canvas.draw()


fig, ax = plt.subplots()
ax= plt.scatter(x,y)

fig.canvas.mpl_connect('pick_event', onpick)
cid = fig.canvas.mpl_connect('key_press_event', on_key)

plt.show()

Thiago
  • 1
  • You need to store the index of the picked point (event.ind), such that upon pressing a key you can remove that index from the list of data of the scatter. (For updating scatters see [this](https://stackoverflow.com/questions/9401658/how-to-animate-a-scatter-plot) or [this](https://stackoverflow.com/questions/42722691/python-matplotlib-update-scatter-plot-from-a-function)) – ImportanceOfBeingErnest Sep 25 '19 at 14:16
  • Thanks, I will try to understand the examples and apply (event.ind) on the code. – Thiago Sep 25 '19 at 14:25
  • @ImportanceOfBeingErnest I could not modify the code. Could you please help? – Thiago Sep 26 '19 at 10:59

1 Answers1

0

Somehow I used (ind) to delete points according to the index. But it is still not working.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd



x=[1,2,3,4]
y=[2,4,5,8]

frame = { 'x': x, 'y' : y} 
df = pd.DataFrame(frame) 



fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click on points')
line, = ax.plot(df.x, df.y, 'o', picker=5)


def onpick(event):
    thisline = event.artist
    xdata = thisline.get_xdata()
    ydata = thisline.get_ydata()
    ind = event.ind
    points = tuple(zip(xdata[ind], ydata[ind]))
    print('onpick points:', ind)
    line.remove(ind)

fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

any solution?

Thiago
  • 1