Python Matplotlib - 强制绘图显示然后返回主代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17149646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Matplotlib - Force plot display and then return to main code
提问by Gabriel
This is a MWE of what I'm after, adapted from this question:
这是我所追求的 MWE,改编自这个问题:
from matplotlib.pyplot import plot, draw, show
def make_plot():
plot([1,2,3])
draw()
print 'continue computation'
print('Do something before plotting.')
# Now display plot in a window
make_plot()
answer = raw_input('Back to main and window visible? ')
if answer == 'y':
print('Excellent')
else:
print('Nope')
show()
What I want is: I call the function to make the plot, the plot window appears, and then I get to go back to the prompt so I can input some value (based on that image that just displayed) and carry on with the code (the window can then close or remain there, I don't care).
我想要的是:我调用函数来制作绘图,绘图窗口出现,然后我回到提示,这样我就可以输入一些值(基于刚刚显示的图像)并继续执行代码(然后窗口可以关闭或保持在那里,我不在乎)。
What I get instead is that the window with the plot only appears afterthe code is completed, which is no good.
我得到的是,只有在代码完成后才会出现带有绘图的窗口,这是不好的。
Add 1
添加 1
I've tried the following with the same results, the plot window appears at the end of the code and not before:
我已经尝试了以下相同的结果,绘图窗口出现在代码的末尾而不是之前:
from matplotlib.pyplot import plot, ion, draw
ion() # enables interactive mode
plot([1,2,3]) # result shows immediately (implicit draw())
# at the end call show to ensure window won't close.
draw()
answer = raw_input('Back to main and window visible? ')
if answer == 'y':
print('Excellent')
else:
print('Nope')
The same happens if I change draw()for show().
如果我更改draw()为show().
Add 2
加2
I've tried the following approach:
我尝试了以下方法:
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 'computation continues...'
print 'Now lets wait for the graph be closed to continue...:'
p.join()
which results in a Python kernel has crashederror in Canopywith the message:
这会导致消息Python kernel has crashed出错Canopy:
The kernel (user Python environment) has terminated with error code -6. This may be due to a bug in your code or in the kernel itself.
Output captured from the kernel process is shown below.
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing /tmp/tmp9cshhw.json
QGtkStyle could not resolve GTK. Make sure you have installed the proper libraries.
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python: ../../src/xcb_io.c:274: poll_for_event: La declaraci?3n `!xcb_xlib_threads_sequence_lost' no se cumple.
I should mention I'm running Canopyin elementary OSwhich is based in Ubuntu 12.04.
我要提到我跑Canopy在elementary OS总部设在Ubuntu 12.04。
Add 3
添加 3
Also tried solution posted in this question:
还尝试了在这个问题中发布的解决方案:
import numpy
from matplotlib import pyplot as plt
if __name__ == '__main__':
x = [1, 2, 3]
plt.ion() # turn on interactive mode
for loop in range(0,3):
y = numpy.dot(x, loop)
plt.figure()
plt.plot(x,y)
plt.show()
_ = raw_input("Press [enter] to continue.")
This displays empty plot windows as the code advances (ie: the user hits [enter]) and only displays the images after the code is finished.
随着代码的推进(即:用户点击 [enter]),这将显示空的绘图窗口,并且仅在代码完成后显示图像。
This solution (also in the same question) doesn't even display the plot windows:
此解决方案(也在同一问题中)甚至不显示绘图窗口:
import numpy
from matplotlib import pyplot as plt
if __name__ == '__main__':
x = [1, 2, 3]
plt.ion() # turn on interactive mode, non-blocking `show`
for loop in range(0,3):
y = numpy.dot(x, loop)
plt.figure() # create a new figure
plt.plot(x,y) # plot the figure
plt.show() # show the figure, non-blocking
_ = raw_input("Press [enter] to continue.") # wait for input from the user
plt.close() # close the figure to show the next one.
采纳答案by David Zwicker
You may use plt.show(block=False), which gets rid of the blocking directly.
您可以使用plt.show(block=False),它可以直接摆脱阻塞。
For your example, this could read
对于您的示例,这可以阅读
from matplotlib.pyplot import plot, show
def make_plot():
plot([1,2,3])
show(block=False)
print('continue computation')
print('Do something before plotting.')
# Now display plot in a window
make_plot()
answer = input('Back to main and window visible? ')
if answer == 'y':
print('Excellent')
else:
print('Nope')
回答by Gabriel
I couldn't get this to work with Canopy(not yet at least) but I could get the code to run sort of like I wanted to using the GeanyIDE. This is the code that works for me, it's a very minor modification to the first block of code in the question where the show()command is moved above from the end of the file to just below the make_plot()command:
我无法使用它Canopy(至少还没有),但我可以让代码运行起来,就像我想使用GeanyIDE 一样。这是对我有用的代码,这是对问题中第一块代码的一个非常小的修改,其中show()命令从文件末尾移到make_plot()命令下方:
from matplotlib.pyplot import plot, draw, show
def make_plot():
plot([1,2,3])
draw()
print 'Plot displayed, waiting for it to be closed.'
print('Do something before plotting.')
# Now display plot in a window
make_plot()
# This line was moved up <----
show()
answer = raw_input('Back to main after plot window closed? ')
if answer == 'y':
print('Move on')
else:
print('Nope')
It doesn't do exactly what I want but it's close enough: it shows a plot to the user, waits till that plot window is closed and then moves on with the code. Ideally it shouldn't have to wait until the plot window is closed to move on with the code, but it's better than nothing I guess.
它并不完全符合我的要求,但已经足够接近了:它向用户显示一个绘图,等待绘图窗口关闭,然后继续执行代码。理想情况下,它不应该等到绘图窗口关闭才能继续执行代码,但我猜总比没有好。
The code in the Add 2section above also works in the same way and with no modifications needed in Geany, but I prefer this one because it's simpler. I'll update this answer If (when?) I get this to work with Canopy.
上面Add 2部分中的代码也以相同的方式工作,并且不需要在 中进行修改Geany,但我更喜欢这个,因为它更简单。我会更新这个答案如果(什么时候?)我可以使用它Canopy。
回答by divenex
None of the presented solutions work for me. I tested them with three different IDEs PyCharm, Spyderand Pyzo, using the (currently) latest Matplotlib 2.1 under Python 3.6.
所提出的解决方案都不适用于我。我使用 Python 3.6 下的(当前)最新的 Matplotlib 2.1 使用三种不同的 IDE PyCharm、Spyder和Pyzo对它们进行了测试。
What works for me, although not optimal, is to use a plt.pausecommand:
对我有用的方法是使用plt.pause命令,虽然不是最优的:
import matplotlib.pyplot as plt
def make_plot():
plt.plot([1, 2, 3])
# plt.show(block=False) # The plot does not appear.
# plt.draw() # The plot does not appear.
plt.pause(0.1) # The plot properly appears.
print('continue computation')
print('Do something before plotting.')
# Now display plot in a window
make_plot()
answer = input('Back to main and window visible? ')
if answer == 'y':
print('Excellent')
else:
print('Nope')

