将matplotlib文件保存到目录 [英] Save matplotlib file to a directory
本文介绍了将matplotlib文件保存到目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是简单的代码,可在该代码的同一目录中生成并保存绘图图像.现在,有没有一种方法可以将其保存在所选目录中?
Here is the simple code which generates and saves a plot image in the same directory as of the code. Now, is there a way through which I can save it in directory of choice?
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(100))
fig.savefig('graph.png')
推荐答案
如果要保存到的目录是工作目录的子目录,只需在文件名之前指定相对路径即可:
If the directory you wish to save to is a sub-directory of your working directory, simply specify the relative path before your file name:
fig.savefig('Sub Directory/graph.png')
如果您希望使用绝对路径,请导入 os 模块:
If you wish to use an absolute path, import the os module:
import os
my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
...
fig.savefig(my_path + '/Sub Directory/graph.png')
如果您不想担心子目录名称前的斜杠,可以按以下方式智能地连接路径:
If you don't want to worry about the leading slash in front of the sub-directory name, you can join paths intelligently as follows:
import os
my_path = os.path.abspath(__file__) # Figures out the absolute path for you in case your working directory moves around.
my_file = 'graph.png'
...
fig.savefig(os.path.join(my_path, my_file))
这篇关于将matplotlib文件保存到目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文