我正在写一个快速和肮脏的脚本,以便在飞行中生成绘图。我使用下面的代码(来自Matplotlib文档)作为起点。
from pylab import figure, axes, pie, title, show
# Make a square figure and axes
figure(1, figsize=(6, 6))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15, 30, 45, 10]
explode = (0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor': '0.8', 'pad': 5})
show() # Actually, don't show, just save to foo.png
我不想在图形用户界面上显示图,而是想把图保存到一个文件中(比如foo.png),这样就可以在批处理脚本中使用。我怎样才能做到这一点?
虽然这个问题已经得到了回答,但我想补充一些使用matplotlib.pyplot.savefig时的有用提示。文件格式可以通过扩展名来指定。
from matplotlib import pyplot as plt
plt.savefig('foo.png')
plt.savefig('foo.pdf')
将分别给出栅格化或矢量化的输出,这两种都可能是有用的。此外,你会发现pylab
会在图像周围留下大量的、通常不受欢迎的空白。用以下方法去除。
savefig('foo.png', bbox_inches='tight')
正如其他人所说,plt.savefig()
或fig1.savefig()
确实是保存图像的方法。
但是我'发现在某些情况下,图总是显示。
(例如:在Spyder有pl.savefig()
的情况下。
与Spyder有plt.ion()
.交互模式=On。
我通过使用plt.close(fig_object)
强制关闭巨大循环中的数字窗口来解决这个问题 (参见 [document][1]),这样我就不会在循环过程中打开一百万个数字。
import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 ) # create figure & 1 axis
ax.plot([0,1,2], [10,20,3])
fig.savefig('path/to/save/image/to.png') # save the figure to file
plt.close(fig) # close the figure window
如果需要的话,你应该可以在以后用fig.show()
重新打开这个图(我自己没有测试)。
[1]: https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.close.html
刚刚在MatPlotLib文档中找到了这个链接,正好解决了这个问题。 http://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear
他们说,防止数字弹出的最简单方法是使用非交互式后台(如:Agg),通过matplotib.use(<backend>)
,如:matplotib.use(,防止数字弹出。 Agg),通过
matplotib.use(
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')
我个人还是更喜欢使用plt.close( fig )
,因为这样你就可以选择隐藏某些数字(在循环过程中),但在循环后的数据处理中仍然显示数字。
不过这可能比选择一个非交互式的后端要慢--如果有人测试过会很有意思。
更新:
对于Spyder来说,你通常不能这样设置后台(因为Spyder通常会提前加载matplotlib,阻止你使用matplotlib.use()
)。
取而代之的是使用plt.switch_backend('Agg')
,或者关闭"enable support"
在Spyder prefs中,自己运行matplotlib.use('Agg')
命令。
从这两个提示来看。 [1][1],[2][2]。
[1]: https://stackoverflow.com/questions/44086597/cant-use-matplotlib-useagg-graphs-always-show-on-the-screen [2]: https://stackoverflow.com/questions/53617655/anaconda-on-mac-cant-set-matplotlib-backend-to-agg/53623640#53623640
其他答案都是正确的。 但是,我有时会发现,我以后想打开图*对象。 例如,我可能想改变标签大小,添加网格,或进行其他处理。 在一个完美的世界里,我会简单地重新运行生成图的代码,并调整设置。 唉,这个世界并不完美。 因此,除了保存为 PDF 或 PNG 之外,我还添加了。
with open('some_file.pkl', "wb") as fp:
pickle.dump(fig, fp, protocol=4)
这样,我以后就可以加载图对象,并按照自己的意愿进行设置。
我还把堆栈中每个函数/方法的源代码和locals()
字典写出来,这样以后我就可以知道到底是什么产生了这个图。
NB: 要小心,因为有时这种方法会产生巨大的文件。
在使用 plot() 和其他函数创建你想要的内容后,你可以使用这样的子句来选择绘制到屏幕上还是绘制到文件中。
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4, 5)) # size in inches
# use plot(), etc. to create your plot.
# Pick one of the following lines to uncomment
# save_file = None
# save_file = os.path.join(your_directory, your_file_name)
if save_file:
plt.savefig(save_file)
plt.close(fig)
else:
plt.show()
import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
plt.figure(figsize=(3, 3))
plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
plt.title('Page One')
pdf.savefig() # saves the current figure into a pdf page
plt.close()
plt.rc('text', usetex=True)
plt.figure(figsize=(8, 6))
x = np.arange(0, 5, 0.1)
plt.plot(x, np.sin(x), 'b-')
plt.title('Page Two')
pdf.savefig()
plt.close()
plt.rc('text', usetex=False)
fig = plt.figure(figsize=(4, 5))
plt.plot(x, x*x, 'ko')
plt.title('Page Three')
pdf.savefig(fig) # or you can pass a Figure object to pdf.savefig
plt.close()
# We can also set the file's metadata via the PdfPages object:
d = pdf.infodict()
d['Title'] = 'Multipage PDF Example'
d['Author'] = u'Jouni K. Sepp\xe4nen'
d['Subject'] = 'How to create a multipage pdf file and set its metadata'
d['Keywords'] = 'PdfPages multipage keywords author title subject'
d['CreationDate'] = datetime.datetime(2009, 11, 13)
d['ModDate'] = datetime.datetime.today()
我采用了以下方法。
import matplotlib.pyplot as plt
p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05), ncol=2, fancybox=True, shadow=True)
plt.savefig('data.png')
plt.show()
f.close()
plt.close()
我发现保存图形后使用plt.show是非常重要的,否则将无法工作。[图形以png格式导出][1]
你可以这样做。
plt.show(hold=False)
plt.savefig('name.pdf')
并记得在关闭GUI图之前让savefig完成。 这样你就可以提前看到图像了。
另外,你也可以用plt.show()
来查看。
然后关闭GUI并再次运行脚本,但这次用plt.savefig()
替换plt.show()
。
或者,你也可以使用 "plt.savefig() "来代替
fig, ax = plt.figure(nrows=1, ncols=1)
plt.plot(...)
plt.show()
fig.savefig('out.pdf')
解决方案 :
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
之后
import matplotlib
根据问题https://stackoverflow.com/q/9012487/6329006。
有一件事需要注意。
如果你使用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()
[![在此输入图像描述][1]][1]
除了以上这些,我还在名称中添加了__file__
,这样图片和Python文件的名称就相同了。
我还添加了一些参数来使它看起来更好。
# 将当前图形的PNG文件保存到文件夹中,并每次更新。
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='紧')
# 硬编码名称。
'./test.png'
最后的提示发现[这里][1]。
你可以用任何扩展名(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' 是你想保存你的人物的名字。 希望能帮到你。)