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

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

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

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


当前回答

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

优点:

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

缺点:

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

其他回答

重要提示:只是为了澄清一些事情。我假设命令在.py脚本中,脚本是使用python script.py从控制台调用的。

对我来说,一个简单的方法是:

使用block = False在里面显示:plt。show(block = False) 在.py脚本的末尾使用另一个show()。


script.py文件示例:

plt.imshow(*something*)                                                               
plt.colorbar()                                                                             
plt.xlabel("true ")                                                                   
plt.ylabel("predicted ")                                                              
plt.title(" the matrix")  

# Add block = False                                           
plt.show(block = False)

################################
# OTHER CALCULATIONS AND CODE HERE ! ! !
################################

# the next command is the last line of my script
plt.show()

我还希望我的图显示运行其余的代码(然后继续显示),即使出现错误(我有时使用图进行调试)。我编写了这个小代码,让这个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。

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

在我的系统上,show()没有阻塞,尽管我希望脚本在继续之前等待用户与图形交互(并使用'pick_event'回调来收集数据)。

为了阻止执行直到绘图窗口关闭,我使用了以下方法:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(x,y)

# set processing to continue when window closed
def onclose(event):
    fig.canvas.stop_event_loop()
fig.canvas.mpl_connect('close_event', onclose)

fig.show() # this call does not block on my system
fig.canvas.start_event_loop_default() # block here until window closed

# continue with further processing, perhaps using result from callbacks

但是请注意,canvas.start_event_loop_default()产生了以下警告:

C:\Python26\lib\site-packages\matplotlib\backend_bases.py:2051: DeprecationWarning: Using default event loop until function specific to this GUI is implemented
  warnings.warn(str,DeprecationWarning)

尽管脚本仍然在运行。

Try

import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.show(block=False)
# other code
# [...]

# Put
plt.show()
# at the very end of your script to make sure Python doesn't bail out
# before you finished examining.

show()文档说:

在非交互模式下,显示所有图形并阻塞直到图形关闭;在交互模式下,除非在从非交互模式切换到交互模式之前创建了图形,否则没有效果(不推荐)。在这种情况下,它会显示数字,但不会阻塞。 单个实验关键字参数block可以被设置为True或False以覆盖上面描述的阻塞行为。