在 matplotlib 图像上清除覆盖散布

Mat*_*sse 3 python matplotlib

所以我又回到了另一个愚蠢的问题。考虑这段代码

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='+')
Run Code Online (Sandbox Code Playgroud)

有没有办法只清除图形上的散点而不清除所有图像?事实上,我正在编写一个代码,其中散点的外观与 Tkinter Checkbutton 绑定,我希望它在单击/取消单击按钮时出现/消失。

谢谢你的帮助!

Bon*_*fum 5

的返回句柄plt.scatter有多种方法,包括remove(). 所以你需要做的就是调用它。以你的例子:

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.
Run Code Online (Sandbox Code Playgroud)

(几乎?)所有 matplotlib 渲染函数都返回一个句柄,它有一些方法来删除渲染的项目。

请注意,您需要调用重绘以查看remove()-- 从删除帮助(我的重点)中的效果:

如果可能,请从图中移除艺术家。在重新绘制图形之前,效果将不可见,例如,使用 :meth: matplotlib.axes.Axes.draw_idle