这将在GUI中显示图形:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
但我如何将图形保存到文件(例如foo.png)中?
这将在GUI中显示图形:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 9])
plt.show()
但我如何将图形保存到文件(例如foo.png)中?
当前回答
除上述内容外,我还为名称添加了__file__,以便图片和Python文件获得相同的名称。我还添加了一些参数以使它看起来更好:
# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'
其他回答
只是一个额外的注释,因为我还不能评论帖子。
如果您使用的是plt.savefig('myfig')或类似行,请确保在保存图像后添加plt.clf()。这是因为savefig不会关闭绘图,如果在没有plt.clf()的情况下添加到绘图,则会添加到上一个绘图。
你可能不会注意到你的情节是否与之前的情节相似,但如果你在循环中保存你的数字,情节将慢慢变得庞大,并使你的脚本变得非常缓慢。
除上述内容外,我还为名称添加了__file__,以便图片和Python文件获得相同的名称。我还添加了一些参数以使它看起来更好:
# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'
嗯,我确实建议使用包装器来渲染或控制绘图。示例可以是mpltex(https://github.com/liuyxpp/mpltex)或prettyplotlib(https://github.com/olgabot/prettyplotlib).
import mpltex
@mpltex.acs_decorator
def myplot():
plt.figure()
plt.plot(x,y,'b-',lable='xxx')
plt.tight_layout(pad=0.5)
plt.savefig('xxxx') # the figure format was controlled by the decorator, it can be either eps, or pdf or png....
plt.close()
我基本上经常使用这个装饰器在美国化学学会、美国物理学会、美国光学学会、Elsivier等各种期刊上发表学术论文。
示例如下图所示(https://github.com/MarkMa1990/gradientDescent):
使用matplotlib.pyplot.savefig时,可以通过扩展名指定文件格式:
from matplotlib import pyplot as plt
plt.savefig('foo.png')
plt.savefig('foo.pdf')
这分别提供光栅化或矢量化输出。此外,图像周围有时存在不希望有的空白,可以通过以下方式删除:
plt.savefig('foo.png', bbox_inches='tight')
注意,如果显示绘图,plt.show()应跟随plt.savefig();否则,文件图像将为空。
如前所述,您可以使用:
import matplotlib.pyplot as plt
plt.savefig("myfig.png")
用于保存您正在显示的任何IPhython图像。或者换个角度(从不同的角度看),如果你曾经使用过open cv,或者你已经导入了open cv的话,你可以去:
import cv2
cv2.imwrite("myfig.png",image)
但这只是为了以防万一,如果您需要使用OpenCV。否则plt.savefig()就足够了。