2012-05-25 28 views
1

我正在嘗試使主循環自動構造並保存圖形,但是我發現這是不可能的,而且我需要單獨選擇每個圖形,打開/顯示並手動保存。有誰知道如何自動化過程。該程序將讀取一個csv文件,並根據參數中指定的行生成圖形。下面的代碼包含下面的代碼,我無法看到我出錯的地方。保存在pyplot中

import matplotlib.pyplot as plt 
import sys, csv, math 

def main(): 
    readAndChart('8to2Ant10Average', 0,1,2, '8to2Ant10: cumulative ethnic and political attacks') 
    readAndChart('8to2Ant10Average',0,8,9, '8to2Ant10: ethnic and political attacks per turn') 
    readAndChart('8to2Ant10Average',0,11,12, '8to2Ant10: ethnic and political attacks as a percentage of total attacks') 

def roundUp(x,y): 
    roun = int(math.ceil(x/y))  
    k = int(roun*y) 
    return k 

def readAndChart(readTitle, r1,r2,r3, graphTitle): 
    time = [] 
    data1 = [] 
    data2 = [] 
    data3 = [] 
    data4 = [] 
    read = csv.reader(open(readTitle + '.csv', 'rb')) 
    legend1 = '' 
    legend2 = '' 

    for row in read: 
     if row[0] == 'turn': 
      legend1 = row[r2] 
      legend2 = row[r3] 

     if row[0] != 'turn': 
      a = row[r1]    
      b = row[r2] 
      c = row[r3] 

      a = float(a); b = float(b); c = float(c) 
      time.append(a) 
      data1.append(b) 
      data2.append(c) 

    axese = [] 
    mt = max(time) 
    mph = max(data1) 
    mpd = max(data2) 

    axese.append(mph) 
    axese.append(mpd) 

    ax = max(axese) 
    print ax 
    if ax < 10 and ax > 1: 
     k = roundUp(ax, 10.0) 

     plt.axis([0,mt, 0, k]) 
    if ax < 100 and ax > 10: 
     k = roundUp(ax, 10.0) 
     plt.axis([0,mt, 0, k]) 
    if ax < 1000 and ax > 100: 
     k = roundUp(ax, 100.0) 
     plt.axis([0,mt, 0, k]) 
    if ax < 10000 and ax > 1000: 
     k = roundUp(ax, 500.0)   
     plt.axis([0,mt, 0, k]) 

    plt.xlabel('generation') 
    plt.ylabel('fequency') 
    plt.title(graphTitle) 
    plt.plot(time, data1, 'r') 
    plt.plot(time, data2, 'b') 

    plt.legend((legend1, legend2),'upper center', shadow=True, fancybox=True) 
    plt.savefig(graphTitle + '.png') 

if __name__=='__main__': main() 
+0

您的代碼看起來很好用一個小小的例外:如果你是在Windows上,我不認爲你可以把一個':'在一個文件名。作爲一個簡單的解決方法,你可以這樣做:'plt.savefig(graphTitle.replace(':','')+'.png')' – bernie

+0

謝謝你做了這個訣竅,但是現在所有的圖形都有另外的行在main()函數的特定部分。抱歉糾纏你,但你有什麼想法? –

+0

啊,以前沒有注意到......你可能會嘗試在'savefig()'調用後清除圖形和/或座標軸,例如:'plt.clf(); plt.cla()'。在該行之後,您還可以這樣做:'plt.close()'關閉當前數字。 – bernie

回答

4

問題1
看樣子你是在Windows上。
Windows不允許您在文件名中放置冒號(:)。
參考,以支持上述聲明:http://support.microsoft.com/kb/289627

即使你是在* nix中,我會建議不要在文件名中使用冒號,因爲有些軟件可能無法正確地處理它。

速戰速決:

plt.savefig(graphTitle.replace(':','') + '.png') 

問題2
正如在評論中提到,你還需要在保存後清除身影。
例子:

plt.savefig(graphTitle.replace(':','') + '.png') 
plt.clf() 
plt.cla() 

或者,也許只是:

plt.savefig(graphTitle.replace(':','') + '.png') 
plt.close() # call w/ no args to close current figure