2012-07-07 46 views
13

Đây là mã đơn giản tạo và lưu hình ảnh lô trong cùng thư mục với mã. Bây giờ, có cách nào để tôi có thể lưu nó trong thư mục lựa chọn không?Lưu tập tin matplotlib vào thư mục

import matplotlib 
import matplotlib.pyplot as plt 

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

fig.savefig('graph.png') 

Trả lời

11

Theo docssavefig chấp nhận một đường dẫn tập tin, vì vậy tất cả bạn cần là để xác định một đường dẫn đầy đủ (hoặc người thân) thay vì một tên tập tin.

9

Nếu thư mục bạn muốn lưu vào một thư mục con của thư mục làm việc của bạn, chỉ cần chỉ định đường dẫn tương đối trước tên tập tin của bạn:

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

Nếu bạn muốn sử dụng một đường dẫn tuyệt đối, nhập khẩu os mô-đun:

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

Nếu bạn không muốn lo lắng về các dấu gạch chéo hàng đầu ở phía trước của tên thư mục, bạn có thể tham gia đường dẫn một cách thông minh như sau:

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

Ngoài các câu trả lời đã được đưa ra, nếu bạn muốn tạo một thư mục mới, bạn có thể sử dụng chức năng này:

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 

và sau đó:

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

Dưới đây là những đoạn mã mà lưu âm mưu vào thư mục đã chọn. Nếu thư mục không tồn tại, nó sẽ được tạo.

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

Đây là một ví dụ đơn giản để lưu vào một thư mục (ổ đĩa USB bên ngoài) sử dụng Python phiên bản 2.7.10 với các dòng chữ Sublime 2 biên tập:

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

xin vui lòng sử dụng "___fullpath____" từ thuộc tính của thư mục

Các vấn đề liên quan