菜鸟笔记Python3——数据可视化(三)世界GDP分析

参考教材

<Python编程——从入门到实践> chapter16 数据可视化

引言

经过世界地图的练习,我们现在来进行自己的数据可视化小项目。Open Konwledge Foundation 提供了一个数据集,其中包含各国的国内生产总值(GDP),我们可以在 http://data.okfn.org/data/core/gdp 中找到这个数据集。接下来,让我们做一些有趣的小练习吧......

section 1:中国GDP的数据可视化练习

下载完成这个 json 文件之后,用记事本打开,搜索一下 'China' , 观察一下数据格式
{"Country Name":"China","Country Code":"CHN","Year":"1960","Value":"59184116448.734"}
后面的事情就很简单了

step 1: 绘制中国历年 GDP 情况直方图

直接贴代码

#! /usr/bin/python <br> # -*- 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 count in range(0,num-1)]
plt.figure(figsize=(10,6))
plt.title('Chinese GDP \'s growth rate from '+str(year_list[0])+' to '+str(year_list[-2])+'')
plt.plot(year_list[:-1],growth_rate,'r--')
plt.plot(year_list[:-1],zero,'b--')
plt.scatter(year_list[:-1],growth_rate,c='r')
plt.xlim([year_list[0], year_list[-2]])
plt.ylim([growth_rate[0]-2, max(growth_rate)+2])
plt.xlabel('Year From 1960 to 2013',fontsize = 14)
plt.ylabel('GDP growth rate ( % )',fontsize = 14)
plt.tick_params(axis='both', labelsize=14)
plt.savefig('Chinese GDP \'s growth rate from '+str(year_list[0])+' to '+str(year_list[-2])+'.png',
            bbox_inches='tight')
plt.show()

结果图

Chinese GDP 's growth rate from 1960 to 2013.png

其实还可以画折点图

line_chart = pygal.Line()
line_chart.title = 'Chinese GDP \'s growth rate from ' \
                   ''+str(year_list[0])+' to '+str(year_list[-2])+' ( % )'
line_chart.x_labels = map(str,year_list[:-1])
line_chart.add('GDP growth rate',growth_rate)
line_chart.render_to_file(''+line_chart.title+'v2.svg')

效果图


额。。。。 ( ̄▽ ̄") 数据太多横坐标显示不过来了
不过可以发现,在数据比较少的时候这样的图还是很不错的 o(*≧▽≦)ツ

section 2: 世界 GDP 数据统计

step 1 : 世界地图

原理跟之前统计世界人口一模一样,改一下代码中的关键字

import pygal
import json
from country_codes import get_country_code
from pygal.style import RotateStyle
from pygal.style import LightColorizedStyle
from countries import get_countries
#将数据加载到一个列表中
filename = 'gdp.json'


#创建一个字典
cc_GDP = {}
cc_GDP1,cc_GDP2,cc_GDP3 = {},{},{}

cc_GDP = get_countries(filename)

for cc,GDP in cc_GDP.items():
    if   GDP < 1E9:
        cc_GDP1[cc] = GDP
    elif GDP < 1E12:
        cc_GDP2[cc] = GDP
    else:
        cc_GDP3[cc] = GDP
wm_style = RotateStyle('#EE2C2C',base_style=LightColorizedStyle)
wm = pygal.maps.world.World(style=wm_style)
wm.title = 'World GDP in 2014, by Country'
wm.add('0-billion',cc_GDP1)
wm.add('1billion-1trillion',cc_GDP2)
wm.add('>1trillion',cc_GDP3)

wm.render_to_file('world_GDP_v8.svg')

成果图

step 2: GDP 前10 排行

存储数据的字典完成之后,如果我们想根据 GDP 排序, 那么需要考虑 对字典中的键值对排序
经过网络,我们发现了这样一种办法 :

dic = sorted(cc_GDP1.items(), key=lambda d:d[1], reverse = True)

分析一下:

第一个参数 cc_GDP.items()sorted 传递了字典中的键值对信息
第二个参数 key=lambda d:d[1] 告诉 sorted 要按照 字典中第2个键的值来排序 (d:d[1])
第三个参数 reverse = Ture 告诉 sorted 按照从小到大的顺序排列

第二个注意的点, 为了绘制美观的图标,我们需要在图表中显示完整的地区名称

为了显示完整的地区名称,我们需要重新写一个函数,这个函数返回一个包含完整地区名称的字典,代码如下

def get_cm_countries(filename):
    cm_countries = {}
    with open(filename) as f:
        pop_data = json.load(f)
    key = True
    for pop_dict in pop_data:
        if pop_dict['Year'] == '2014':
            country_name = pop_dict['Country Name']
            value = int(float(pop_dict['Value']))
            code = get_country_code(country_name)
            if country_name == 'World':
                key = False
                cm_countries[country_name] = value # 'World' 不在 COUNTRIES 字典里面
            if code and (key == False):
                cm_countries[country_name] = value
    return cm_countries

相应的主程序也要修改

#! /usr/bin/python <br> # -*- coding: utf8 -*-
import pygal
import json
from country_codes import get_country_code
from pygal.style import RotateStyle
from pygal.style import LightColorizedStyle
from countries import get_cm_countries
#将数据加载到一个列表中
filename = 'gdp.json'

#创建一个包含字典
cc_GDP = {}
cc_GDP1={}

cc_GDP = get_cm_countries(filename)
#把GDP达到万亿以上的国家存进字典 cc_GDP1
for cc,GDP in cc_GDP.items():
    if  GDP > 1E12:
        cc_GDP1[cc] = GDP

dic = sorted(cc_GDP1.items(), key=lambda d:d[1], reverse = True)
dic = dic[0:10]
line_chart = pygal.HorizontalBar()
line_chart.title='The top 10 countries in 2014-GDP-Rank'
for element in dic:
    line_chart.add(element[0],int(element[1]))
line_chart.render_to_file('top 10 in 2014.svg')

看一下成果

最后进行一下代码重构,将生成svg文件的画图程序重构成一个接受年份的函数,方便多次画图

重构一下 得到包含完整国家名称的字典的函数


def get_cm_countries(filename,year):
    cm_countries = {}
    with open(filename) as f:
        pop_data = json.load(f)
    key = True
    for pop_dict in pop_data:
        if pop_dict['Year'] == str(year):
            country_name = pop_dict['Country Name']
            value = int(float(pop_dict['Value']))
            code = get_country_code(country_name)
            if country_name == 'World':
                key = False
                cm_countries[country_name] = value # 'World' 不在 COUNTRIES 字典里面
            if code and (key == False):
                cm_countries[country_name] = value
    return cm_countries

重构一下主函数

def one_plot(filename,year):
    cc_GDP = {}
    cc_GDP1={}
    cc_GDP = get_cm_countries(filename,year)
    #把GDP达到万亿以上的国家存进字典 cc_GDP1
    for cc,GDP in cc_GDP.items():
        if  GDP > 1E12:
            cc_GDP1[cc] = GDP

    dic = sorted(cc_GDP1.items(), key=lambda d:d[1], reverse = True)
    dic = dic[0:10]
    line_chart = pygal.HorizontalBar()
    line_chart.title='The top 10 countries in '+str(year)+'-GDP-Rank'
    for element in dic:
        line_chart.add(element[0],int(element[1]))
    line_chart.render_to_file('top 10 in '+str(year)+'.svg')

for year in range(2008,2015):
    one_plot(filename,year)

这样我们一下就生成了从2008年到2015年全部的数据图
贴一下几张图

其实,我们也可以直接把文件写入到csv文件中,然后用excel来画图

最后贴一下 GitHub 链接

https://github.com/JesuisCelestin/python3-data_analyse_16.2

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容