python编程第16章
下载数据CSV文件格式
锡特卡和死亡谷数据对比
import csv
from datetime import datetime
import matplotlib.pyplot as plt
def get_weather_data(filename,dates,highs,lows,date_index,high_index,low_index):
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
#从文件中获取日期、最高温度和最低温度
for row in reader:
current_date=datetime.strptime(row[date_index], '%Y-%m-%d')
try:
high=int(row[high_index])
low=int(row[low_index])
except ValueError:
print(f"Missing data for {current_date}.")
else:
dates.append(current_date)
highs.append(high)
lows.append(low)
#获取锡特卡的气温数据
filename1='F:/Python_work/SS16/the_csv_formate/data/sitka_weather_2018_simple.csv'
dates,highs,lows=[],[],[]
get_weather_data(filename1,dates,highs,lows,date_index=2,high_index=5,low_index=6)
#根据最低温和最高温度绘制图形
plt.style.use('seaborn')
fig,ax=plt.subplots()
ax.plot(dates,highs, c='red',alpha=0.6)
ax.plot(dates,lows,c='blue',alpha=0.6)
ax.fill_between(dates,highs,lows,facecolor='blue',alpha=0.15)
#获取死亡谷气温数据
filename2='F:/Python_work/SS16/the_csv_formate/data/death_valley_2018_simple.csv'
dates,highs,lows=[],[],[]
get_weather_data(filename2,dates,highs,lows,date_index=2,high_index=4,low_index=5)
#将死亡谷数据添加到当前图表中
ax.plot(dates,highs,c='red',alpha=0.3)
ax.plot(dates,lows,c='blue',alpha=0.3)
plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.05)
#设置图形格式
title="2018年每日最高温度和最低温度"
title+="\n美国阿拉斯加州锡特卡(深色)\n加利福尼亚死亡峡谷(浅色)"
ax.set_title(title,fontproperties='SimHei',fontsize=16)
ax.set_xlabel('',fontsize=16)
fig.autofmt_xdate()
ax.set_ylabel("温度 (F)",fontproperties='SimHei',fontsize=16)
#y_ticks_label=range(130)
#plt.yticks(y_ticks_label[::10])
ax.tick_params(axis='both', which='major', labelsize=16)
plt.ylim(10,130)
plt.show()
输出结果