是否有方法分离matplotlib绘图以便继续计算?

2024-03-28 14:44:48 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python解释器中执行这些指令后,将得到一个带有绘图的窗口:

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

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

有可能吗?有时计算时间很长,如果在检查中间结果时继续计算,会有帮助。


Tags: fromimport程序图形绘图plotmatplotlibshow
3条回答

使用不会阻塞的matplotlib调用:

使用draw()

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

使用关键字“block”覆盖阻塞行为,例如

from matplotlib.pyplot import show, plot

plot(1)  
show(block=False)

# your code

继续你的代码。

如果您使用的库支持以非阻塞方式使用,则最好始终与它联系。

但是,如果您想要一个更通用的解决方案,或者如果没有其他方法,您可以使用python中包含的^{}模块在一个分离的进程中运行任何阻塞。计算将继续:

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

这有启动一个新进程的开销,有时在复杂的场景中很难调试,所以我更喜欢另一个解决方案(使用matplotlibnonblocking API calls

相关问题 更多 >