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

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

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

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


当前回答

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

其他回答

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

如果你在控制台工作,即IPython,你可以使用plt.show(block=False),正如在其他答案中指出的那样。但如果你很懒,你可以输入:

plt.show(0)

这是一样的。

我还希望我的图显示运行其余的代码(然后继续显示),即使出现错误(我有时使用图进行调试)。我编写了这个小代码,让这个with语句中的任何plot都像这样。

这可能有点太非标准了,不适合用于生产代码。这段代码中可能有很多隐藏的“陷阱”。

from contextlib import contextmanager

@contextmanager
def keep_plots_open(keep_show_open_on_exit=True, even_when_error=True):
    '''
    To continue excecuting code when plt.show() is called
    and keep the plot on displaying before this contex manager exits
    (even if an error caused the exit).
    '''
    import matplotlib.pyplot
    show_original = matplotlib.pyplot.show
    def show_replacement(*args, **kwargs):
        kwargs['block'] = False
        show_original(*args, **kwargs)
    matplotlib.pyplot.show = show_replacement

    pylab_exists = True
    try:
        import pylab
    except ImportError: 
        pylab_exists = False
    if pylab_exists:
        pylab.show = show_replacement

    try:
        yield
    except Exception, err:
        if keep_show_open_on_exit and even_when_error:
            print "*********************************************"
            print "Error early edition while waiting for show():" 
            print "*********************************************"
            import traceback
            print traceback.format_exc()
            show_original()
            print "*********************************************"
            raise
    finally:
        matplotlib.pyplot.show = show_original
        if pylab_exists:
            pylab.show = show_original
    if keep_show_open_on_exit:
        show_original()

# ***********************
# Running example
# ***********************
import pylab as pl
import time
if __name__ == '__main__':
    with keep_plots_open():
        pl.figure('a')
        pl.plot([1,2,3], [4,5,6])     
        pl.plot([3,2,1], [4,5,6])
        pl.show()

        pl.figure('b')
        pl.plot([1,2,3], [4,5,6])
        pl.show()

        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        time.sleep(1)
        print '...'
        this_will_surely_cause_an_error

如果/当我实现了一个适当的“保持图打开(即使发生错误)并允许显示新的图”,我希望脚本在没有用户干扰的情况下正确退出(用于批处理执行)。

我可能会使用超时问题“脚本结束!”\nPress p如果你想要绘图输出暂停(你有5秒):" from https://stackoverflow.com/questions/26704840/corner-cases-for-my-wait-for-user-input-interruption-implementation。

我所发现的最佳解决方案是,程序不会等待您关闭图形,并将所有的图放在一起,以便您可以并排检查它们,这是在最后显示所有的图。 但是通过这种方式,您不能在程序运行时检查图。

# 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()

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