解决使用plt.savefig保存图片时一片空白

来源:互联网 发布:网络推广信息方案 编辑:程序博客网 时间:2024/05/22 15:19

问题

当使用如下代码保存使用plt.savefig 保存生成的图片时,结果打开生成的图片确实一片空白。

import matplotlib.pyplot as plt""" 一些画图代码 """plt.show()plt.savefig("filename.png")

原因

其实产生这个现象的原因很简单:在plt.show() 后调用了plt.savefig() ,在plt.show() 后实际上已经创建了一个新的空白的图片(坐标轴),这时候你再plt.savefig() 就会保存这个新生成的空白图片。


解决

知道了原因,就不难知道解决办法了,解决办法有两种:

1 在plt.show() 之前调用plt.savefig()

import matplotlib.pyplot as plt""" 一些画图代码 """plt.savefig("filename.png")plt.show()
2 画图的时候获取当前图像(这一点非常类似于Matlab的句柄的概念):
# gcf: Get Current Figure    fig = plt.gcf()    plt.show()    fig1.savefig('tessstttyyy.png', dpi=100)


另一种解决方法

在用python中的matplotlib 画图时,show()函数总是要放在最后,且它阻止命令继续往下运行,直到1.0.1版本才支持多个show()的使用。想在显示图像后继续运行相关的处理命令,或者显示一副图像后关闭它,再显示第二幅图像。如下办法:首先搜索到:plt.close() will close current instance.plt.close(2) will close figure 2plt.close(plot1) will close figure with instance plot1plt.close('all') will close all fiuresFound here.Remember that plt.show() is a blocking function, so in the example code you used above,plt.close() isn't being executed until the window is closed, which makes it redundant.You can use plt.ion() at the beginning of your code to make it non-blocking, although this has other implications.搜索到:http://matplotlib.org/faq/usage_faq.html#what-is-interactive-mode总结如下例子:import matplotlib.pyplot as pltimport timeplt.ion() #开启interactive modex = np.linspace(0, 50, 1000)plt.figure(1) # 创建图表1plt.plot(x, np.sin(x))plt.draw()time.sleep(5)plt.close(1)plt.figure(2) # 创建图表2plt.plot(x, np.cos(x))plt.draw()time.sleep(5)print 'it is ok'如果不需要关闭图表1,去掉plt.close(1),如果不需要redraw the current figure,那也可以去掉plt.draw()



原创粉丝点击