简单的针对CSV
和JSON
两种格式的数据利用matplotlib
和pygal
两个模块进行相关的数据可视化操作。绘制了温度变化图像和人口分布地图。
例子来自: 《Python编程从入门到实战》【美】Eric Matthes
CSV 文件
定义
逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。纯文本意味着该文件是一个字符序列,不含必须像二进制数字那样被解读的数据。
导入数据并分析
import csv
from matplotlib import pyplot as plt
filename = 'weather_test.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
# 打印数据的表头
for index,column_header in enumerate(header_row):
print(index,column_header)
# 提取最高温度
highs = []
for row in reader:
high = int (row[1]) # 转换为整形变量
highs.append(high)
# 根据数据绘制图形
fig = plt.figure(dpi=128,figsize=(10,6))
plt.plot(highs,c='blue')
# 设置图形的格式
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.savefig('highs_lows.png', bbox_inches='tight')
plt.show()
加载一组温度数据(CSV)。通过打印表头可知最高温度在第二列,提取数据,转换成整形,然后用过pyplot
绘制相应的折线图。
结果
时间信息
datetime 模块
使用
from datetime import datetime
my_date = datetime.strptime('2017-10-1', '%Y-%m-%d')
print(my_date)
输出
2017-10-01 00:00:00
美化图表
导入全年的温度信息,提取最高温和最低温,然后绘制折线图。填充其间隔
import csv
from matplotlib import pyplot as plt
from datetime import datetime
filename = 'sitka_weather_2014.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
dates,highs,lows = [],[],[]
for row in