清除matplotlib imag上的覆盖散点图

2024-05-12 21:40:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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='+')

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

谢谢你的帮助!


Tags: 代码图像图形npplt按钮markersquare
1条回答
网友
1楼 · 发布于 2024-05-12 21:40:02

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.

(几乎?)所有matplotlib呈现函数都返回一个句柄,该句柄具有一些方法来移除呈现项。

注意,您需要调用redraw来查看来自remove帮助的remove()的效果(我的重点是):

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.

相关问题 更多 >