1. 程式人生 > >python.matplotlib/datatime/CSV學習範例-讀取CSV格式檔案生成折線圖

python.matplotlib/datatime/CSV學習範例-讀取CSV格式檔案生成折線圖

import csv

from datetime import datetime

from matplotlib import pyplot as plt

filename='D:\python program\weather.csv'

#分析csv標頭檔案

with open(filename) as f:

reader=csv.reader(f)  #生成閱讀器

header_row=next(reader) #將閱讀器物件傳給next返回下一行,本部讀取頭行

#下一行

#讀取資料,獲取日期(row[0])、最高氣溫row[1]、最低氣溫row[3]

dates,highs,lows=[],[],[]

for row in reader:

#對某個日期沒有溫度的異常處理

try:

#將日期字串轉換為表示日期的物件

current_date=datetime.strptime(row[0],"%Y-%m-%d")

high=int(row[1])   #字串轉換成數字讓matplotlib讀取

low=int(row[3])

except ValueError:

print(current_date,'missing data')

else:

dates.append(current_date)

highs.append(high)

lows.append(low)

 #繪製圖形

fig=plt.figure(dpi=128,figsize=(10,6))

plt.plot(dates,highs,c='red',alpha=0.5)

plt.plot(dates,lows,c='blue',alpha=0.5)

#給圖示區域填充顏色

plt.fill_between(dates,highs,lows,facecolor='yellow',alpha=0.1)

#設定圖形格式 

plt.title('daily high and low temperatures, july 2014',fontsize=24)

plt.xlabel('',fontsize=16)

#繪製傾斜的日期標籤

fig.autofmt_xdate()

plt.ylabel('temperature ',fontsize=16)

plt.tick_params(axis='both',which='major',labelsize=16)

plt.show()