Python 脚本结束后,如何保持matplotlib图处于打开状态?

Python 脚本结束后,如何保持matplotlib图处于打开状态?,python,matplotlib,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') f

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

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
不幸的是,该图在脚本结束后关闭

如何预防

更新


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

您可以保存图形:

plt.savefig('my_fig.pdf')

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

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.

一种方法是在运行脚本后保持python打开。 为了做到这一点,必须在命令行中包含-i选项。因此,如果您的Python脚本是myscript.py,请在命令行执行以下操作:

python-i myscript.py


来源:

我可以通过某种方式将
fig
传递给此函数吗?或者它是如何知道要拯救什么的?fig是plt的孩子。plt知道要保存什么。如果我有几个无花果呢?你有问题吗?你能发布一个简单的可重复的例子吗?我已经进入源代码,发现<代码> SaveFigg < /代码>委托给<代码> gcf().SaveFigIE()/Case>并且更喜欢使用它……如果他们帮助了你,请考虑接受答案。