菜鳥筆記Python3——數(shù)據(jù)可視化(三)世界GDP分析

參考教材

<Python編程——從入門到實(shí)踐> chapter16 數(shù)據(jù)可視化

引言

經(jīng)過世界地圖的練習(xí),我們現(xiàn)在來進(jìn)行自己的數(shù)據(jù)可視化小項(xiàng)目。Open Konwledge Foundation 提供了一個(gè)數(shù)據(jù)集,其中包含各國的國內(nèi)生產(chǎn)總值(GDP),我們可以在 http://data.okfn.org/data/core/gdp 中找到這個(gè)數(shù)據(jù)集。接下來,讓我們做一些有趣的小練習(xí)吧......

section 1:中國GDP的數(shù)據(jù)可視化練習(xí)

下載完成這個(gè) json 文件之后,用記事本打開,搜索一下 'China' , 觀察一下數(shù)據(jù)格式
{"Country Name":"China","Country Code":"CHN","Year":"1960","Value":"59184116448.734"}
后面的事情就很簡(jiǎn)單了

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: 進(jìn)階一點(diǎn),GDP年增長率

數(shù)據(jù)都分類好了,直接玩數(shù)學(xué)游戲就行了
代碼

#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()

結(jié)果圖

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

其實(shí)還可以畫折點(diǎn)圖

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')

效果圖


額。。。。 ( ̄▽ ̄") 數(shù)據(jù)太多橫坐標(biāo)顯示不過來了
不過可以發(fā)現(xiàn),在數(shù)據(jù)比較少的時(shí)候這樣的圖還是很不錯(cuò)的 o(*≧▽≦)ツ

section 2: 世界 GDP 數(shù)據(jù)統(tǒng)計(jì)

step 1 : 世界地圖

原理跟之前統(tǒng)計(jì)世界人口一模一樣,改一下代碼中的關(guān)鍵字

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
#將數(shù)據(jù)加載到一個(gè)列表中
filename = 'gdp.json'


#創(chuàng)建一個(gè)字典
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 排行

存儲(chǔ)數(shù)據(jù)的字典完成之后,如果我們想根據(jù) GDP 排序, 那么需要考慮 對(duì)字典中的鍵值對(duì)排序
經(jīng)過網(wǎng)絡(luò),我們發(fā)現(xiàn)了這樣一種辦法 :

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

分析一下:

第一個(gè)參數(shù) cc_GDP.items()sorted 傳遞了字典中的鍵值對(duì)信息
第二個(gè)參數(shù) key=lambda d:d[1] 告訴 sorted 要按照 字典中第2個(gè)鍵的值來排序 (d:d[1])
第三個(gè)參數(shù) reverse = Ture 告訴 sorted 按照從小到大的順序排列

第二個(gè)注意的點(diǎn), 為了繪制美觀的圖標(biāo),我們需要在圖表中顯示完整的地區(qū)名稱

為了顯示完整的地區(qū)名稱,我們需要重新寫一個(gè)函數(shù),這個(gè)函數(shù)返回一個(gè)包含完整地區(qū)名稱的字典,代碼如下

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

相應(yīng)的主程序也要修改

#! /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
#將數(shù)據(jù)加載到一個(gè)列表中
filename = 'gdp.json'

#創(chuàng)建一個(gè)包含字典
cc_GDP = {}
cc_GDP1={}

cc_GDP = get_cm_countries(filename)
#把GDP達(dá)到萬億以上的國家存進(jìn)字典 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')

看一下成果

最后進(jìn)行一下代碼重構(gòu),將生成svg文件的畫圖程序重構(gòu)成一個(gè)接受年份的函數(shù),方便多次畫圖

重構(gòu)一下 得到包含完整國家名稱的字典的函數(shù)


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

重構(gòu)一下主函數(shù)

def one_plot(filename,year):
    cc_GDP = {}
    cc_GDP1={}
    cc_GDP = get_cm_countries(filename,year)
    #把GDP達(dá)到萬億以上的國家存進(jìn)字典 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年全部的數(shù)據(jù)圖
貼一下幾張圖

其實(shí),我們也可以直接把文件寫入到csv文件中,然后用excel來畫圖

最后貼一下 GitHub 鏈接

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容