[英]python matplotlib save plot
It must be easy but I still cant figure it out. 它一定很容易,但我仍然无法弄清楚。 Suppose I am reading lot of txt file with glob module.And do some processing, and later plotting them with matplotlib. 假设我正在使用glob模块读取大量的txt文件,并进行一些处理,然后再使用matplotlib进行绘制。
import glob
ascii = sorted(glob.glob('C:/Users/ENAMUL/PYTHON/*.txt'))
for count,i in enumerate(ascii):
........
........
Now I want to save those figures. 现在我要保存这些数字。 I can do it like this which will save them by counting numbers. 我可以这样做,这样可以通过计算数字来保存它们。
plt.savefig(str(count)+'png')
But if I want to save them by taking their input file name, how can I do that? 但是,如果我想通过输入输入文件名来保存它们,该怎么办? Any help please. 请帮忙。
In the loop, i
contains the name of the file, so: 在循环中, i
包含文件的名称,因此:
import os.path
....
plt.savefig(os.path.splitext(os.path.basename(i))[0] + '.png')
It works like this. 它是这样的。 os.path.basename
returns the filename: os.path.basename
返回文件名:
In [2]: os.path.basename('foo/bar/baz.bat')
Out[2]: u'baz.bat'
Then splitext
does the obvious: 然后splitext
做splitext
明显:
In [3]: os.path.splitext(os.path.basename('foo/bar/baz.bat'))
Out[3]: (u'baz', u'.bat')
So: 所以:
In [4]: os.path.splitext(os.path.basename('foo/bar/baz.bat'))[0] + '.png'
Out[4]: u'baz.png'
If you want to keep the path, just remove the basename
call, and only use splitext
: 如果要保留路径,只需删除basename
调用,而仅使用splitext
:
In [5]: os.path.splitext('foo/bar/baz.bat')[0] + '.png'
Out[5]: u'foo/bar/baz.png'
您将文件名存储在ascii
-因此在保存图形时应该可以使用它:
plt.savefig(ascii[count] + '.png')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.