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()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章