Python如何读取CSV文件并进行数据可视化绘图 |
您所在的位置:网站首页 › python读取不到csv文件 › Python如何读取CSV文件并进行数据可视化绘图 |
Python如何读取CSV文件并进行数据可视化绘图
发布时间:2022-06-17 09:14:34
来源:亿速云
阅读:1034
作者:iii
栏目:开发技术
这篇文章主要讲解了“Python如何读取CSV文件并进行数据可视化绘图”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python如何读取CSV文件并进行数据可视化绘图”吧! 介绍:文件 sitka_weather_07-2018_simple.csv是阿拉斯加州锡特卡2018年1月1日的天气数据,其中包含当天的最高温度和最低温度。数据文件存储与data文件夹下,接下来用Python读取该文件数据,再基于数据进行可视化绘图。 sitka_highs.py import csv # 导入csv模块 from datetime import datetime import matplotlib.pyplot as plt filename = 'data/sitka_weather_07-2018_simple.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) # 返回文件的下一行,在这便是首行,即文件头 # for index, column_header in enumerate(header_row): # 对列表调用了 enumerate()来获取每个元素的索引及其值,方便我们提取需要的数据列 # print(index, column_header) # 从文件中获取最高温度 dates, highs = [], [] for row in reader: current_date = datetime.strptime(row[2], '%Y-%m-%d') high = int(row[5]) dates.append(current_date) highs.append(high) # 根据最高温度绘制图形 plt.style.use('seaborn') fig, ax = plt.subplots() ax.plot(dates, highs, c='red') # 设置图形的格式 ax.set_title("2018年7月每日最高温度", fontproperties="SimHei", fontsize=24) ax.set_xlabel('', fontproperties="SimHei", fontsize=16) fig.autofmt_xdate() ax.set_ylabel("温度(F)", fontproperties="SimHei", fontsize=16) ax.tick_params(axis='both', which='major', labelsize=16) plt.show()运行结果如下: 设置以上图标后,我们来添加更多的数据,生成一副更复杂的锡特卡天气图。将sitka_weather_2018_simple.csv数据文件置于data文件夹下,该文件包含整年的锡特卡天气数据。 对代码进行修改: sitka_highs.py import csv # 导入csv模块 from datetime import datetime import matplotlib.pyplot as plt filename = 'data/sitka_weather_2018_simple.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) # 返回文件的下一行,在这便是首行,即文件头 # for index, column_header in enumerate(header_row): # 对列表调用了 enumerate()来获取每个元素的索引及其值,方便我们提取需要的数据列 # print(index, column_header) # 从文件中获取最高温度 dates, highs = [], [] for row in reader: current_date = datetime.strptime(row[2], '%Y-%m-%d') high = int(row[5]) dates.append(current_date) highs.append(high) # 根据最高温度绘制图形 plt.style.use('seaborn') fig, ax = plt.subplots() ax.plot(dates, highs, c='red') # 设置图形的格式 ax.set_title("2018年每日最高温度", fontproperties="SimHei", fontsize=24) ax.set_xlabel('', fontproperties="SimHei", fontsize=16) fig.autofmt_xdate() ax.set_ylabel("温度(F)", fontproperties="SimHei", fontsize=16) ax.tick_params(axis='both', which='major', labelsize=16) plt.show()运行结果如下: 代码再改进:虽然上图已经显示了丰富的数据,但是还能再添加最低温度数据,使其更有用 对代码进行修改: sitka_highs_lows.py import csv # 导入csv模块 from datetime import datetime import matplotlib.pyplot as plt filename = 'data/sitka_weather_2018_simple.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) # 返回文件的下一行,在这便是首行,即文件头 # for index, column_header in enumerate(header_row): # 对列表调用了 enumerate()来获取每个元素的索引及其值,方便我们提取需要的数据列 # print(index, column_header) # 从文件中获取日期、最高温度和最低温度 dates, highs, lows = [], [], [] for row in reader: current_date = datetime.strptime(row[2], '%Y-%m-%d') high = int(row[5]) low = int(row[6]) dates.append(current_date) highs.append(high) lows.append(low) # 根据最高温度和最低温度绘制图形 plt.style.use('seaborn') fig, ax = plt.subplots() ax.plot(dates, highs, c='red', alpha=0.5) # alpha指定颜色的透明度,0为完全透明 ax.plot(dates, lows, c='blue', alpha=0.5) ax.fill_between(dates, highs, lows, facecolor='blue',alpha=0.1) # 设置图形的格式 ax.set_title("2018年每日最高温度", fontproperties="SimHei", fontsize=24) ax.set_xlabel('', fontproperties="SimHei", fontsize=16) fig.autofmt_xdate() ax.set_ylabel("温度(F)", fontproperties="SimHei", fontsize=16) ax.tick_params(axis='both', which='major', labelsize=16) plt.show()运行结果如下: 此外,读取CSV文件过程中,数据可能缺失,程序运行时就会报错甚至崩溃。所有需要在从CSV文件中读取值时执行错误检查代码,对可能的异常进行处理,更换数据文件为:death_valley_2018_simple.csv ,该文件有缺失值。 对代码进行修改: death_valley_highs_lows.py import csv # 导入csv模块 from datetime import datetime import matplotlib.pyplot as plt filename = 'data/death_valley_2018_simple.csv' with open(filename) as f: reader = csv.reader(f) header_row = next(reader) # 返回文件的下一行,在这便是首行,即文件头 # for index, column_header in enumerate(header_row): # 对列表调用了 enumerate()来获取每个元素的索引及其值,方便我们提取需要的数据列 # print(index, column_header) # 从文件中获取日期、最高温度和最低温度 dates, highs, lows = [], [], [] for row in reader: current_date = datetime.strptime(row[2], '%Y-%m-%d') try: high = int(row[5]) low = int(row[6]) except ValueError: print(f"Missing data for {current_date}") else: dates.append(current_date) highs.append(high) lows.append(low) # 根据最高温度和最低温度绘制图形 plt.style.use('seaborn') fig, ax = plt.subplots() ax.plot(dates, highs, c='red', alpha=0.5) # alpha指定颜色的透明度,0为完全透明 ax.plot(dates, lows, c='blue', alpha=0.5) ax.fill_between(dates, highs, lows, facecolor='blue',alpha=0.1) # 设置图形的格式 ax.set_title("2018年每日最高温度和最低气温\n美国加利福利亚死亡谷", fontproperties="SimHei", fontsize=24) ax.set_xlabel('', fontproperties="SimHei", fontsize=16) fig.autofmt_xdate() ax.set_ylabel("温度(F)", fontproperties="SimHei", fontsize=16) ax.tick_params(axis='both', which='major', labelsize=16) plt.show()如果现在运行 death_valley_highs_lows.py,将会发现缺失数据的日期只有一个: Missing data for 2018-02-18 00:00:00妥善地处理错误后,代码能够生成图形并忽略缺失数据的那天。运行结果如下: 感谢各位的阅读,以上就是“Python如何读取CSV文件并进行数据可视化绘图”的内容了,经过本文的学习后,相信大家对Python如何读取CSV文件并进行数据可视化绘图这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注! 推荐阅读: python中读取csv文件的方法 python如何读取csv文件免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:[email protected]进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。 python csv 上一篇新闻:C#怎么对WPF数据绑定的菜单插入分隔 下一篇新闻:Android开发组件化架构设计原理实例分析 猜你喜欢 php中setcookie参数有什么用 如何解决url地址传参数时字符串有回车造成页面脚本赋值失败的问题 利用PHP怎么对Mysql数据库进行读写分离 如何在win7环境中安装memCache 启动Memcache的常用参数以及telnet命令详解 HTTP消息头网页缓存控制以及header常用指令的示例分析 apache配置文件httpd.conf的参数有什么用 static变量修饰符怎么在php中使用 使用php怎么将日志写进syslog PHP中VC6 X86和VC9 X86的区别有哪些 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |