使用matplotlib做动态排名图
生活随笔
收集整理的這篇文章主要介紹了
使用matplotlib做动态排名图
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
數(shù)據(jù)源
數(shù)據(jù)
過程:
1.將數(shù)據(jù)進(jìn)行持久化存儲(chǔ)
先使用pandas的read_csv函數(shù)從網(wǎng)頁端直接讀取數(shù)據(jù),并篩選部分?jǐn)?shù)據(jù)
得到name,group,year,value數(shù)據(jù)后進(jìn)行持久化存儲(chǔ)避免重復(fù)讀取網(wǎng)頁端數(shù)據(jù)
df.to_csv('data.csv')2.具體表格數(shù)據(jù)處理:
df.head() import random color1=['#BBFFFF', '#FAF0E6', '#FFFF00', '#7CCD7C','#8470FF', '#87CEEB', '#C1FFC1','SlateBlue','Cyan','#C0FF3E','#00EEEE','#FFAEB9','#FFE4E1','#54FF9F','RoyalBlue','Moccasin','#00FF7F','#00FF00','#FFC1C1','#00F5FF','#9AFF9A','#8470FF'] def randomcolor():return random.choice(color1) #對(duì)地區(qū)列表進(jìn)行去重,分類; # 因?yàn)楹竺鎱^(qū)域個(gè)數(shù) 要與顏色個(gè)數(shù)保持一致,這里用了len函數(shù); color_list =[] for i in range(df['name'].size):str_1 = randomcolor()color_list.append(str_1)str_1 = randomcolor() area_list_1 = list(df['name'])#Series colors =dict(zip(area_list_1,color_list)) group_lk = df.set_index('name')['group'].to_dict()#每個(gè)城市對(duì)應(yīng)的州做成字典形式 # 用plt加理圖表,figsize表示圖標(biāo)長(zhǎng)寬,ax表示標(biāo)簽 fig, ax = plt.subplots(figsize=(15, 8))#設(shè)置圖表3.畫表格線:
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(16)# 所有坐標(biāo)、標(biāo)簽清除ax.clear()# 顯示顏色、城市名字ax.barh(dff['name'], dff['value'], color=[colors[x] for x in dff['name']])dx = dff['value'].max() / 200for i, (value, name) in enumerate(zip(dff['value'], dff['name'])):#城市名ax.text(value - dx, i, name, size=14, weight=600, ha='right', va='bottom')#標(biāo)簽開始位置,文本,文本字體大小和字體位置(如左上右上)# 城市所在州ax.text(value - dx, i - .25, group_lk[name], size=10, color='#444444', ha='right', va='baseline')#數(shù)據(jù)ax.text(value + dx, i, int(value), size=14, ha='left', va='center')ax.text(1, 0.4, current_year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800)#transform設(shè)置形式,ax.transAxes為軸標(biāo)簽ax.text(0, 1.06, '人口數(shù)量 (/千人)', 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.10, '1900 - 2020 年世界城市人口數(shù)量及排名',transform=ax.transAxes, size=18, fontproperties='SimSun',weight=600, ha='left')ax.text(1, 0, '17195190', transform=ax.transAxes, color='#777777', ha='right',bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))plt.box(False)#取消圖表外邊框4.使用funcanimation制作動(dòng)畫
#單獨(dú)繪制2020年最后一年各城市人口情況 draw_barchart(2020) fig, ax = plt.subplots(figsize=(15, 8)) animator = animation.FuncAnimation(fig, draw_barchart, frames=range(1900, 2021),interval=80,repeat=False)#選擇數(shù)據(jù)源中的1900-2020年的數(shù)據(jù),幀率80ms,取消循環(huán)5.使用pygame添加音效并展示
import pygame from os import environ import time environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1' pygame.mixer.init() url = r"C:\.....mp3" pygame.mixer.music.load(url) pygame.mixer.music.play(-1, 0) plt.show() time.sleep(20) pygame.mixer.music.stop()注意:由于動(dòng)畫特殊性,需要在命令行界面運(yùn)行才能動(dòng)態(tài)展示,否則為靜態(tài)圖。
補(bǔ)充問題:
出現(xiàn)matplotlib中文亂碼怎么辦?
總結(jié)
以上是生活随笔為你收集整理的使用matplotlib做动态排名图的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql navicat如何为表添加外
- 下一篇: hbase建表,删表,修改,查询(get