Matplotlib: clear scatter data before redrawing

I have a scatter plot above imshow (map). I want the click event to add a new scatter point, which I did with scater (newx, newy)). The problem is that I want to add the ability to delete points using the pick event. Since there is no remove (pickX, PickY) function, I have to get the selected index and remove them from the list, which means that I cannot create my scatter as above, I have to scatter (allx, ally).

So, on the bottom line, I need a method to remove the scatter chart and redraw it with new data, without changing the presence of my imshow. I tried and tried: just one try.

fig = Figure() axes = fig.add_subplot(111) axes2 = fig.add_subplot(111) axes.imshow(map) axes2.scatter(allx,ally) # and the redraw fig.delaxes(axes2) axes2 = fig.add_subplot(111) axes2.scatter(NewscatterpointsX,NewscatterpointsY,picker=5) canvas.draw() 

to my surprise, this got along with my imshow and axes too :(. Any methods of achieving my dream are much appreciated. Andrew

+1
source share
1 answer

First, you should read the docs events well here .

You can attach a function that is called with every mouse click. If you maintain a list of artists (dots in this case) that you can select, you can ask if there was a mouse click event inside the artists, and call the artist's remove method. If not, you can create a new artist and add it to the list of clicked points:

 import matplotlib.pyplot as plt fig = plt.figure() ax = plt.axes() ax.set_xlim(0, 1) ax.set_ylim(0, 1) pickable_artists = [] pt, = ax.plot(0.5, 0.5, 'o') # 5 points tolerance pickable_artists.append(pt) def onclick(event): if event.inaxes is not None and not hasattr(event, 'already_picked'): ax = event.inaxes remove = [artist for artist in pickable_artists if artist.contains(event)[0]] if not remove: # add a pt x, y = ax.transData.inverted().transform_point([event.x, event.y]) pt, = ax.plot(x, y, 'o', picker=5) pickable_artists.append(pt) else: for artist in remove: artist.remove() plt.draw() fig.canvas.mpl_connect('button_release_event', onclick) plt.show() 

enter image description here

Hope this helps you achieve your dream. :-)

+2
source

Source: https://habr.com/ru/post/1216186/


All Articles