引入csv模块
从matplotlib引入pyplot模块
从datetime引入datetime
import csv
from matplotlib import pyplot
from datetime import datetime
传入并打开下载好的天气文件
filename = 'death_valley_2014.csv'
f = open(filename)
reader = csv.reader(f)
header_row = next(reader)
创建日期、最高温、最低温三个列表
并用try...except...else将空数据错误跳过
#读取文件中最高温
dates = []
highs = []
lows = []for row in reader:
try:
current_date = datetime.strptime(row[0],"%Y-%m-%d")
high = int(row[1])
low = int(row[3])
except ValueError:
print(str(current_date)+"数据丢失!")
else:
dates.append(current_date)
highs.append(high)
lows.append(low)
#根据数据绘制图形
fig = pyplot.figure(dpi=100,figsize = (13,6))
pyplot.plot(dates,highs,c='red',alpha=1)
pyplot.plot(dates,lows,c='blue',alpha=1)
pyplot.fill_between(dates,highs,lows,facecolor='yellow',alpha=1)
#设置图形格式
pyplot.title("Daily high and low Temperatures!",fontsize = 20)
pyplot.xlabel("date",fontsize = 14)
fig.autofmt_xdate()
pyplot.ylabel("Temperature",fontsize = 14)
pyplot.tick_params(axis='both',which='major',labelsize=14)pyplot.savefig('temp.png')
plt.show()