将matplotlib文件保存到目录

kha*_*han 23 python matplotlib

这是一个简单的代码,它在与代码相同的目录中生成并保存绘图图像.现在,有没有办法可以将它保存在选择目录中?

import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(100))

fig.savefig('graph.png')
Run Code Online (Sandbox Code Playgroud)

小智 20

如果要保存的目录是工作目录的子目录,只需指定文件名前的相对路径:

    fig.savefig('Sub Directory/graph.png')
Run Code Online (Sandbox Code Playgroud)

如果要使用绝对路径,请导入os模块:

    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')
Run Code Online (Sandbox Code Playgroud)

如果您不想担心子目录名称前面的前导斜杠,可以智能地连接路径,如下所示:

    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))        
Run Code Online (Sandbox Code Playgroud)

  • 目录的路径应该是 `os.path.dirname(os.path.abspath(__file__))` (2认同)

KL-*_*L-7 14

根据文档 savefig接受文件路径,所以您只需要指定完整(或相对)路径而不是文件名.


cog*_*rus 11

这是将绘图保存到所选目录的一段代码。如果该目录不存在,则创建它。

import os
import matplotlib.pyplot as plt

script_dir = os.path.dirname(__file__)
results_dir = os.path.join(script_dir, 'Results/')
sample_file_name = "sample"

if not os.path.isdir(results_dir):
    os.makedirs(results_dir)

plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.savefig(results_dir + sample_file_name)
Run Code Online (Sandbox Code Playgroud)


mak*_*kis 6

最简单的方式做,这是如下:


save_results_to = '/Users/S/Desktop/Results/'
plt.savefig(save_results_to + 'image.png', dpi = 300)
Run Code Online (Sandbox Code Playgroud)

图像将保存在save_results_to具有名称的目录中image.png


tmd*_*son 5

除了已经给出的答案之外,如果要创建新目录,还可以使用以下功能:

def mkdir_p(mypath):
    '''Creates a directory. equivalent to using mkdir -p on the command line'''

    from errno import EEXIST
    from os import makedirs,path

    try:
        makedirs(mypath)
    except OSError as exc: # Python >2.5
        if exc.errno == EEXIST and path.isdir(mypath):
            pass
        else: raise
Run Code Online (Sandbox Code Playgroud)

然后:

import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(100))

# Create new directory
output_dir = "some/new/directory"
mkdir_p(output_dir)

fig.savefig('{}/graph.png'.format(output_dir))
Run Code Online (Sandbox Code Playgroud)