这将在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)中?
当前回答
如果您不喜欢“当前”数字的概念,请执行以下操作:
import matplotlib.image as mpimg
img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)
其他回答
您可以使用任何扩展名(png、jpg等)和所需的分辨率保存图像。这里有一个功能来保存您的身材。
import os
def save_fig(fig_id, tight_layout=True, fig_extension="png", resolution=300):
path = os.path.join(IMAGES_PATH, fig_id + "." + fig_extension)
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(path, format=fig_extension, dpi=resolution)
“fig_id”是您希望保存数字的名称。希望它有帮助:)
如果您不喜欢“当前”数字的概念,请执行以下操作:
import matplotlib.image as mpimg
img = mpimg.imread("src.png")
mpimg.imsave("out.png", img)
嗯,我确实建议使用包装器来渲染或控制绘图。示例可以是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输出空白图像。
有一点需要注意:如果您使用plt.show,并且它应该在plt.savefig之后,否则您将给出一个空白图像。
详细示例:
import numpy as np
import matplotlib.pyplot as plt
def draw_result(lst_iter, lst_loss, lst_acc, title):
plt.plot(lst_iter, lst_loss, '-b', label='loss')
plt.plot(lst_iter, lst_acc, '-r', label='accuracy')
plt.xlabel("n iteration")
plt.legend(loc='upper left')
plt.title(title)
plt.savefig(title+".png") # should before plt.show method
plt.show()
def test_draw():
lst_iter = range(100)
lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
# lst_loss = np.random.randn(1, 100).reshape((100, ))
lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
# lst_acc = np.random.randn(1, 100).reshape((100, ))
draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")
if __name__ == '__main__':
test_draw()
你可以这样做:
def plotAFig():
plt.figure()
plt.plot(x,y,'b-')
plt.savefig("figurename.png")
plt.close()