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

參考教材

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

引言

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

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

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

step 1: 繪制中國(guó)歷年 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年增長(zhǎng)率

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

#GDP增長(zhǎng)率
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)顯示不過來(lái)了
不過可以發(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è)鍵的值來(lái)排序 (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á)到萬(wàn)億以上的國(guó)家存進(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)一下 得到包含完整國(guó)家名稱的字典的函數(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á)到萬(wàn)億以上的國(guó)家存進(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來(lái)畫圖

最后貼一下 GitHub 鏈接

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市驾窟,隨后出現(xiàn)的幾起案子庆猫,更是在濱河造成了極大的恐慌,老刑警劉巖绅络,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件月培,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡恩急,警方通過查閱死者的電腦和手機(jī)杉畜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)衷恭,“玉大人此叠,你說(shuō)我怎么就攤上這事∷嬷椋” “怎么了灭袁?”我有些...
    開封第一講書人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵猬错,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我茸歧,道長(zhǎng)倦炒,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任软瞎,我火速辦了婚禮逢唤,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘铜涉。我一直安慰自己蜕企,他們只是感情好疹味,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開白布雕擂。 她就那樣靜靜地躺著杠愧,像睡著了一般题山。 火紅的嫁衣襯著肌膚如雪枫振。 梳的紋絲不亂的頭發(fā)上澳化,一...
    開封第一講書人閱讀 51,365評(píng)論 1 302
  • 那天烁竭,我揣著相機(jī)與錄音召边,去河邊找鬼铺呵。 笑死,一個(gè)胖子當(dāng)著我的面吹牛隧熙,可吹牛的內(nèi)容都是我干的片挂。 我是一名探鬼主播,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼贞盯,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼音念!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起躏敢,我...
    開封第一講書人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤闷愤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后件余,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體讥脐,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年啼器,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了旬渠。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡端壳,死狀恐怖告丢,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情更哄,我是刑警寧澤芋齿,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布腥寇,位于F島的核電站,受9級(jí)特大地震影響觅捆,放射性物質(zhì)發(fā)生泄漏赦役。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一栅炒、第九天 我趴在偏房一處隱蔽的房頂上張望掂摔。 院中可真熱鬧,春花似錦赢赊、人聲如沸乙漓。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)叭披。三九已至,卻和暖如春玩讳,著一層夾襖步出監(jiān)牢的瞬間涩蜘,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工熏纯, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留同诫,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓樟澜,卻偏偏與公主長(zhǎng)得像误窖,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子秩贰,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容