用python绘制气温图,并着色

来源:互联网 发布:php简单计算器代码 编辑:程序博客网 时间:2024/05/17 04:06

用python绘制气温图,并着色

import csvfrom datetime import datetimefrom matplotlib import pyplot as plt# 将使用的文件的名称存储在filename中filename='sitka_weather_2014.csv'# 打开该文件,并将文件对象存储在 f 中with open(filename) as f:    # 接收文件对象,并创建一个与文件相关的 阅读器(reader)对象    reader=csv.reader(f)    #csv的函数next(),将 阅读器对象传递,并返回文件的下一行    header_row=next(reader)    #创建空列表    dates=[]    highs=[]    lows=[]    #遍历文件中剩余的各行    #每次都自动返回文件中的一行数据,以列表的形式返回,从第二行开始    for row in reader:        #提取时间        current_date=datetime.strptime(row[0],"%Y-%m-%d")        dates.append(current_date)        #转换为int类型        high=int(row[1])        #row:表示读取文件的一行数据,row[1]返回列表索引值为1的值        highs.append(high)        #获取最低温度        low=int(row[3])        lows.append(low)#根据数据绘制图形fig=plt.figure(figsize=(10,6))#将日期和最高气温值传给plot()#alpha:指定颜色的透明度,0:完全透明;1:完全不透明plt.plot(dates,highs,c='red',alpha=0.5)plt.plot(dates,lows,c='blue',alpha=0.5)#给图表区域着色,fill_between():接受一个X值系列,和两个Y值系列,并填充两个Y值系列之间的空间plt.fill_between(dates,highs,lows,facecolor='orange',alpha=0.3)#设置图形样式plt.title("Daily high and low temperatures,2014",fontsize=24)plt.xlabel('Dates',fontsize=14)#绘制倾斜的日期标签fig.autofmt_xdate()plt.ylabel('Temperature(F)',fontsize=14)#设置坐标轴参数plt.tick_params(axis='both',which='major',labelsize=10)plt.show()