Python对CSV文件数据进行可视化

从网上下载数据,并对这些数据进行可视化。

我们将访问并可视化两种常见格式存储的数据:CSV和JSON。分别使用Python中的csv以及json模块对他们进行处理。
然后,我们再根据下载的数据,使用matplotlib创建一个图标。

1、获取CSV文件

我们将首先处理少量的锡卡尔的CSV格式的天气数据,将文件sitka_weather_07-2018_simple.csv复制到创建的程序文件夹中。

附上文件链接:
csv文件下载链接 提取码:zwfj
打开CSV文件如下图所示(如下几项数据):
在这里插入图片描述

2、分析CSV数据

直接在Python中调用csv模块,尝试着打印csv文件每行包含什么数据,是否和上方截图相同。

新建highs_lows.py文件

import csv

#将文件名存储在filename中
filename='sitka_weather_2018_simple.csv'        
with open(filename) as f:
    #创建阅读器(调用csv.reader()将前面存储的文件对象最为实参传给它)
    reader=csv.reader(f)
    #调用了next()一次,所以这边只调用了文件的第一行,并将头文件存储在header_row中
    header_row=next(reader)
    print(header_row)

测试结果如下(代码不懂的看注释):
在这里插入图片描述
和上面的csv文件第一行对比是相同的。

3、打印文件头及其位置

从csv文件中我们可以看出数据并不是很多,基本是我们要用到的,如果是数据量足够大,每行足够多,这时候我们找数据位置的话,会有些繁琐,这边我们可以对文件头进行索引。

修改highs_lows.py文件

import csv

#将文件名存储在filename中
filename='sitka_weather_2018_simple.csv'
with open(filename) as f:
    #创建阅读器(调用csv.reader()将前面存储的文件对象最为实参传给它)
    reader=csv.reader(f)
    #调用了next()一次,所以这边只调用了文件的第一行,并将头文件存储在header_row中
    header_row=next(reader)

    for index,column_header in enumerate(header_row):
        print(index,column_header)

输出结果如下,指出了每个头文件的索引:
从中我们可以得出日期和最高气温分别存储在第2列和第5列
在这里插入图片描述

4、提取并读取数据

知道数据所在的索引位置之后,首先我们先读取每天的最高气温。

修改highs_lows.py文件

import csv

#将文件名存储在filename中
filename='sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    #创建阅读器(调用csv.reader()将前面存储的文件对象最为实参传给它)
    reader=csv.reader(f)
    #调用了next()一次,所以这边只调用了文件的第一行,并将头文件存储在header_row中
    header_row=next(reader)

    highs=[]
    for row in reader:
        highs.append(row[5])
    print(highs)

创建了一个空列表highs,遍历我们需要的数据那一列,得到的数据附加到highs末尾。
效果图如下所示:
在这里插入图片描述
并将字符串转换为数字形式:
用int()来转换

highs=[]
    for row in reader:
        high=int(row[5])
        highs.append(high)
    print(highs)

效果图如下所示:
在这里插入图片描述

5、绘制气温图标

对数据进行可视化,用matplotlib创建一个简单图形

修改highs_lows.py文件

import csv
from matplotlib import pyplot as plt

#将文件名存储在filename中
filename='sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    #创建阅读器(调用csv.reader()将前面存储的文件对象最为实参传给它)
    reader=csv.reader(f)
    #调用了next()一次,所以这边只调用了文件的第一行,并将头文件存储在header_row中
    header_row=next(reader)

    highs=[]
    for row in reader:
        high=int(row[5])
        highs.append(high)
    #print(highs)
    #头文件索引
    #for index,column_header in enumerate(header_row):
        #print(index,column_header)

#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(highs,c='red')

#设置图形格式
plt.title("Daily high temperatures July 2018",fontsize=24)
plt.xlabel('',fontsize=24)
plt.ylabel('Temperature(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)

plt.show()

plt.plot(highs,c=‘red’)
将最高气温传给plot()
plt.title、plt.xlabel、plt.ylabel、plt.tick_params
设置格式
效果图如下所示:
在这里插入图片描述

6、在图表中添加对应的日期

使用datetine模块中的方法strptime()来决定如何解读日期.
(例如:%Y 表示四位数的年份、%m 表示月份、%d 表示天数)

修改highs_lows.py文件

import csv
from matplotlib import pyplot as plt
from datetime import datetime

#将文件名存储在filename中
filename='sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    #创建阅读器(调用csv.reader()将前面存储的文件对象最为实参传给它)
    reader=csv.reader(f)
    #调用了next()一次,所以这边只调用了文件的第一行,并将头文件存储在header_row中
    header_row=next(reader)

    dates,highs=[],[]
    for row in reader:
        current_date=datetime.strptime(row[2],"%Y-%m-%d")
        dates.append(current_date)
        high=int(row[5])
        highs.append(high)
    #print(highs)
    #头文件索引
    #for index,column_header in enumerate(header_row):
        #print(index,column_header)

#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red')

#设置图形格式
plt.title("Daily high temperatures July 2018",fontsize=24)
plt.xlabel('',fontsize=24)
fig.autofmt_xdate()
plt.ylabel('Temperature(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)


plt.show()

current_date=datetime.strptime(row[2],"%Y-%m-%d")
将包含date的数据row[2]转换为datetime对象
fig.autofmt_xdate()
绘制斜的日期标签

效果图如下:
在这里插入图片描述

7、涵盖更长的时间

完善图标,绘制成一幅更加复杂的锡特卡天气图,这边我们需要新的csv文件sitka_weather_2018_simple.csv涉及全年的天气数据。

附上文件链接:
文件下载链接 提取码:a7id
打开CSV文件如下图所示(如下几项数据):
从1月份至12月份的数据:
在这里插入图片描述
将highs_lows.py复制一份至新的文件highs_lows_new.py
highs_lows_new.py文件如下:

import csv
from matplotlib import pyplot as plt
from datetime import datetime

#将文件名存储在filename中
filename='sitka_weather_2018_simple.csv'
with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)

    dates,highs=[],[]
    for row in reader:
        current_date=datetime.strptime(row[2],"%Y-%m-%d")
        dates.append(current_date)
        high=int(row[5])
        highs.append(high)

#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red')

#设置图形格式
plt.title("Daily high temperatures - 2018",fontsize=24)
plt.xlabel('',fontsize=24)
fig.autofmt_xdate()
plt.ylabel('Temperature(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)


plt.show()

效果图如下:
在这里插入图片描述

8、在绘制一个数据系列

上述我们多的都是对最高气温进行数据处理,现在我们从数据中提取最低气温数据

import csv
from matplotlib import pyplot as plt
from datetime import datetime

#将文件名存储在filename中
filename='sitka_weather_2018_simple.csv'
with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)

    dates,highs,lows=[],[],[]
    for row in reader:
        current_date=datetime.strptime(row[2],"%Y-%m-%d")
        dates.append(current_date)

        high=int(row[5])
        highs.append(high)

        low=int(row[6])
        lows.append(low)
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red')
plt.plot(dates,lows,c='blue')

#设置图形格式
plt.title("Daily high and low temperatures - 2018",fontsize=24)
plt.xlabel('',fontsize=24)
fig.autofmt_xdate()
plt.ylabel('Temperature(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)


plt.show()

新建lows列表,row[6]读取第6列中的最低气温数据,添加到lows末尾,用蓝色线在图表中显示。
效果图如下:
在这里插入图片描述

9、图标区域着色

高气温、低气温显示后,我们可以了解每天的气温范围,可以给范围着色,更明显的呈现气温范围。这边我们用到了fill_between()来填充范围。

修改highs_lows_new.py文件中的绘制图形部分:

#根据数据绘制图形
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='blue',alpha=0.1)

alpha
alpha值在0~1范围内(0表示完全透明,1表示完全不透明)、
plt.fill_between(dates,highs,lows,facecolor=‘blue’,alpha=0.1)
facecolor指定了填充区颜色
效果图如下:
在这里插入图片描述

9、错误检查

有些气象站会偶尔出现故障,未能收集全部数据,缺失数据可能会引发异常,导入death_valley_2018_simple.csv

附上文件链接:
文件下载链接 提取码:iou6
打开CSV文件如下图所示(如下几项数据):
发现2月18日这一天数据遗漏!!!
在这里插入图片描述
将highs_lows.py复制一份至新的文件highs_lows_death.py
只需修改highs_lows_death.py文件如下:

#将文件名存储在filename中
filename='death_valley_2018_simple.csv'

运行效果如下:
在这里插入图片描述
这边显示有错误,无法将(’ ')空字符转换为整数,存在有数据为空。

解决问题,对异常进行处理

修改highs_lows_death.py文件

dates,highs,lows=[],[],[]
    for row in reader:
        try:
            current_date=datetime.strptime(row[2],"%Y-%m-%d")
            high=int(row[4])
            low = int(row[5])
        except ValueError:
            print(current_date,'missing data')
        else:
            dates.append(current_date)
            highs.append(high)
            lows.append(low)

except ValueError:
print(current_date,‘missing data’)

只要数据中缺其中一项,就会引发异常,打印错误消息,指出缺失数据的日期
运行效果如下:
在这里插入图片描述
控制台显示如下:
在这里插入图片描述

综上对CSV文件数据可视化完毕!!!

附上完整的highs_lows.py和highs_lows_new.py和dice_visual.py和highs_lows_death.py文件

highs_lows.py

import csv
from matplotlib import pyplot as plt
from datetime import datetime

#将文件名存储在filename中
filename='sitka_weather_07-2018_simple.csv'
with open(filename) as f:
    #创建阅读器(调用csv.reader()将前面存储的文件对象最为实参传给它)
    reader=csv.reader(f)
    #调用了next()一次,所以这边只调用了文件的第一行,并将头文件存储在header_row中
    header_row=next(reader)

    dates,highs=[],[]
    for row in reader:
        current_date=datetime.strptime(row[2],"%Y-%m-%d")
        dates.append(current_date)
        high=int(row[5])
        highs.append(high)
    #print(highs)
    #头文件索引
    #for index,column_header in enumerate(header_row):
        #print(index,column_header)

#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red')

#设置图形格式
plt.title("Daily high temperatures July 2018",fontsize=24)
plt.xlabel('',fontsize=24)
fig.autofmt_xdate()
plt.ylabel('Temperature(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)


plt.show()

highs_lows_new.py

import csv
from matplotlib import pyplot as plt
from datetime import datetime

#将文件名存储在filename中
filename='sitka_weather_2018_simple.csv'
with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)

    dates,highs,lows=[],[],[]
    for row in reader:
        current_date=datetime.strptime(row[2],"%Y-%m-%d")
        dates.append(current_date)

        high=int(row[5])
        highs.append(high)

        low=int(row[6])
        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='blue',alpha=0.1)

#设置图形格式
plt.title("Daily high and low temperatures - 2018",fontsize=24)
plt.xlabel('',fontsize=24)
fig.autofmt_xdate()
plt.ylabel('Temperature(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)


plt.show()

highs_lows_death.py

import csv
from matplotlib import pyplot as plt
from datetime import datetime

#将文件名存储在filename中
filename='death_valley_2018_simple.csv'
with open(filename) as f:
    reader=csv.reader(f)
    header_row=next(reader)

    dates,highs,lows=[],[],[]
    for row in reader:
        try:
            current_date=datetime.strptime(row[2],"%Y-%m-%d")
            high=int(row[4])
            low = int(row[5])
        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='blue',alpha=0.1)

#设置图形格式
plt.title("Daily high and low temperatures - 2018",fontsize=24)
plt.xlabel('',fontsize=24)
fig.autofmt_xdate()
plt.ylabel('Temperature(F)',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)


plt.show()

不足之处,请指出,蟹蟹!!!

  • 50
    点赞
  • 277
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值