python 数据可视化练习(2)

简单的针对CSVJSON两种格式的数据利用matplotlibpygal两个模块进行相关的数据可视化操作。绘制了温度变化图像和人口分布地图。


例子来自: 《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 reader:
        current_date = datetime.strptime(row[0],"%Y-%m-%d")
        dates.append(current_date)
        high = int (row[1])  # 转换为整形变量
        highs.append(high)      
        low = int(row[3])
        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 - 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.savefig('highs_lowswithdate.png', bbox_inches='tight')
plt.show()

结果

错误检测

如果导入的CSV文件中有错误,那么也许会导致程序崩溃,所以需要引入错误检测的相应功能。比如某一天的某些数据为空。

2014-2-15,82,60,37,20,17,14,39,21,9,30.05,29.97,29.91,10,10,10,23,7,28,0.00,0,,247
2014-2-16,,,,,,,,,,,,,,,,,,,0.00,,,-1
2014-2-18,75,56,37,25,21,16,51,25,13,30.08,30.01,29.93,10,10,10,9,3,,0.00,6,,157

在读取信息的过程中加入如下的代码:

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

程序不会因为数据的缺失而卡死,可以继续往下执行。并且打印数据丢失的信息

2014-02-16 00:00:00 missing data

JSON 文件

JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。它基于 ECMAScript (w3c制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

JSON文件内容

[
  {
    "Country Name": "Arab World",
    "Country Code": "ARB",
    "Year": "1960",
    "Value": "96388069"
  },
  ......

  {
    "Country Name": "Arab World",
    "Country Code": "ARB",
    "Year": "1961",
    "Value": "98882541.4"
  },
]

这个文件实际上就是一个很长的Python列表,其中每个元素都是一个包含四个键的字典:国家名、国别码、年份以及表示人口数量的值。
为了提取2010年各国的人口数。编写如下代码

import json

# 将数据加载到一个列表中
filename = 'population_data.json'
with open(filename) as f:
    pop_data = json.load(f)

# 打印每个国家2010年的人口数量
for pop_dict in pop_data:
    if pop_dict['Year'] == '2010':
        country_name = pop_dict['Country Name']
        population = int(float(pop_dict['Value']))
        print(country_name + ": " + str(population))

应为每个国家的人数含有小数,直接有str转成int会报错,所以先转换成float,然后在转换成int型的变量。

输出结果

Chad: 11227000
Channel Islands: 153352
Chile: 17113688
China: 1338300000
Colombia: 46295000
Comoros: 735000

国别码

Pygal中的地图制作工具要求数据为特定的格式:用国别码表示国家,以及用数字表示人口数量。Pygal要求的是两位的国别码,但是原始数据包含的是三位。

Pygal使用的国别码存储在模块pygal_maps_world。字典COUNTRIES包含的键和值分别为两个字母的国别码和国家名。先通过命令pip install pygal_maps_world安装模块。

from pygal_maps_world.i18n import COUNTRIES

for country_code in sorted(COUNTRIES.keys()):
    print(country_code, COUNTRIES[country_code])

输出结果

ad Andorra
ae United Arab Emirates
af Afghanistan
al Albania
······

国别码转换

from pygal_maps_world.i18n import COUNTRIES

def get_country_code(country_name):
    """根据指定的国家,返回Pygal使用的两个字母的国别码"""
    for code,name in COUNTRIES.items():
        if name == country_name:
            return code
    # 如果没有找指定的国家,就返回None
    return None

准备数据

# 打印每个国家2010年的人口数量
for pop_dict in pop_data:
    if pop_dict['Year'] == '2010':
        country_name = pop_dict['Country Name']
        population = int(float(pop_dict['Value']))
        code = get_country_code(country_name)
        if code:
            print(code + ":" + str(population))
        else:
            print('ERROR - ' + country_name)

输出结果

af:34385000
al:3205000
dz:35468000
ERROR - American Samoa
ad:84864
ao:19082000

制作世界地图

使用Pygal-Worldmap

通过一个简单的例子了解模块的使用

from pygal_maps_world.maps import World
wm = World()
wm.title = 'North, Central, and South America'
wm.add('North America', ['ca', 'mx', 'us'])
wm.add('Central America', ['bz', 'cr', 'gt', 'hn', 'ni', 'pa', 'sv'])
wm.add('South America', ['ar', 'bo', 'br', 'cl', 'co', 'ec', 'gf','gy', 'pe', 'py', 'sr', 'uy', 've'])

wm.render_to_file('americas.svg')

输出

绘制

import json
import pygal

from pygal.style import LightColorizedStyle, RotateStyle  #修改整个图表的主题
from pygal_maps_world.maps import World

from country_codes import get_country_code

# 将数据加载到一个列表中
filename = 'population_data.json'
with open(filename) as f:
    pop_data = json.load(f)


# 创建一个包含人口数量的字典
cc_populations = {}    
for pop_dict in pop_data:
    if pop_dict['Year'] == '2010':
        country = pop_dict['Country Name']
        population = int(float(pop_dict['Value']))
        code = get_country_code(country)   
        if code:
            cc_populations[code] = population


# 根据人口数量将所有国家分成三组
cc_pops_1,cc_pops_2,cc_pops_3 = {},{},{}
for cc,pop in cc_populations.items():
    if pop < 10000000:
        cc_pops_1[cc] = pop
    elif pop < 1000000000:
        cc_pops_2[cc] = pop
    else:
        cc_pops_3[cc] = pop

# 看看每组分别包含多少个国家
print(len(cc_pops_1), len(cc_pops_2), len(cc_pops_3))

wm_style = RotateStyle('#336699', base_style=LightColorizedStyle)    
wm = World(style=wm_style)
wm.title = 'World Population in 2010'
wm.add('0-10m', cc_pops_1)
wm.add('10m-1bn', cc_pops_2)
wm.add('>1bn', cc_pops_3)  

wm.render_to_file('world_population.svg')
  • cc_populations是一个dict,里面存放了两位国别码与人口的键值对。
  • world = World(style=wm_style)这是一个地图类。
  • wm_style = RotateStyle(‘#336699’,base_style=LightColorizedStyle)这里修改了pygal默认的主题颜色。

输出

你可能感兴趣的:(python)