Python編程實(shí)現(xiàn)超炫動(dòng)態(tài)排序圖
用 python 制作超燃動(dòng)態(tài)排序視頻
在開始之前,先貼張圖,之前網(wǎng)上一段時(shí)間下面這種排序風(fēng)格視頻很火,下面這張圖當(dāng)作是視頻其中的一幀。
制作這樣視頻的原理:就是把不同的幀組合在一起拼接成視頻;把不同時(shí)間的排序圖拼接在一起,拼接在一起形成一個(gè)隨時(shí)間快速變化的動(dòng)畫,轉(zhuǎn)化成視頻,為了觀看效果加一首很燃的BGM,最后的效果很贊。
這種視頻 python 也能做,基本上分為三大部分,主要用到的就是兩個(gè)庫函數(shù) pandas做數(shù)據(jù)處理,matplotlib繪制表、制作視頻動(dòng)畫
1,數(shù)據(jù)預(yù)處理
這一部分細(xì)分為:數(shù)據(jù)讀取,隨機(jī)生成顏色代碼,城市地區(qū)與顏色映射關(guān)系構(gòu)造。
本次選取的數(shù)據(jù)為從1500年到2018年各地區(qū)的人數(shù)統(tǒng)計(jì)(提醒一下,是各城市所在區(qū)域人口數(shù)量)
數(shù)據(jù)源鏈接:1500-2018各地區(qū)人口數(shù)量
# 導(dǎo)入庫函數(shù) import random import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker import matplotlib.animation as animation from IPython.display import HTML import matplotlib #防止動(dòng)漫內(nèi)存太大,報(bào)錯(cuò) matplotlib.rcParams['animation.embed_limit'] = 2**128
原數(shù)據(jù)是這樣的,數(shù)據(jù)之間以”,(逗號(hào))“隔開,我們需要的只是其中的幾列,所以這里利用pandas 中的 usecols做一些列提取;
#pandas讀取數(shù)據(jù),且去列名分別為name,group,year和value的值; url = 'https://gist.githubusercontent.com/johnburnmurdoch/4199dbe55095c3e13de8d5b2e5e5307a/raw/fa018b25c24b7b5f47fd0568937ff6c04e384786/city_populations' df = pd.read_csv(url, usecols=['name', 'group', 'year', 'value']) df.head()
因?yàn)槊總€(gè)地區(qū)標(biāo)記一個(gè)顏色,這里需要構(gòu)造一個(gè)隨機(jī)顏色代碼生成函數(shù):
#導(dǎo)入random函數(shù),randomcolor用于生成顏色代碼 # randomcolor生成顏色代碼原理, # 【1-9/A-F】15個(gè)數(shù)字隨機(jī)組合成6位字符串前面再加上一個(gè)“#”號(hào)鍵 import random def randomcolor(): colorlist = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] color ='' for i in range(6): color += random.choice(colorlist) return '#'+ color
最后構(gòu)造兩個(gè)字典:一個(gè)是城市與顏色之間的,一個(gè)是城市與所在區(qū)域(亞洲、歐洲等)之間的,
形成一一映射關(guān)系方便后續(xù)處理
#對(duì)地區(qū)列表進(jìn)行去重,分類; area_list1 = set(df['name']) # color_list用于存放隨機(jī)生成顏色代碼個(gè)數(shù) # 因?yàn)楹竺鎱^(qū)域個(gè)數(shù) 要與顏色個(gè)數(shù)保持一致,這里用了len函數(shù); color_list =[] for i in range(len(area_list1)): str_1 = randomcolor() color_list.append(str_1) str_1 = randomcolor() #area_list轉(zhuǎn)化為列表 area_list_1 = [i for i in area_list1] print(color_list) print(area_list_1)
構(gòu)造映射關(guān)系:
#colors表示 所在城市:顏色 一一對(duì)應(yīng)字典形式; colors =dict(zip(area_list_1,color_list)) print(colors) #group_lk為 城市:所在區(qū)域 --對(duì)應(yīng)字典形式; group_lk = df.set_index('name')['group'].to_dict() print(group_lk)
2,圖表繪制
這一部分主要是利用matplotlib 寫了一個(gè)在某一年中各地區(qū)人口分布的直方圖繪制函數(shù),在代碼每一步中有詳細(xì)注釋,想實(shí)現(xiàn)的可以參照一下代碼:
# 用plt加理圖表,figsize表示圖標(biāo)長寬,ax表示標(biāo)簽 fig, ax = plt.subplots(figsize=(15, 8)) #dras_barchart生成current_year這一年各城市人口基本情況; def draw_barchart(current_year): #dff對(duì)year==current_year的行,以value從升序方式排序,取后十名也就是最大值; dff = df[df['year'].eq(current_year)].sort_values(by='value',ascending = True).tail(12) # 所有坐標(biāo)、標(biāo)簽清除 ax.clear() #顯示顏色、城市名字 ax.barh(dff['name'],dff['value'],color = [colors[x] for x in dff['name']]) dx = dff['value'].max()/200 #ax.text(x,y,name,font,va,ha) # x,y表示位置; # name表示顯示文本; # va,ba分別表示水平位置,垂直放置位置; for i ,(value,name) in enumerate(zip(dff['value'], dff['name'])): ax.text(value-dx,i,name,size=14,weight=600,ha ='right',va = 'bottom') ax.text(value-dx,i-.25,group_lk[name],size = 10,color ='#444444',ha ='right',va = 'baseline') ax.text(value+dx,i ,f'{value:,.0f}',size = 14,ha = 'left',va ='center') #ax.transAxes表示軸坐標(biāo)系,(1,0.4)表示放置位置 ax.text(1,0.4,current_year,transform = ax.transAxes,color ='#777777',size = 46,ha ='right',weight=800) ax.text(0,1.06,'Population (throusands)',transform = ax.transAxes,size=12,color='#777777') #set_major_formatter表示刻度尺格式; ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}')) ax.xaxis.set_ticks_position('top') ax.tick_params(axis='x',colors='#777777',labelsize=12) ax.set_yticks([]) #margins表示自動(dòng)縮放余額; ax.margins(0,0.01) # 設(shè)置后面的網(wǎng)格 ax.grid(which='major',axis='x',linestyle='-') #刻度線和網(wǎng)格線是在圖標(biāo)上方還是下方,True為下方 ax.set_axisbelow(True) ax.text(0,1.15,'The most population cities in the word from 1500 to 2018', transform=ax.transAxes,size=24,weight=600,ha='left',va='top') ax.text(1,0,'by@zeroing1',transform = ax.transAxes,color ='#777777',ha = 'right', bbox = dict(facecolor='white',alpha = 0.8,edgecolor='white')) #取消圖表周圍的方框顯示 plt.box(False) #繪制2018年各城市人口情況 draw_barchart(2018)
圖表如下:
3,制作的圖表轉(zhuǎn)化為視頻、動(dòng)畫
用到的功能是 matplotlib 的 animation 函數(shù),下面這個(gè)是生成一個(gè)jshtml頁面,可以在線預(yù)覽
#將原來的靜態(tài)圖拼接成動(dòng)畫 fig, ax = plt.subplots(figsize=(15, 8)) animator = animation.FuncAnimation(fig, draw_barchart, frames=range(1500, 2019)) #保存到j(luò)shtml HTML(animator.to_jshtml())
展示效果如下:
當(dāng)然,也可以直接生成視頻保存到本地,但在此之前請(qǐng)確保你的電腦已經(jīng)配置好 FFmpeg,然后運(yùn)行下面的代碼,否則的話無法生成
#生成video,并保存至指定文件夾中 animator.to_html5_video() animator.save('E:/ceshi/country_populations1.mp4')
然后可以加上合適的背景音樂,一個(gè)超燃的動(dòng)態(tài)排序視頻就完成了!
以上就是Python編程實(shí)現(xiàn)超炫動(dòng)態(tài)排序圖的詳細(xì)內(nèi)容,更多關(guān)于Python實(shí)現(xiàn)動(dòng)態(tài)排序圖的資料請(qǐng)關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。