在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()创建的图形。
这可能吗?有时计算很长,如果在检查中间结果时进行计算将会有所帮助。
当前回答
虽然没有直接回答OPs的请求,但我发布了这个变通方法,因为它可能会帮助一些人在这种情况下:
我用pyinstaller创建了一个.exe,因为我不能在我需要生成图形的地方安装python,所以我需要python脚本来生成图形,将其保存为.png,关闭它并继续下一个,在循环中实现为几个图形或使用一个函数。
为此,我使用:
import matplotlib.pyplot as plt
#code generating the plot in a loop or function
#saving the plot
plt.savefig(var+'_plot.png',bbox_inches='tight', dpi=250)
#you can allways reopen the plot using
os.system(var+'_plot.png') # unfortunately .png allows no interaction.
#the following avoids plot blocking the execution while in non-interactive mode
plt.show(block=False)
#and the following closes the plot while next iteration will generate new instance.
plt.close()
其中“var”标识循环中的情节,因此它不会被覆盖。
其他回答
在我看来,这个帖子中的答案提供的方法并不适用于每个系统和更复杂的情况,如动画。我建议在下面的帖子中看看MiKTeX的答案,在那里找到了一个健壮的方法: 如何等待matplotlib动画结束?
最好总是检查您正在使用的库是否支持以非阻塞的方式使用。
但是如果你想要一个更通用的解决方案,或者如果没有其他方法,你可以通过使用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()
这有启动新进程的开销,而且在复杂的场景下有时更难调试,因此我更喜欢其他解决方案(使用matplotlib的非阻塞API调用)
使用关键字'block'来覆盖阻塞行为,例如:
from matplotlib.pyplot import show, plot
plot(1)
show(block=False)
# your code
继续您的代码。
我还必须在我的代码中添加plt.pause(0.001),以真正使它在for循环中工作(否则它只会显示第一个和最后一个plot):
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)
Try
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.show(block=False)
# other code
# [...]
# Put
plt.show()
# at the very end of your script to make sure Python doesn't bail out
# before you finished examining.
show()文档说:
在非交互模式下,显示所有图形并阻塞直到图形关闭;在交互模式下,除非在从非交互模式切换到交互模式之前创建了图形,否则没有效果(不推荐)。在这种情况下,它会显示数字,但不会阻塞。 单个实验关键字参数block可以被设置为True或False以覆盖上面描述的阻塞行为。