参考教材
chapter16 数据可视化
引言
经过世界地图的练习,我们现在来进行自己的数据可视化小项目。Open Konwledge Foundation 提供了一个数据集,其中包含各国的国内生产总值(GDP),我们可以在
section 1:中国GDP的数据可视化练习
下载完成这个 json 文件之后,用记事本打开,搜索一下 'China' , 观察一下数据格式
{"Country Name":"China","Country Code":"CHN","Year":"1960","Value":"59184116448.734"}
后面的事情就很简单了
step 1: 绘制中国历年 GDP 情况直方图
直接贴代码
#! /usr/bin/python
# -*- coding: utf8 -*-
import json
import pygal
filename = 'gdp.json'
with open(filename) as f:
gdp = json.load(f)
china_gdp = []
year_list = []
for gdp_dict in gdp:
if gdp_dict['Country Name'] == 'China':
year = gdp_dict['Year']
value = gdp_dict['Value']
year_list.append(int(year))
china_gdp.append(int(float(value)))
hist = pygal.Bar()
hist.title = 'Chinese GDP from '+str(year_list[0])+' to '+str(year_list[-1])+''
hist.x_labels = year_list
hist.x_title = 'Year'
hist.y_title = 'GDP (dollars)'
hist.add('Chinese GDP',china_gdp)
hist.render_to_file(hist.title+'.svg')
step 2: 进阶一点,GDP年增长率
数据都分类好了,直接玩数学游戏就行了
代码
#GDP增长率
num = len(china_gdp)
zero = [0 for count in range(0,num-1)]
growth_rate = [int(10000*(china_gdp[count+1] - china_gdp[count])/china_gdp[count])/100
for coun