2012-07-07 451 views
13

下面是生成並保存與代碼相同的目錄中的打印圖像的簡單代碼。現在,我可以通過哪種方式將它保存在選擇的目錄中?將matplotlib文件保存到目錄

import matplotlib 
import matplotlib.pyplot as plt 

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

fig.savefig('graph.png') 

回答

11

按照docssavefig接受文件路徑,因此,所有你需要的是指定一個完整的(或相對)路徑,而不是一個文件名。

9

如果你希望保存的目錄是你的工作目錄的子目錄,只需將文件名前指定的相對路徑:如果你想使用絕對路徑

fig.savefig('Sub Directory/graph.png') 

,導入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') 

如果你不想擔心的子目錄名稱前的斜線,可以智能化地結合路徑如下:

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))   
0

除了答案已經給出,如果要創建一個新的目錄,你可以使用這個功能:

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 

然後:

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)) 
1

下面是一段代碼,將繪圖保存到選定的目錄。如果該目錄不存在,則創建該目錄。

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) 
1

下面是使用Python版本2.7.10與崇高的文本保存到一個目錄(外部USB驅動器)2編輯器一個簡單的例子:

import numpy as np 
import matplotlib.pyplot as plt 

X = np.linspace(-np.pi, np.pi, 256, endpoint = True) 
C, S = np.cos(X), np.sin(X) 

plt.plot(X, C, color = "blue", linewidth = 1.0, linestyle = "-") 
plt.plot(X, S, color = "red", linewidth = 1.0, linestyle = "-") 

plt.savefig("/Volumes/seagate/temp_swap/sin_cos_2.png", dpi = 72) 
0
plt.plot(x,y) 
plt.savefig('___fullpath____/figure.jpg') 
plt.show() 

請使用 「___fullpath____」 從文件夾的屬性