下载数据
如今的社会的信息已经不能用氢弹大爆炸来形容了,信息的海量,多的难以置信,且大多未经过仔细检查,所以就需要对信息进行分析。
接下来我们将可视化两种常见格式存储的数据:CSV和JSON。
将使用Python模块csv来处理以CSV格式存储的天气数据,找出两个不同地区在一段时间内的最高温度和最低温度,然后生成一张图表。
还会使用json来访问以JSON格式存储的交易收盘价数据,并使用Pygal绘制图形以探索价格变化的周期性。
CSV文件格式
要在文本文件中存储数据,最简单的方式是将数据作为一系列以逗号分隔的值(CSV)写入文件。这样的文件称为CSV文件。例如,下面是一行CSV格式的天气数据。
2014-1-5,61,44,26,187,-1,56,30.34,30.15,,,,10,4,,0.00,0,,195
其中包含当天的最高气温和最低气温,还有众多其他数据。该类型的文件阅读起来比较麻烦,但是可以使用程序读取和分析出来,方便人们阅读。
分析CSV文件头
csv模块包含在python标准库中,可用于分析CSV文件中的数据行。
#highs_lows.py
import csv
filename='sitka_weather_07-2014.csv'
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
print(header_row)
打印文件头及其位置
#highs_lows.py
import csv
filename='sitka_weather_07-2014.csv'
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
for index, column_header in enumerate(header_row):
print(header_row)
提取并读取数据
#highs_lows.py
import csv
#从文件中获取最高温度
filename='sitka_weather_07-2014.csv'
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
highs=[]
for row in reader:
highs.append(row[1])
print(highs)
#for index, column_header in enumerate(header_row):
# print(header_row)
import csv
#从文件中获取最高温度
filename='sitka_weather_07-2014.csv'
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
highs=[]
for row in reader:
high=int(row[1]) #将这些字符串转换为数字,然后方便,atplotlib读取它们
highs.append(high)
print(highs)
#for index, column_header in enumerate(header_row):
# print(header_row)
绘制气温图表
#highs_lows.py
import csv
from matplotlib import pyplot as plt
#从文件中获取最高温度
filename='sitka_weather_07-2014.csv'
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)
highs=[]
for row in reader:
high=int(row[1]) #将这些字符串转换为数字,然后方便,atplotlib读取它们
highs.append(high)
print(highs)
#for index, column_header in enumerate(header_row):
# print(header_row)
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(highs,c='red')
#设置图形的格式
plt.title("Daily high temperatures,July 2014",fontsize=24)
plt.xlabel('',fontsize=16)
plt.ylabel("Temperature (F)",fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
模块datetime
在读取上面数据时,获得的是一个字符串,为了把字符串中的日期转换为相应日期的对象,可使用模块datetime中的方法strptime().下面看怎么用的
实参 | 含义 |
---|---|
%A | 星期的名称,如Monday |
%B | 月份名,如January |
%m | 用数字表示的月份(01~12) |
%d | 用数字表示月份中的一天(01~31) |
%Y | 四位的年份,如2015 |
%y | 两位的年份,如15 |
%H | 24小时制的小时数(00~23) |
%I | 12小时制的小时数(01~12) |
%p | am或pm |
%M | 分钟数(00~59) |
%S | 秒数(00~61) |
在图表中添加日期
知道如何处理CSV文件中的日期后,就可对气温图形进行改进了,即提取日期和最高气温,并将它们传递给plot(),如下表示
import csv
from datetime import datetime
from matplotlib import pyplot as plt
#从文件中获取最高温度
#从文件中获取日期和最高温度
filename='sitka_weather_07-2014.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[0],"%Y-%m-%d") #row[0]包含日期信息的数据转换为datetime对象
dates.append(current_date)#并将其附加到列表dates的末尾
high=int(row[1]) #将这些字符串转换为数字,然后方便,atplotlib读取它们
highs.append(high)
print(highs)
#for index, column_header in enumerate(header_row):
# print(header_row)
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red')
#设置图形的格式
plt.title("Daily high temperatures,July 2014",fontsize=24)
plt.xlabel('',fontsize=16)
fig.autofmt_xdate()#绘制斜的日期标签,以免它们批次重叠
plt.ylabel("Temperature (F)",fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
涵盖更长的时间
import csv
from datetime import datetime
from matplotlib import pyplot as plt
#从文件中获取最高温度
#从文件中获取日期和最高温度
filename='sitka_weather_2014.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[0],"%Y-%m-%d") #row[0]包含日期信息的数据转换为datetime对象
dates.append(current_date)#并将其附加到列表dates的末尾
high=int(row[1]) #将这些字符串转换为数字,然后方便,atplotlib读取它们
highs.append(high)
print(highs)
#for index, column_header in enumerate(header_row):
# print(header_row)
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red')
#设置图形的格式
plt.title("Daily high temperatures-2014",fontsize=24)
plt.xlabel('',fontsize=16)
fig.autofmt_xdate()#绘制斜的日期标签,以免它们批次重叠
plt.ylabel("Temperature (F)",fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
在绘制一个数据系列
import csv
from datetime import datetime
from matplotlib import pyplot as plt
#从文件中获取最高温度
#从文件中获取日期和最高温度和最低气温
filename='sitka_weather_2014.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[0],"%Y-%m-%d") #row[0]包含日期信息的数据转换为datetime对象
dates.append(current_date)#并将其附加到列表dates的末尾
high=int(row[1]) #将这些字符串转换为数字,然后方便,atplotlib读取它们
highs.append(high)
low=int(row[3])
lows.append(low)
print(highs)
#for index, column_header in enumerate(header_row):
# print(header_row)
#根据数据绘制图形
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-2014",fontsize=24)
plt.xlabel('',fontsize=16)
fig.autofmt_xdate()#绘制斜的日期标签,以免它们批次重叠
plt.ylabel("Temperature (F)",fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
给图表区域着色
使用方法fill_between(),它接受一个x值系列和两个y值系列,并填充两个y值系列之间的空间
import csv
from datetime import datetime
from matplotlib import pyplot as plt
#从文件中获取最高温度
#从文件中获取日期和最高温度和最低气温
filename='sitka_weather_2014.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[0],"%Y-%m-%d") #row[0]包含日期信息的数据转换为datetime对象
dates.append(current_date)#并将其附加到列表dates的末尾
high=int(row[1]) #将这些字符串转换为数字,然后方便,atplotlib读取它们
highs.append(high)
low=int(row[3])
lows.append(low)
print(highs)
#for index, column_header in enumerate(header_row):
# print(header_row)
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red',alpha=0.5) #alpha指定颜色的透明度,为0表示完全透明,1表示完全不透明
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-2014",fontsize=24)
plt.xlabel('',fontsize=16)
fig.autofmt_xdate()#绘制斜的日期标签,以免它们批次重叠
plt.ylabel("Temperature (F)",fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
错误检查
任何时候在编写代码和处理数据时,有可能不会达到非常完美的状态,有可能发生在读取数据时,读取不到数据,这样的话就需要,对代码进行异常处理
比如在读取文件death_valley_2014.csv文件时,找不到最高气温,就会产生traceback。
import csv
from datetime import datetime
from matplotlib import pyplot as plt
#从文件中获取最高温度
#从文件中获取日期和最高温度和最低气温
filename='death_valley_2014.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[0],"%Y-%m-%d") #row[0]包含日期信息的数据转换为datetime对象
dates.append(current_date)#并将其附加到列表dates的末尾
high=int(row[1]) #将这些字符串转换为数字,然后方便,atplotlib读取它们
highs.append(high)
low=int(row[3])
lows.append(low)
print(highs)
#for index, column_header in enumerate(header_row):
# print(header_row)
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red',alpha=0.5) #alpha指定颜色的透明度,为0表示完全透明,1表示完全不透明
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-2014",fontsize=24)
plt.xlabel('',fontsize=16)
fig.autofmt_xdate()#绘制斜的日期标签,以免它们批次重叠
plt.ylabel("Temperature (F)",fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
那接下来我们就对异常进行处理
import csv
from datetime import datetime
from matplotlib import pyplot as plt
#从文件中获取最高温度
#从文件中获取日期和最高温度和最低气温
filename='death_valley_2014.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[0],"%Y-%m-%d") #row[0]包含日期信息的数据转换为datetime对象
high = int(row[1]) #将这些字符串转换为数字,然后方便,atplotlib读取它们
low = int(row[3])
except ValueError:
print(current_date,'missing data')
else:
dates.append(current_date)#并将其附加到列表dates的末尾
highs.append(high)
lows.append(low)
print(highs)
#for index, column_header in enumerate(header_row):
# print(header_row)
#根据数据绘制图形
fig=plt.figure(dpi=128,figsize=(10,6))
plt.plot(dates,highs,c='red',alpha=0.5) #alpha指定颜色的透明度,为0表示完全透明,1表示完全不透明
plt.plot(dates,lows,c='blue',alpha=0.5)
plt.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1)
#设置图形的格式
title="Daily high and low temperatures-2014\nDeath Valley,CA"
plt.title(title,fontsize=24)
plt.xlabel('',fontsize=16)
fig.autofmt_xdate()#绘制斜的日期标签,以免它们批次重叠
plt.ylabel("Temperature (F)",fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
注:在编写异常处理的代码时,出现了一个小插曲,因为提供的原始excel表格数据,里面有部分的日期是XXXX表示的,我就把这些XXXX的日期改为了具体的日期,然后就不得了了,在编译运行的时候,总是报错,说current_date没有定义,就在网上搜啊,说很多方法都不相符,然后呢,就想到了自己动手改过数据文件的格式然后呢,就把excel数据文件的格式恢复成原始状态后,就好了!
原始的数据文件:
修改后的数据文件:
然后编译运行出现的错误:
前面已经定义了,然后呢,在后面就出错了。
可能是修改数据文件的软件和数据文件原始使用的软件不相符和导致的。