如何在脚本结束后保持 matplotlib 图打开?

Suz*_*ioc 7 python matplotlib

假设我有以下脚本为我绘制图表:

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np

img = mpimg.imread('stinkbug.png')
#circle = plt.Circle((0, 0), radius=0.5, fc='y')
circle = plt.Circle((0, 0), radius=100, fill=False, color='b')

fig, ax = plt.subplots()
ax.imshow(img)
ax.add_artist(circle)
fig.show()
pass
Run Code Online (Sandbox Code Playgroud)

不幸的是,这个人物在脚本结束后就关闭了。

如何预防呢?

更新

如果这个人物不可能在剧本中幸存下来,那么原因是什么?人物和剧本之间有什么联系?

Sto*_*ica 2

你不能。脚本创建的人物在脚本结束后将无法继续存在。但也许您不需要这样做,您可以让脚本等待您关闭图形窗口。只需确保交互模式未激活即可。

import matplotlib.pyplot as plt
plt.ioff()  # Use non-interactive mode.
plt.plot([0, 1])  # You won't see the figure yet.
plt.show()  # Show the figure. Won't return until the figure is closed.
Run Code Online (Sandbox Code Playgroud)