Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear overlay scatter on matplotlib image

So I am back again with another silly question. Consider this piece of code

x = linspace(-10,10,100);
[X,Y]=meshgrid(x,x)
g = np.exp(-(square(X)+square(Y))/2)
plt.imshow(g)
scat = plt.scatter(50,50,c='r',marker='+')

Is there a way to clear only the scatter point on the graph without clearing all the image? In fact, I am writing a code where the appearance of the scatter point is bound with a Tkinter Checkbutton and I want it to appear/disappear when I click/unclick the button.

Thanks for your help!

like image 743
Mathieu Paurisse Avatar asked Mar 23 '23 04:03

Mathieu Paurisse


1 Answers

The return handle of plt.scatter has several methods, including remove(). So all you need to do is call that. With your example:

x = np.linspace(-10,10,100);
[X,Y] = np.meshgrid(x,x)
g = np.exp(-(np.square(X) + np.square(Y))/2)
im_handle = plt.imshow(g)
scat = plt.scatter(50,50,c='r', marker='+')
# image, with scatter point overlayed
scat.remove()
plt.draw()
# underlying image, no more scatter point(s) now shown

# For completeness, can also remove the other way around:
plt.clf()
im_handle = plt.imshow(g)
scat = plt.scatter(50,50,c='r', marker='+')
# image with both components
im_handle.remove()
plt.draw()
# now just the scatter points remain.

(almost?) all matplotlib rendering functions return a handle, which have some method to remove the rendered item.

Note that you need the call to redraw to see the effects of remove() -- from the remove help (my emphasis):

Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with :meth:matplotlib.axes.Axes.draw_idle.

like image 196
Bonlenfum Avatar answered Apr 01 '23 16:04

Bonlenfum