### 有没有办法分离matplotlib图，以便计算可以继续？

204429 观看

18回复

2309 作者的声誉

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

### 回应 (18)

29

163237 作者的声誉

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

199

163237 作者的声誉

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

10

163237 作者的声誉

8

2309 作者的声誉

``````from matplotlib.pyplot import draw, figure, show
f1, f2 = figure(), figure()
af1.plot([1,2,3])
af2.plot([6,5,4])
draw()
print 'continuing computation'
show()
``````

PS。matplotlib的OO接口非常有用的指南

6

21424 作者的声誉

``````import sys
import gtk, gobject
import matplotlib
matplotlib.use('GTKAgg')
import pylab as p
import numpy as nx
import time

ax = p.subplot(111)
canvas = ax.figure.canvas

# for profiling
tstart = time.time()

# create the initial line
x = nx.arange(0,2*nx.pi,0.01)
line, = ax.plot(x, nx.sin(x), animated=True)

# save the clean slate background -- everything but the animated line
# is drawn and saved in the pixel buffer background
background = canvas.copy_from_bbox(ax.bbox)

# just a plain global var to pass data (from main, to plot update thread)
global mypass

# http://docs.python.org/library/multiprocessing.html#pipes-and-queues
from multiprocessing import Pipe
global pipe1main, pipe1upd
pipe1main, pipe1upd = Pipe()

# the kind of processing we might want to do in a main() function,
# will now be done in a "main thread" - so it can run in
global mypass
global pipe1main

print "tt"

interncount = 1

mypass += 1
if mypass > 100: # start "speeding up" animation, only after 100 counts have passed
interncount *= 1.03
pipe1main.send(interncount)
time.sleep(0.01)
return

# main plot / GUI update
def update_line(*args):
global mypass
global t0
global pipe1upd

return False

if pipe1upd.poll(): # check first if there is anything to receive
myinterncount = pipe1upd.recv()

update_line.cnt = mypass

# restore the clean slate background
canvas.restore_region(background)
# update the data
line.set_ydata(nx.sin(x+(update_line.cnt+myinterncount)/10.0))
# just draw the animated artist
ax.draw_artist(line)
# just redraw the axes rectangle
canvas.blit(ax.bbox)

if update_line.cnt>=500:
# print the timing info and quit
print 'FPS:' , update_line.cnt/(time.time()-tstart)

t0.join(1)
print "exiting"
sys.exit(0)

return True

update_line.cnt = 0
mypass = 0

global t0
t0.start()

# start the graphics update thread
p.show()

print "out" # will never print - show() blocks indefinitely!
``````

2

21 作者的声誉

``````fig = plt.figure()
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
``````

``````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)
``````

119

3586 作者的声誉

``````from matplotlib.pyplot import show, plot

plot(1)
show(block=False)

``````

21

16928 作者的声誉

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

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

5

1036 作者的声誉

• 您可以打开它，查看它并在此过程中随时关闭它。当您的应用程序运行很长时间时，这非常方便。
• 没有任何东西弹出，你不会被迫打开窗户。当你处理许多数字时，这是特别方便的。
• 您的图像可供以后参考，关闭图形窗口时不会丢失。

• 我唯一能想到的是你必须自己去查找文件夹并打开图像。

3

1556 作者的声誉

``````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
``````

1

304 作者的声誉

5

16792 作者的声誉

``````plt.show(0)
``````

0

529 作者的声誉

``````show(block=False)
draw()
``````

4

1581 作者的声誉

``````import matplotlib.pyplot as plt

plt.scatter([0], [1])
plt.draw()
plt.show(block=False)

for i in range(10):
plt.scatter([i], [i+1])
plt.draw()
plt.pause(0.001)
``````

2

398 作者的声誉

``````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
``````

9

9645 作者的声誉

1. 在show：plt.show中使用block = False （block = False）
2. 在.py脚本的末尾使用另一个 show（）。

`script.py`文件示例

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

plt.show(block = False)

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

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

0

45 作者的声誉

OP要求关于拆分`matplotlib`地块。大多数答案都假定在python解释器中执行命令。这里介绍的用例是我倾向于在终端（例如bash）中测试代码，其中a `file.py`运行并且你想要绘图，但是python脚本要完成并返回到命令提示符。

`multiprocessing`是专为python-only代码执行而设计的，它可能比它更适合`subprocess``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
``````

`ps ax|grep -v grep |grep file.py`

0

467 作者的声誉