在Python解释器中的这些指令之后,你会看到一个带有图形的窗口:
from matplotlib.pyplot import *
plot([1,2,3])
show()
# other code
不幸的是,我不知道如何在程序进行进一步计算时继续交互式地探索show()创建的图形。
这可能吗?有时计算很长,如果在检查中间结果时进行计算将会有所帮助。
在Python解释器中的这些指令之后,你会看到一个带有图形的窗口:
from matplotlib.pyplot import *
plot([1,2,3])
show()
# other code
不幸的是,我不知道如何在程序进行进一步计算时继续交互式地探索show()创建的图形。
这可能吗?有时计算很长,如果在检查中间结果时进行计算将会有所帮助。
当前回答
在许多情况下,将图像保存为硬盘上的.png文件会更方便。原因如下:
优点:
在这个过程中,你可以随时打开、查看和关闭它。当应用程序运行较长时间时,这尤其方便 时间。 什么都不会弹出,你也不会被迫打开窗户。这在处理许多数字时特别方便。 您的图像可用于以后的参考,并且在关闭图形窗口时不会丢失。
缺点:
我唯一能想到的是,你将不得不去查找文件夹,并打开自己的图像。
其他回答
plt.figure(1)
plt.imshow(your_first_image)
plt.figure(2)
plt.imshow(your_second_image)
plt.show(block=False) # That's important
raw_input("Press ENTER to exist") # Useful when you run your Python script from the terminal and you want to hold the running to see your figures until you press Enter
OP询问分离matplotlib图。大多数回答假设从python解释器中执行命令。这里给出的用例是我对在终端(例如bash)中测试代码的偏好,在终端中运行file.py,并且您希望出现绘图,但python脚本完成并返回命令提示符。
这个独立文件使用多处理启动一个单独的进程,用matplotlib绘制数据。主线程使用本文中提到的os._exit(1)退出。os._exit()强制main退出,但在plot窗口关闭之前,matplotlib子进程仍然活跃并保持响应。这是一个完全独立的过程。
这种方法有点像带有图形窗口的Matlab开发会话,会产生响应式命令提示符。使用这种方法,您将失去与图形窗口进程的所有联系,但是,这对于开发和调试来说是可以的。只需关闭窗口并继续测试。
多处理是专为python代码执行而设计的,这使得它可能比子进程更适合。multiprocessing是跨平台的,所以这应该在Windows或Mac上工作得很好,很少或没有调整。不需要检查底层操作系统。这是在linux Ubuntu 18.04LTS上测试的。
#!/usr/bin/python3
import time
import multiprocessing
import os
def plot_graph(data):
from matplotlib.pyplot import plot, draw, show
print("entered plot_graph()")
plot(data)
show() # this will block and remain a viable process as long as the figure window is open
print("exiting plot_graph() process")
if __name__ == "__main__":
print("starting __main__")
multiprocessing.Process(target=plot_graph, args=([1, 2, 3],)).start()
time.sleep(5)
print("exiting main")
os._exit(0) # this exits immediately with no cleanup or buffer flushing
运行file.py会弹出一个图形窗口,然后__main__退出,但是multiprocessing + matplotlib图形窗口仍然对缩放、平移和其他按钮有响应,因为它是一个独立的进程。
在bash命令提示符下检查进程:
Ps ax|grep -v grep |grep file.py
使用关键字'block'来覆盖阻塞行为,例如:
from matplotlib.pyplot import show, plot
plot(1)
show(block=False)
# your code
继续您的代码。
虽然没有直接回答OPs的请求,但我发布了这个变通方法,因为它可能会帮助一些人在这种情况下:
我用pyinstaller创建了一个.exe,因为我不能在我需要生成图形的地方安装python,所以我需要python脚本来生成图形,将其保存为.png,关闭它并继续下一个,在循环中实现为几个图形或使用一个函数。
为此,我使用:
import matplotlib.pyplot as plt
#code generating the plot in a loop or function
#saving the plot
plt.savefig(var+'_plot.png',bbox_inches='tight', dpi=250)
#you can allways reopen the plot using
os.system(var+'_plot.png') # unfortunately .png allows no interaction.
#the following avoids plot blocking the execution while in non-interactive mode
plt.show(block=False)
#and the following closes the plot while next iteration will generate new instance.
plt.close()
其中“var”标识循环中的情节,因此它不会被覆盖。
我所发现的最佳解决方案是,程序不会等待您关闭图形,并将所有的图放在一起,以便您可以并排检查它们,这是在最后显示所有的图。 但是通过这种方式,您不能在程序运行时检查图。
# stuff
numFig = 1
plt.figure(numFig)
numFig += 1
plt.plot(x1, y1)
# other stuff
plt.figure(numFig)
numFig += 1
plt.plot(x2, y2)
# more stuff
plt.show()