【python】处理csv文件,并借助matplotlib生成可视化图形

引入csv模块

从matplotlib引入pyplot模块

从datetime引入datetime

import csv
from matplotlib import pyplot
from datetime import datetime

传入并打开下载好的天气文件

filename = 'death_valley_2014.csv'
f = open(filename)
reader = csv.reader(f)
header_row = next(reader)

创建日期、最高温、最低温三个列表

并用try...except...else将空数据错误跳过

#读取文件中最高温
dates = []
highs = []
lows = []

for row in reader:
    try:
        current_date = datetime.strptime(row[0],"%Y-%m-%d")
        high = int(row[1])
        low = int(row[3])
    except ValueError:
        print(str(current_date)+"数据丢失!")
    else:
        dates.append(current_date)
        highs.append(high)
        lows.append(low)
        
    
#根据数据绘制图形
fig = pyplot.figure(dpi=100,figsize = (13,6))
pyplot.plot(dates,highs,c='red',alpha=1)
pyplot.plot(dates,lows,c='blue',alpha=1)
pyplot.fill_between(dates,highs,lows,facecolor='yellow',alpha=1)

#设置图形格式
pyplot.title("Daily high and low Temperatures!",fontsize = 20)
pyplot.xlabel("date",fontsize = 14)
fig.autofmt_xdate()
pyplot.ylabel("Temperature",fontsize = 14)
pyplot.tick_params(axis='both',which='major',labelsize=14)

pyplot.savefig('temp.png')

plt.show()
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值