參考教材
<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é)果圖
其實(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)畫圖