2016-06-10 135 views
1

我是新來的蟒蛇世界。我試圖創建一個圖表,顯示在給定時間段內所選城市的累計GDD(增長度天數)與時間的關係在Python中繪製累積圖形

我寫了一個函數來完成這個任務,但似乎無法使其工作對。我不斷收到一個空的陰謀。還有一個尺寸錯誤。任何人都知道我可以如何解決這些問題。

任何幫助/建議表示讚賞!

下面是代碼

import sys, argparse, csv 
import numpy as np 

import matplotlib.pyplot as plt 
import matplotlib.dates as mdates 
import datetime as dt 

def open_file(file_name, mode): 
    """Open a file.""" 
    try: 
     with open(sys.argv[1], 'r') as the_file: 
      filename=the_file.read() 

    except IOError as err: 
     print("Unable to open the file", file_name, "Ending program.\n", err) 
     input("\n\nPress the enter key to exit.") 
     sys.exit() 
    else: 
     return filename 

"""Cities.txt file as an argument"""  
try: 
    my_file = open_file(sys.argv[1], 'r') 
except: 
    print("GDD needs one argument", "\nEnding program...\n") 
    input("Press the enter key to exit.") 
    sys.exit() 


extension=".csv" 
for line in my_file.splitlines(): 
    file_name=line+extension 
    print(file_name) 
    with open('data/'+ file_name, "rU") as files: 
     val = list(csv.DictReader(files)) 
     l = [] 
    for i in range(0, len(val)): 
     row = val[i] 
     if row['Min Temp'] == '' or row['Max Temp'] == '': 
       pass 
     else: 
      GDD = ((float(row['Min Temp']) + float(row['Max Temp']))/2)-10 
      l.append(GDD) 

      val[i]['GDD'] = GDD 

      #print(row['Min Temp'], ' ' , row['Max Temp'], ' ', str(round(row['GDD'], 2))) 

      #plt.subplot(1,1,1)   
      #x = np.linspace(1, 12, 365, endpoint=True) 


    x = np.linspace(1, 12, 365, endpoint=True) 
    plt.plot(x,GDD, label = file_name.split(',')[0]) 
    plt.gcf().autofmt_xdate() 
    plt.legend(loc="upper left") 

    plt.xlabel('Months', color='black') 
    plt.ylabel('Cumulative GDD (>10°C)') 
    plt.title('Accumulated Growing Degree Days') 
    plt.draw()   

回答

0

一個簡單而快速的解決方案可能是一個陰謀的呼叫後添加plt.hold(True)

一個更乾淨的解決方案是使用一個可以作爲窗口繪製的圖形。 just like in this example

所以你定義一個數字,保持其基準,加軸和這些軸執行所有動作

fig = plt.figure() 
ax = fig.add_axes([0.1, 0.1, 0.4, 0.7]) 
ax.plot(...) 
+0

感謝,得到它固定 – Jake