python从入门到实践第十六章答案

16.2

import csv
from matplotlib import pyplot as plt
from datetime import datetime
#读取第一个文件数据
filename_1 = 'sitka_weather_2014.csv'
with open(filename_1) as f1:
    reader1 = csv.reader(f1)
    header_row1 = next(reader1)

    highs1, dates1, lows1 = [], [], []
    for row in reader1:
        try:
            current_date1 = datetime.strptime(row[0], "%Y-%m-%d")
            high1 = int(row[1])
            low1 = int(row[3])
        except ValueError:
            print(current_date1, 'missing data')
        else:
            dates1.append(current_date1)
            highs1.append(high1)
            lows1.append(low1)
filename_2 = 'death_valley_2014.csv'
#读取第二个文件数据
with open(filename_2) as f2:
    reader2 = csv.reader(f2)
    header_row2 = next(reader2)

    highs2, dates2, lows2 = [], [], []
    for row in reader2:
        try:
            current_date2 = datetime.strptime(row[0], "%Y-%m-%d")
            high2 = int(row[1])
            low2 = int(row[3])
        except ValueError:
            print(current_date2, 'missing data')
        else:
            dates2.append(current_date2)
            highs2.append(high2)
            lows2.append(low2)

#根据数据绘制图形
fig = plt.figure(dpi = 128,figsize = (10,6))
plt.plot(dates1,highs1,c = 'red',alpha = 0.5)
plt.plot(dates1,lows1,c = 'blue',alpha = 0.5)
plt.fill_between(dates1,highs1,lows1,facecolor = 'blue',alpha = 0.1)
plt.plot(dates2,highs2,c = 'yellow',alpha = 0.5)
plt.plot(dates2,lows2,c = 'green',alpha = 0.5)
plt.fill_between(dates2,highs2,lows2,facecolor = 'blue',alpha = 0.1)

#设置图形的格式
plt.xlabel('',fontsize = 16)
fig.autofmt_xdate()
plt.ylabel("Temperature(F)",fontsize = 16)
plt.tick_params(axis = 'both',which = 'major',labelsize = 16)
title = "Daily high and low temperatures - 2014\nDeath Valley and Sitka Weather,CA"
plt.title(title,fontsize = 20)

plt.show()

把2个数据放到了一个图中显示

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值