这将在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 pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
plt.figure()
ts.plot()
plt.savefig("foo.png", bbox_inches='tight')
如果您想显示图像并保存图像,请使用:
%matplotlib inline
之后导入matplotlib
其他回答
根据问题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()
使用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();否则,文件图像将为空。
没有什么对我有用。问题是保存的图像很小,我找不到它是怎么变大的。
这似乎使它更大,但仍然不是全屏。
https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure.set_size_inches
图set_size_inches((宽,高))
希望这对某人有所帮助。
解决方案是:
pylab.savefig('foo.png')