Matplotlib - 强制绘图显示然后返回主代码

时间:2013-06-17 14:10:44

标签: python matplotlib enthought

这是我所追求的MWE,改编自this question

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

我想要的是:我调用函数来创建绘图,出现绘图窗口,然后我返回到提示符,以便我可以输入一些值(基于刚刚显示的图像)并继续使用代码(窗口可以关闭或保留在那里,我不在乎)。

我得到的是,带有图表的窗口仅在代码完成后出现,这是不行的。


添加1

我尝试了以下相同的结果,绘图窗口出现在代码的末尾而不是之前:

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

如果我为draw()更改show(),也会发生相同的情况。


添加2

我尝试了以下方法:

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

导致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ón `!xcb_xlib_threads_sequence_lost' no se cumple.

我应该提到我在Canopy elementary OS中运行Ubuntu 12.04


添加3

还尝试了在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.")

当代码前进时显示空的绘图窗口(即:用户点击[enter])并且仅在代码完成后显示图像。

此解决方案(也在同一问题中)甚至不显示绘图窗口:

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.

3 个答案:

答案 0 :(得分:23)

您可以使用plt.show(block=False),直接删除阻止。

对于您的示例,可以阅读

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

答案 1 :(得分:8)

所提供的解决方案都不适合我。我使用三个不同的IDE PyCharmSpyderPyzo测试它们,使用Python 3.6下的(当前)最新的Matplotlib 2.1。

对我来说,虽然不是最佳的,但是使用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')

答案 2 :(得分:1)

我无法使用Canopy(至少还没有),但我可以让代码运行,就像我想使用Geany IDE一样。这是适合我的代码,它是对问题中第一个代码块的一个非常小的修改,其中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')

它并不完全符合我的要求,但它足够接近:它向用户显示一个情节,等待该情节窗口关闭然后继续使用代码。理想情况下,它不应该等到关闭绘图窗口以继续使用代码,但它总比没想象的要好。

上面添加2 部分中的代码也以同样的方式工作,Geany中无需修改,但我更喜欢这个,因为它更简单。我会更新这个答案如果(何时?)我可以使用Canopy