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%了,如卡塔尔这是十分危险的!最后给个绝对值人口数据吧
在这里插入图片描述

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