今天收到一個(gè)可視化數(shù)據(jù)分析的小需求,客戶提供了一份各省份人口的Excel的數(shù)據(jù)文檔。
需要將Excel中的數(shù)據(jù)提取出來(lái),最后將數(shù)據(jù)展示到一個(gè)平面的中國(guó)地圖上面形成一個(gè)可視化的人口分布展示效果。
立即前往微信小程序【知識(shí)星球】提問(wèn)>>>
先展示一下已經(jīng)生成的中華人民共和國(guó)人口分布圖的效果吧!
這次可以選用pyecharts這個(gè)框架來(lái)實(shí)現(xiàn),這個(gè)框架是基于前端的echarts框架實(shí)現(xiàn)的,使用起來(lái)相對(duì)比較簡(jiǎn)單。
下面是Excel文檔中存儲(chǔ)的人口分布數(shù)據(jù),數(shù)據(jù)不具備當(dāng)前中國(guó)人口的真實(shí)性。
使用pandas的read_excel函數(shù)讀取excel文檔數(shù)據(jù)。
# Importing the pandas library and giving it the alias pd.
import pandas as pd
# Importing the numpy library and giving it the alias np.
import numpy as np
# A module that allows you to print things in a pretty way.
from pprint import pprint
# Reading the excel file and storing it in a dataframe.
person_data_frame = pd.read_excel('./person_data.xlsx')
# Converting the dataframe into a list.
person_data_list = np.array(person_data_frame).tolist()
# Printing the list of lists.
pprint(person_data_list)
[['廣東', 10432],
['山東', 9580], ['河南', 9402], ['四川', 8042], ['江蘇', 7865], ['河北', 7185], ['湖南', 6568],
['安徽', 5950], ['湖北', 5724], ['浙江', 5442],
['廣西', 4603], ['云南', 4597], ['江西', 4457], ['云南', 4597], ['江西', 4457], ['遼寧', 4375],
['黑龍江', 3840], ['陜西', 3754], ['山西', 3652], ['福建', 3524], ['貴州', 3245],
['重慶', 2884], ['吉林', 2736], ['甘肅', 2557], ['內(nèi)蒙古', 1987], ['臺(tái)灣', 2316],
['上海', 1876], ['新疆', 2181], ['北京', 1961], ['天津', 1294], ['海南', 876],
['香港', 712], ['寧夏', 654], ['青海', 578], ['西藏', 315], ['澳門', 56]]
然后,將pycharts的非標(biāo)準(zhǔn)模塊導(dǎo)入進(jìn)來(lái),并且配置相應(yīng)的地圖參數(shù)。
# Importing all the charts from the pyecharts library.
from pyecharts.charts import *
# Importing the options module from the pyecharts library and giving it the alias opts.
from pyecharts import options as opts
調(diào)用pyecharts模塊中的Map對(duì)象,使用opts.InitOpts函數(shù)初始化主題顏色、寬度、高度的大小。
map = Map(init_opts=opts.InitOpts(theme='light',
width='1250px',
height='650px'))
設(shè)置地圖的范圍屬性為china,就是顯示的整個(gè)中國(guó)地圖,若是某個(gè)區(qū)域則可以按具體區(qū)域名稱進(jìn)行設(shè)置。
緊接著設(shè)置data_pair的數(shù)據(jù)來(lái)源為我們前面從Excel數(shù)據(jù)文檔中讀取到的list列表數(shù)據(jù),隨后設(shè)置地圖顯示的標(biāo)題即可。
map.add('中華人民共和國(guó)人口分布(萬(wàn)人)',
data_pair=person_data_list,
maptype='china')
map.set_global_opts(visualmap_opts=opts.VisualMapOpts(
max_=230000,
is_piecewise=True
))
最后使用Map的函數(shù)render生成顯示的html源文件-render.html。
# Creating a html file called render.html.
map.render()
在任意瀏覽器中打開(kāi)已經(jīng)生成好的render.html文件就能形成一個(gè)動(dòng)態(tài)顯示的中國(guó)地圖。
「Python 集中營(yíng)」,只做知識(shí)分享 !
聯(lián)系客服