【Python从⼊门到实践】16章习题
16-2 ⽐较锡卡特和死亡⾕的⽓温
使y轴具有固定的刻度,并将两个温度的数据集展⽰在同⼀个图当中。
Thinking:最直接的⽅法就是⽤不同的变量名在同⼀个py下,将两个数据集的数据传给plot,即可在⼀个图中展⽰。
我尝试使⽤了重构的思想,将获取数据单独写了⼀个Class出来,然后创建两个对象,原理上是⼀样的,只是为了锻炼下⾃⼰类及函数的使⽤,见笑。
另外,图中的颜⾊可以⾃⾏调整,会更明显的看出两个地区的温度差异。
#Get_info.py
import csv
from datetime import datetime
"""在缺失代码处,为了偷懒,所以将缺失的数据置为0,从图中可明显看出"""
class Get_info():
"""获取数据集当中的⽇期、最⾼温度及最低温度的数据"""
def__init__(self, filename):
self.dates = []
self.highs = []
self.lows = []
self.filename = filename
def get_dates(self):
with open(self.filename) as f:
reader = ader(f)
header_row = next(reader)
for row in reader:
try:
python新手函数
current_date = datetime.strptime(row[0], '%Y-%m-%d')
except ValueError:
print('missing data')
else:
self.dates.append(current_date)
def get_highs(self):
with open(self.filename) as f:
reader = ader(f)
header_row = next(reader)
for row in reader:
try:
high = int(row[1])
except ValueError:
self.highs.append(0)
else:
self.highs.append(high)
def get_lows(self):
with open(self.filename) as f:
reader = ader(f)
header_row = next(reader)
for row in reader:
try:
low = int(row[3])
except ValueError:
self.lows.append(0)
else:
self.lows.append(low)
#text.py
from matplotlib import pyplot as plt
from chapter16.Get_info import Get_info
"""创建两个实例对象,使⽤plot绘制图形"""
filename1='sitka_weather_2014.csv'
filename2='death_valley_2014.csv'
files1=Get_info(filename1)
files2=Get_info(filename2)
<_dates()
<_highs()
<_lows()
<_dates()
<_highs()
<_lows()
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(files1.dates,files1.highs,c='red',alpha=0.5)
plt.plot(files1.dates,files1.lows,c='blue',alpha=0.5)
plt.plot(files2.dates,files2.highs,c='red',alpha=0.3)
plt.plot(files2.dates,files2.lows,c='blue',alpha=0.3)
plt.fill_between(files2.dates,files2.highs,files2.lows,facecolor='blue',alpha=0.1) plt.fill_between(files1.dates,files1.highs,files1.lows,facecolor='blue',alpha=0.1) plt.title("Daily high and low temperatures-2014")
plt.xlabel('',fontsize=16)
fig.autofmt_xdate()
plt.ylabel("Temperature(F)")
plt.show()

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。