您的位置:首页 > 编程语言 > Python开发

python.matplotlib/datatime/CSV学习范例-读取CSV格式文件生成折线图

2017-10-01 16:01 1451 查看
import csv

from datetime import datetime

from matplotlib import pyplot as plt

filename='D:\python program\weather.csv'

#分析csv头文件

with open(filename) as f:

reader=csv.reader(f)  #生成阅读器

header_row=next(reader) #将阅读器对象传给next返回下一行,本部读取头行

#下一行

#读取数据,获取日期(row[0])、最高气温row[1]、最低气温row[3]

dates,highs,lows=[],[],[]

for row in reader:

#对某个日期没有温度的异常处理

try:

#将日期字符串转换为表示日期的对象

current_date=datetime.strptime(row[0],"%Y-%m-%d")

high=int(row[1])   #字符串转换成数字让matplotlib读取

low=int(row[3])

except ValueError:

print(current_date,'missing data')

else:

dates.append(current_date)

highs.append(high)

lows.append(low)

 #绘制图形

fig=plt.figure(dpi=128,figsize=(10,6))

plt.plot(dates,highs,c='red',alpha=0.5)

plt.plot(dates,lows,c='blue',alpha=0.5)

#给图标区域填充颜色

plt.fill_between(dates,highs,lows,facecolor='yellow',alpha=0.1)

#设置图形格式 

plt.title('daily high and low temperatures, july 2014',fontsize=24)

plt.xlabel('',fontsize=16)

#绘制倾斜的日期标签

fig.autofmt_xdate()

plt.ylabel('temperature ',fontsize=16)

plt.tick_params(axis='both',which='major',labelsize=16)

plt.show()

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: