2012-11-25 52 views
7

我有這段代碼可以從文件夾中的所有文本文件生成多個地塊。它運行得非常好,顯示情節,但我不能解決如何將它們全部保存。保存多個地塊

import re 
import numpy as np 
import matplotlib.pyplot as plt 
import pylab as pl 
import os 

rootdir='C:\documents\Neighbors for each search id' 

for subdir,dirs,files in os.walk(rootdir): 
for file in files: 
    f=open(os.path.join(subdir,file),'r') 
    print file 
    data=np.loadtxt(f) 

    #plot data 
    pl.plot(data[:,1], data[:,2], 'gs') 

    #Put in the errors 
    pl.errorbar(data[:,1], data[:,2], data[:,3], data[:,4], fmt='ro') 

    #Dashed lines showing pmRa=0 and pmDec=0 
    pl.axvline(0,linestyle='--', color='k') 
    pl.axhline(0,linestyle='--', color='k') 
    pl.show() 

    f.close() 

我以前用過

fileName="C:\documents\FirstPlot.png" 
plt.savefig(fileName, format="png") 

,但我認爲這只是保存每個圖形到一個文件中,並覆蓋上一個。

回答

9

所有你需要做的就是提供獨特的文件名。你可以使用一個計數器:

fileNameTemplate = r'C:\documents\Plot{0:02d}.png' 

for subdir,dirs,files in os.walk(rootdir): 
    for count, file in enumerate(files): 
     # Generate a plot in `pl` 
     pl.savefig(fileNameTemplate.format(count), format='png') 
     pl.clf() # Clear the figure for the next loop 

我做了什麼:

+0

嗨,謝謝你的幫助。我嘗試過這種方法,它的所有工作,但情節都出來了空白。我也使用了pl.show(),並且他們生成了正確的繪圖,而不是實際的節省位。有任何想法嗎? – user1841859

+0

@ user1841859:我不知道。在保存之前,可能需要'pl.show()'?我自己並沒有使用過'pylab'。 –

+0

plt.show()不能來之前plt.savefig 您必須先保存它,然後再顯示它。 – arynaq

0

你做保存情節正確的事情(只要把代碼f.close()之前,並確保使用pl.savefig,而不是plt.savefig,因爲您導入pyplotpl)。你只需要給每個輸出圖表一個不同的文件名。要做到這一點

一種方法是添加得到遞增的每個文件,你經過一個計數器變量,並添加到文件名,例如,做這樣的事情:

fileName = "C:\documents\Plot-%04d.png" % ifile 

另一種選擇是根據輸入的文件名製作一個唯一的輸出文件名。你可以嘗試這樣的:

fileName = "C:\documents\Plot-" + "_".join(os.path.split(os.path.join(subdir,file))) + ".png" 

這將需要輸入路徑,並與_更換任何路徑分隔符。您可以將其用作輸出文件名的一部分。