温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python如何读取CSV文件并进行数据可视化绘图

发布时间:2022-06-17 09:14:34 来源:亿速云 阅读:1237 作者: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()

运行结果如下:

Python如何读取CSV文件并进行数据可视化绘图

 设置以上图标后,我们来添加更多的数据,生成一副更复杂的锡特卡天气图。将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()

运行结果如下:

Python如何读取CSV文件并进行数据可视化绘图

代码再改进:虽然上图已经显示了丰富的数据,但是还能再添加最低温度数据,使其更有用

对代码进行修改:

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()

运行结果如下:

Python如何读取CSV文件并进行数据可视化绘图

此外,读取CSV文件过程中,数据可能缺失,程序运行时就会报错甚至崩溃。所有需要在从CSV文件中读取值时执行错误检查代码,对可能的异常进行处理,更换数据文件为:death_valley_2018_simple.csv  ,该文件有缺失值。

Python如何读取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文件并进行数据可视化绘图这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI