python的matplotlib的熱門可視化動圖


1.圖

2.代碼

import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker 
import matplotlib.animation as animation
#導出數據,當然這個數據也可以是直接在網上下載,是的有點慢
#網址:https://gist.githubusercontent.com/johnburnmurdoch/4199dbe55095c3e13de8d5b2e5e5307a/raw/fa018b25c24b7b5f47fd0568937ff6c04e384786/city_populations
df = pd.read_csv('city_populations.csv', 
                 usecols=['name', 'group', 'year', 'value']) #將數據下載下來放在指定默認的目錄和文件夾下,city_populations.csv
#定義
current_year = 2018
dff=()

fig, ax = plt.subplots(figsize=(15, 8))

colors = dict(zip(
    ['India', 'Europe', 'Asia', 'Latin America',
     'Middle East', 'North America', 'Africa'],
    ['#adb0ff', '#ffb3ff', '#90d595', '#e48381',
     '#aafbff', '#f7bb5f', '#eafb50']
))

group_lk = df.set_index('name')['group'].to_dict()

def draw_barchart(year):
    dff = df[df['year'].eq(year)].sort_values(by='value', ascending=True).tail(10)
    ax.clear() #每次清空、刷新
    ax.barh(dff['name'], dff['value'], color=[colors[group_lk[x]] for x in dff['name']])
    dx = dff['value'].max() / 200
    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')
    #顯示文字,x=0,y=1.10,坐標,ha=水平對准=水平線平放
    #ax.text()格式=(x,y,string,fontsize=15,verticalalignment="top",horizontalalignment="right")
    #string=字符串='文字內容'
    ax.text(0, 1.10, 'The most populous cities in the world from 1968 to 2018',
            transform=ax.transAxes, size=18, weight=600, ha='left') #文字標題,第1層
    ax.text(0, 1.04, 'Population (thousands)', transform=ax.transAxes, size=12, color='#777777') #顯示文字,第2層
    ax.text(1, 0.4, year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800) #右邊固定顯示動圖年份
    #va=verticalalignment="top",垂直對准
    #ha=horizontalalignment="right",alignment=對准,水平對准
    ax.xaxis.set_ticks_position('top')  #x軸在上面

    ax.set_yticks([]) #默認是顯示y軸的名稱,左邊垂直的城市名字,設為[]就是不顯示
    ax.margins(0, 0.01) #不設置就是默認值,縮放比例(0,0.05)
    ax.grid(which='major', axis='x', linestyle='--') #垂直線,布局和格式
    ax.set_axisbelow(True)  #默認是true的

    plt.box(False) #默認是True,False之后不顯示黑色線框
    
animator = animation.FuncAnimation(fig, draw_barchart, frames=range(1968, 2019)) #以animator形式展現動畫
plt.show() #以plt的形式展現圖片


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM