在Python解释器中的这些指令之后,你会看到一个带有图形的窗口:

from matplotlib.pyplot import *
plot([1,2,3])
show()
# other code

不幸的是,我不知道如何在程序进行进一步计算时继续交互式地探索show()创建的图形。

这可能吗?有时计算很长,如果在检查中间结果时进行计算将会有所帮助。


当前回答

在许多情况下,将图像保存为硬盘上的.png文件会更方便。原因如下:

优点:

在这个过程中,你可以随时打开、查看和关闭它。当应用程序运行较长时间时,这尤其方便 时间。 什么都不会弹出,你也不会被迫打开窗户。这在处理许多数字时特别方便。 您的图像可用于以后的参考,并且在关闭图形窗口时不会丢失。

缺点:

我唯一能想到的是,你将不得不去查找文件夹,并打开自己的图像。

其他回答

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

使用matplotlib调用不会阻塞:

使用画():

from matplotlib.pyplot import plot, draw, show
plot([1,2,3])
draw()
print('continue computation')

# at the end call show to ensure window won't close.
show()

使用交互模式:

from matplotlib.pyplot import plot, ion, show
ion() # enables interactive mode
plot([1,2,3]) # result shows immediatelly (implicit draw())

print('continue computation')

# at the end call show to ensure window won't close.
show()

最好总是检查您正在使用的库是否支持以非阻塞的方式使用。

但是如果你想要一个更通用的解决方案,或者如果没有其他方法,你可以通过使用python中包含的多处理模块来运行任何在分离进程中阻塞的东西。计算将继续:

from multiprocessing import Process
from matplotlib.pyplot import plot, show

def plot_graph(*args):
    for data in args:
        plot(data)
    show()

p = Process(target=plot_graph, args=([1, 2, 3],))
p.start()

print 'yay'
print 'computation continues...'
print 'that rocks.'

print 'Now lets wait for the graph be closed to continue...:'
p.join()

这有启动新进程的开销,而且在复杂的场景下有时更难调试,因此我更喜欢其他解决方案(使用matplotlib的非阻塞API调用)

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

您可能需要阅读matplotlib文档中的这个文档,标题为:

在python shell中使用matplotlib