PYTHON動態圖實例&實踐

今天(3.8)是個特殊節日哈,針對婦女朋友。衆所周知,世界上最早的程序員是女性哦,剛好有GITHUB一個超火的動態圖項目:barrace(https://gist.githubusercontent.com/johnburnmurdoch/4199dbe55095c3e13de8d5b2e5e5307a/raw/),博主我就順勢發揮下,整出個主題有的意思的玩意,各位可以提提意見。

##主題
利用pandas,matplotlib,爬蟲得到2010-2018年世界各國女性人口占比。數據格式如下:需要完整數據、動圖等、python文件可在我的資源頁面下載。
在這裏插入圖片描述

#代碼

#導入庫,非完全原創
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib. animation as animation
import plotly
from  IPython.display import HTML
from matplotlib import font_manager

##數據處理合併
'''
f = pd.ExcelFile('人口數據.xlsx')
y=f.sheet_names
df = pd.DataFrame()
for i in y[:-1]:
    d = pd.read_excel('人口數據.xlsx', sheet_name= i)
    df = pd.concat([df, d],axis=0)
df.to_excel('新人口數據.xlsx')
'''
#my_font = font_manager.FontProperties(fname="/Library/Fonts/Songti.ttc")
plt.rcParams['font.sans-serif']=['SimHei'] #用來正常顯示中文標籤這必須有,否則matplotlib無法準確使用中文顯示
df = pd.read_csv('‘新人口數據’, 
                 usecols=['nation', 'group', 'year', 'value'])
current_year = 2018 #似乎是第一幀的數據年份索引
#fig, ax = plt.subplots(figsize=(25, 12))
#讀取數據
df1 = pd.read_excel('新人口數據.xlsx')  #, usecols=['nation', 'group', 'year', 'value']
df = pd.read_excel(r'C:\Users\ASUS\Desktop\新人口數據.xlsx', usecols=['nation', 'group', 'year', 'value'])
current_year = 2018
y=df['nation'] #可刪除

colors = dict(zip( ['亞洲', '美洲', '非洲', '大洋洲', '歐洲'],
    ['#FF69B4', '#00FFFF', '#FFA500', '#00FFFF','#1E90FF']
))  #利用zip函數將兩個列表中元素對應組合成字典
#'#FF69B4' 爲RGB顏色的16進製表示
group_lk = df.set_index('nation')['group'].to_dict()  #也是字典。
fig, ax = plt.subplots(figsize=(25, 12))
def draw_barchart(year):
    #dff 1= df[df['year'].eq(year)].sort_values(by='value', ascending=True).tail(10) #抽取對於年份數據進行排序,取尾部後10個順序排列,
    dff = df[df['year'].eq(year)][0:12].sort_values(by='value', ascending=True)  #ascending=false也可,這是繪圖數據,爲了使得變化性,與上一級二選一
    ax.clear()
    ax.barh(dff['name'], dff['value'], color=[colors[group_lk[x]] for x in dff['name']])
    dx = dff['value'].max() / 1000 #控制字符效果的偏移量
    for i, (value, name) in enumerate(zip(dff['value'], dff['name'])): #enumerate是個好東西 ,返回元組,包含元素和元素序號
        #pass
        a=100*value-100*dx
        b=100*value-100*dx
        c=100*value+100*dx
        d=100*value
        ax.text(a, i,     nation,           size=14, weight=600, ha='right', va='bottom') #不可進行運算,直接填100*value-100*dx
        ax.text(b, i-.25, group_lk[nation], size=10, color='#444444', ha='right', va='baseline')
        ax.text(c, i,     f'{d:,.1f}',  size=14, ha='left',  va='center')
    print(value,'&',dx,i)
    # ... polished styles
    ax.text(1, 0.4, year, transform=ax.transAxes, color='#666667', size=46, ha='right', weight=800)
    ax.text(0, 1.06, 'Percentage (%)', transform=ax.transAxes, size=12, color='#777777')  #text ,主要接受座標參數,隨圖片大小靈活調整
    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([]) #y 座標軸不顯示
    ax.margins(0, 0.01)
    ax.grid(which='major', axis='x', linestyle='-')
    ax.set_axisbelow(True)
    ax.text(0.08, 1.10, 'The proportion of women in every country in the world from 2010 to 2018',
            transform=ax.transAxes, size=24, weight=600, ha='left')

    plt.box(False)
draw_barchart(2018)

animator = animation.FuncAnimation(fig, draw_barchart,frames=range(2010, 2019),interval=488)  #interval單位是ms,。
animator.save('demo-bar-race-womenrate-t.gif')    #也可以是其他格式,如MP4
    

效果展示

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

分析

數據分析無處不在,可以看出,世界上190多個國家中,女性還是多於男性,多爲西方國家,我國女性比例最近是48.7%,雖然男女失衡,但在逐年好轉。而少數國家出現了20%~30%了,如卡塔爾這是十分危險的!最後給個絕對值人口數據吧
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章