Python 使用matplotlib数据可视化显示CSV文件数据

(一)获取数据

1.下载sitka_weather_07-2014.csv数据:https://ehmatthes.github.io/pcc/

(二)分析CSV文件头

csv模块包含在python标准库中,不需额外要下载。调用一次next()方法读取文件头信息。如果调用n次next()方法,那么读取到n行数据。

import csv
import os
filename='sitka_weather_07-2014.csv'
with open(filename,'r')as file:
    #1.创建阅读器对象
    reader=csv.reader(file)
    #2.读取文件头信息
    header_row=next(reader)
    print(header_row)
结果演示:
['AKDT', 'Max TemperatureF', 'Mean TemperatureF', 'Min TemperatureF', 'Max Dew PointF', 'MeanDew PointF', 'Min DewpointF', 'Max Humidity', ' Mean Humidity', ' Min Humidity', ' Max Sea Level PressureIn', ' Mean Sea Level PressureIn', ' Min Sea Level PressureIn', ' Max VisibilityMiles', ' Mean VisibilityMiles', ' Min VisibilityMiles', ' Max Wind SpeedMPH', ' Mean Wind SpeedMPH', ' Max Gust SpeedMPH', 'PrecipitationIn', ' CloudCover', ' Events', ' WindDirDegrees']
(三)打印文件头及其位置(打印列表的索引和值)
import csv
import os
filename='sitka_weather_07-2014.csv'
with open(filename,'r')as file:
    #1.创建阅读器对象
    reader=csv.reader(file)
    #2.读取文件头信息
    header_row=next(reader)
    for index,column_header in enumerate(header_row):
        print(index,column_header)
结果演示:
0 AKDT
1 Max TemperatureF
2 Mean TemperatureF
snip
21  Events
22  WindDirDegrees

(四)提取并读取数据
import csv
filename='sitka_weather_07-2014.csv'
with open(filename,'r')as file:
    #1.创建阅读器对象
    reader=csv.reader(file)
    #2.读取文件头信息
    header_row=next(reader)

    #3.保存最高气温数据
    hights=[]
    for row in reader:
        #4.将字符串转换为整型数据
        hights.append(int(row[1]))
    print(hights)
结果演示:
[64, 71, 64, 59, 69, 62, 61, 55, 57, 61, 57, 59, 57, 61, 64, 61, 59, 63, 60, 57, 69, 63, 62, 59, 57, 57, 61, 59, 61, 61, 66]

(五)绘制气温图表和在图表中添加日期
import csv
from datetime import datetime
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
filename='sitka_weather_07-2014.csv'
with open(filename,'r')as file:
    #1.创建阅读器对象
    reader=csv.reader(file)
    #2.读取文件头信息
    header_row=next(reader)

    #3.保存最高气温数据
    dates,hights=[],[]
    for row in reader:
        current_date=datetime.strptime(row[0],"%Y-%m-%d")
        dates.append(current_date)
        #4.将字符串转换为整型数据
        hights.append(int(row[1]))
    #5.根据数据绘制图形
    fig=plt.figure(dpi=128,figsize=(10,6))
    #6.将列表hights传个plot()方法
    plt.plot(dates,hights,c='red')
    #7.设置图形的格式
    plt.title('2014年4月份的温度',fontsize=24)
    plt.xlabel('',fontsize=26)
    # 8.绘制斜线日期标签
    fig.autofmt_xdate()
    plt.ylabel('华摄氏度F',fontsize=16)
    plt.tick_params(axis='both',which='major',labelsize=16)
    plt.show()

结果演示:
Python 使用matplotlib数据可视化显示CSV文件数据_第1张图片

(六)绘制全年天气数据
import csv
from datetime import datetime
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
filename='sitka_weather_2014.csv'
with open(filename,'r')as file:
    #1.创建阅读器对象
    reader=csv.reader(file)
    #2.读取文件头信息
    header_row=next(reader)

    #3.保存最高气温数据
    dates,hights=[],[]
    for row in reader:
        current_date=datetime.strptime(row[0],"%Y-%m-%d")
        dates.append(current_date)
        #4.将字符串转换为整型数据
        hights.append(int(row[1]))
    #5.根据数据绘制图形
    fig=plt.figure(dpi=128,figsize=(10,6))
    #6.将列表hights传个plot()方法
    plt.plot(dates,hights,c='red')
    #7.设置图形的格式
    plt.title('2014全年的温度',fontsize=24)
    plt.xlabel('',fontsize=26)
    # 8.绘制斜线日期标签
    fig.autofmt_xdate()
    plt.ylabel('华摄氏度F',fontsize=16)
    plt.tick_params(axis='both',which='major',labelsize=16)
    plt.show()

结果演示:
Python 使用matplotlib数据可视化显示CSV文件数据_第2张图片


(七)绘制一系列数据并给图表区着色
import csv
from datetime import datetime
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
filename='sitka_weather_2014.csv'
with open(filename,'r')as file:
    #1.创建阅读器对象
    reader=csv.reader(file)
    #2.读取文件头信息
    header_row=next(reader)

    #3.保存最高气温数据
    dates,hights,lows=[],[],[]
    for row in reader:
        current_date=datetime.strptime(row[0],"%Y-%m-%d")
        dates.append(current_date)
        #4.将字符串转换为整型数据
        hights.append(int(row[1]))
        lows.append(int(row[3]))
    #5.根据数据绘制图形
    fig=plt.figure(dpi=128,figsize=(10,6))
    #给图表区绘域着色
    plt.plot(dates,hights,c='red',alpha=0.5)
    plt.plot(dates,lows, c='blue', alpha=0.5)
    plt.fill_between(dates,hights,lows,facecolor='blue',alpha=0.1)
    #6.将列表hights传个plot()方法
    plt.plot(dates,hights,c='red')
    plt.plot(dates,lows, c='blue')
    #7.设置图形的格式
    plt.title('2014全年的最高温度和最低温度',fontsize=24)
    plt.xlabel('',fontsize=26)
    # 8.绘制斜线日期标签
    fig.autofmt_xdate()
    plt.ylabel('华摄氏度F',fontsize=16)
    plt.tick_params(axis='both',which='major',labelsize=16)
    plt.show()


结果演示:
Python 使用matplotlib数据可视化显示CSV文件数据_第3张图片


(八)错误检测

气象站收集的数据偶尔出故障,未能收集全部其应该收集到的数据。缺失的数据可能引发异常,如果处理不当,可能导致程序瘫痪。因此需要异常处理。

1.数据异常处理

 import csv
from datetime import datetime
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
filename='sitka_weather_2014.csv'
with open(filename,'r')as file:
    #1.创建阅读器对象
    reader=csv.reader(file)
    #2.读取文件头信息
    header_row=next(reader)

    #3.保存最高气温数据
    dates,hights,lows=[],[],[]
    for row in reader:
        try:
          current_date=datetime.strptime(row[0],"%Y-%m-%d")
        except ValueError:
            print("数据错误!")
        else:
            dates.append(current_date)
            # 4.将字符串转换为整型数据
            hights.append(int(row[1]))
            lows.append(int(row[3]))
    #5.根据数据绘制图形
    fig=plt.figure(dpi=128,figsize=(10,6))
    #给图表区绘域着色
    plt.plot(dates,hights,c='red',alpha=0.5)
    plt.plot(dates,lows, c='blue', alpha=0.5)
    plt.fill_between(dates,hights,lows,facecolor='blue',alpha=0.1)
    #6.将列表hights传个plot()方法
    plt.plot(dates,hights,c='red')
    plt.plot(dates,lows, c='blue')
    #7.设置图形的格式
    plt.title('2014全年的最高温度和最低温度',fontsize=24)
    plt.xlabel('',fontsize=26)
    # 8.绘制斜线日期标签
    fig.autofmt_xdate()
    plt.ylabel('华摄氏度F',fontsize=16)
    plt.tick_params(axis='both',which='major',labelsize=16)
    plt.show()

你可能感兴趣的:(Python)