在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()创建的图形。
这可能吗?有时计算很长,如果在检查中间结果时进行计算将会有所帮助。
当前回答
使用plt.show(block=False),并在脚本的末尾调用plt.show()。
这将确保脚本完成时窗口不会关闭。
其他回答
在我的例子中,我希望在计算窗口时弹出几个窗口。作为参考,方法如下:
from matplotlib.pyplot import draw, figure, show
f1, f2 = figure(), figure()
af1 = f1.add_subplot(111)
af2 = f2.add_subplot(111)
af1.plot([1,2,3])
af2.plot([6,5,4])
draw()
print 'continuing computation'
show()
一个非常有用的matplotlib的OO接口指南。
您可能需要阅读matplotlib文档中的这个文档,标题为:
在python shell中使用matplotlib
我所发现的最佳解决方案是,程序不会等待您关闭图形,并将所有的图放在一起,以便您可以并排检查它们,这是在最后显示所有的图。 但是通过这种方式,您不能在程序运行时检查图。
# 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()
使用关键字'block'来覆盖阻塞行为,例如:
from matplotlib.pyplot import show, plot
plot(1)
show(block=False)
# your code
继续您的代码。
在我的系统上,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)
尽管脚本仍然在运行。