2021-07-04

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

输出结果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值