import csv
#导入日期包
from datetime import datetime
#导入绘图包
from matplotlib import pyplot as plt
获取数据
filename = ‘death_valley.csv’
#打开数据文件
with open(filename) as f:
reader = csv.reader(f)
#读取下一行
header_row = next(reader)
#定义三个空列表
dates, highs, lows = [], [], []
for row in reader:
#判断数据行是否为空
try:
#row[i]表示数据文件对应的第几列
#日期表示%Y/%m/%d或者%Y-%m-%d
current_date = datetime.strptime(row[0], “%Y-%m-%d”)
high = int(row[1])
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))
#绘制根据时间的最高气温折线,alpha 是设置透明度
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=‘blue’, alpha=0.1)
#设置标题
title = “Daily high and low temperatures - 2014\nDeath Valley, CA”
plt.title(title, fontsize=20)
#设置x y 轴的标签
plt.xlabel(’’, fontsize=16)
#增加时间标签
fig.autofmt_xdate()
plt.ylabel(“Temperature (F)”, fontsize=16)
plt.tick_params(axis=‘both’, which=‘major’, labelsize=16)
plt.show()