1. 程式人生 > >python讀取txt天氣資料並使用matplotlib模組繪圖

python讀取txt天氣資料並使用matplotlib模組繪圖

  天氣資料可以從網上下載,這個例子的資料是從http://data.cma.cn/下載而來的。

  下載的資料裝在txt檔案中。

  

  裡面包含了12年開始北京的月最低和最高溫度。

  讀取資料:

1 with open('S201812261702093585500.txt') as file_object:
2     lines=file_object.readlines()

  將txt中的資料逐行存到列表lines裡 lines的每一個元素對應於txt中的一行。然後將每個元素中的不同資訊提取出來:

1 file1=[] 
2 row=[]
3 for line in
lines: 4 row=line.split() #指定空格作為分隔符對line進行切片 5 file1.append(row)

  這樣,所有的資訊都存在了中file1中,file1嵌套了列表row,file1中的每一元素包含了一個列表,所有的資訊都被分隔開了。

  可以print(file1)看一下:

  需要使用第2、3、4、5列的年、月、最低溫度、最高溫度資訊,將它們分別提取出來。

 1 date=[]
 2 highs=[]
 3 lows=[]
 4 for row1 in file1:
 5     a=row1[1]+"-"+row1[2] #合併年月
6 date.append(a) 7 for row1 in file1: 8 lows.append(row1[3]) 9 highs.append(row1[4])

  在讀資料時將表頭也讀進去了,刪除列表第一個元素

1 del highs[0]
2 del lows[0]
3 del date[0]

  現在,日期和溫度資料被分別存在date、highs、lows三個列表裡,但是還不能直接使用,因為提取出來的都是字元型資料,轉換資料格式為int型:

1 int_highs=[]
2 for str_h in highs:
3     a=int(float(str_h))
4 int_highs.append(a) 5 6 int_lows=[] 7 for str_l in lows: 8 a=int(float(str_l)) 9 int_lows.append(a)

  將日期轉換為日期格式,需要使用datetime模組,在檔案開頭加上from datetime import datetime,:

1 from datetime import datetime
2 dates=[]
3 for a in date:
4     current_dates=datetime.strptime(a,'%Y-%m')
5     dates.append(current_dates)

  匯入matplotlib模組

1 from matplotlib import pyplot as plt
2 import matplotlib.dates as mdates

  下面就準備畫圖啦:

 1 fig=plt.figure(figsize=(10,6))
 2 ax1=fig.add_subplot(111) # 將畫面分割為1行1列選第一個
 3 ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))#設定橫軸為日期格式
 4 ax1.plot(dates,int_highs,c="red")#畫最高溫度,顏色紅
 5 ax1.plot(dates,int_lows,c="blue")#畫最低溫度,顏色藍
 6 fig.autofmt_xdate()
 7 ax1.set_title("Daily Max and Min TemperatureC",fontsize=14)#標題
 8 ax1.set_ylabel("Temperature  (℃)")#縱軸label
 9 ax1.tick_params(direction='in')#刻度向裡
10 plt.show()

  畫好的圖: