臥槽,還能這麼玩!用Python生成動態PPT

選自TowardsDataScience

作者:Costas Andreou

機器之心編譯

參與:Jamin、張倩

在讀技術博客的過程中,我們會發現那些能夠把知識、成果講透的博主很多都會做動態圖表。他們的圖是怎麼做的?難度大嗎?

這篇文章就介紹了 Python 中一種簡單的動態圖表製作方法,這樣生成的動圖就可以豐富我們的PPT啦~

數據暴增的年代,數據科學家、分析師在被要求對數據有更深的理解與分析的同時,還需要將結果有效地傳遞給他人。如何讓目標聽衆更直觀地理解?當然是將數據可視化啊,而且最好是動態可視化。

本文將以線型圖、條形圖和餅圖爲例,系統地講解如何讓你的數據圖表動起來

這些動態圖表是用什麼做的?

接觸過數據可視化的同學應該對 Python 裏的 Matplotlib 庫並不陌生。它是一個基於 Python 的開源數據繪圖包,僅需幾行代碼就可以幫助開發者生成直方圖、功率譜、條形圖、散點圖等。這個庫裏有個非常實用的擴展包——FuncAnimation,可以讓我們的靜態圖表動起來。

FuncAnimation 是 Matplotlib 庫中 Animation 類的一部分,後續會展示多個示例。如果是首次接觸,你可以將這個函數簡單地理解爲一個 While 循環,不停地在 “畫布” 上重新繪製目標數據圖。

如何使用 FuncAnimation?

這個過程始於以下兩行代碼:

import matplotlib.animation as ani

animator = ani.FuncAnimation(fig, chartfunc, interval = 100)

從中我們可以看到 FuncAnimation 的幾個輸入:

  • fig 是用來 「繪製圖表」的 figure 對象;

  • chartfunc 是一個以數字爲輸入的函數,其含義爲時間序列上的時間;

  • interval 這個更好理解,是幀之間的間隔延遲,以毫秒爲單位,默認值爲 200。

這是三個關鍵輸入,當然還有更多可選輸入,感興趣的讀者可查看原文檔,這裏不再贅述。

下一步要做的就是將數據圖表參數化,從而轉換爲一個函數,然後將該函數時間序列中的點作爲輸入,設置完成後就可以正式開始了。

在開始之前依舊需要確認你是否對基本的數據可視化有所瞭解。也就是說,我們先要將數據進行可視化處理,再進行動態處理。

按照以下代碼進行基本調用。另外,這裏將採用大型流行病的傳播數據作爲案例數據(包括每天的死亡人數)。

import matplotlib.animation as ani
import matplotlib.pyplot as plt
import numpy as np
import pandas as pdurl = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv'
df = pd.read_csv(url, delimiter=',', header='infer')df_interest = df.loc[
    df['Country/Region'].isin(['United Kingdom', 'US', 'Italy', 'Germany'])
    & df['Province/State'].isna()]df_interest.rename(
    index=lambda x: df_interest.at[x, 'Country/Region'], inplace=True)
df1 = df_interest.transpose()df1 = df1.drop(['Province/State', 'Country/Region', 'Lat', 'Long'])
df1 = df1.loc[(df1 != 0).any(1)]
df1.index = pd.to_datetime(df1.index)

繪製三種常見動態圖表

繪製動態線型圖

如下所示,首先需要做的第一件事是定義圖的各項,這些基礎項設定之後就會保持不變。它們包括:創建 figure 對象,x 標和 y 標,設置線條顏色和 figure 邊距等:

import numpy as np
import matplotlib.pyplot as pltcolor = ['red', 'green', 'blue', 'orange']
fig = plt.figure()
plt.xticks(rotation=45, ha="right", rotation_mode="anchor") #rotate the x-axis values
plt.subplots_adjust(bottom = 0.2, top = 0.9) #ensuring the dates (on the x-axis) fit in the screen
plt.ylabel('No of Deaths')
plt.xlabel('Dates')

接下來設置 curve 函數,進而使用 .FuncAnimation 讓它動起來:

def buildmebarchart(i=int):
    plt.legend(df1.columns)
    p = plt.plot(df1[:i].index, df1[:i].values) #note it only returns the dataset, up to the point i
    for i in range(0,4):
        p[i].set_color(color[i]) #set the colour of each curveimport matplotlib.animation as ani
animator = ani.FuncAnimation(fig, buildmebarchart, interval = 100)
plt.show()

動態餅狀圖

可以觀察到,其代碼結構看起來與線型圖並無太大差異,但依舊有細小的差別。

import numpy as np
import matplotlib.pyplot as pltfig,ax = plt.subplots()
explode=[0.01,0.01,0.01,0.01] #pop out each slice from the piedef getmepie(i):
    def absolute_value(val): #turn % back to a number
        a  = np.round(val/100.*df1.head(i).max().sum(), 0)
        return int(a)
    ax.clear()
    plot = df1.head(i).max().plot.pie(y=df1.columns,autopct=absolute_value, label='',explode = explode, shadow = True)
    plot.set_title('Total Number of Deaths\n' + str(df1.index[min( i, len(df1.index)-1 )].strftime('%y-%m-%d')), fontsize=12)import matplotlib.animation as ani
animator = ani.FuncAnimation(fig, getmepie, interval = 200)
plt.show()

主要區別在於,動態餅狀圖的代碼每次循環都會返回一組數值,但在線型圖中返回的是我們所在點之前的整個時間序列。返回時間序列通過 df1.head(i) 來實現,而. max()則保證了我們僅獲得最新的數據,因爲流行病導致死亡的總數只有兩種變化:維持現有數量或持續上升。

df1.head(i).max()

動態條形圖

創建動態條形圖的難度與上述兩個案例並無太大差別。在這個案例中,作者定義了水平和垂直兩種條形圖,讀者可以根據自己的實際需求來選擇圖表類型並定義變量欄。

fig = plt.figure()
bar = ''def buildmebarchart(i=int):
    iv = min(i, len(df1.index)-1) #the loop iterates an extra one time, which causes the dataframes to go out of bounds. This was the easiest (most lazy) way to solve this :)
    objects = df1.max().index
    y_pos = np.arange(len(objects))
    performance = df1.iloc[[iv]].values.tolist()[0]
    if bar == 'vertical':
        plt.bar(y_pos, performance, align='center', color=['red', 'green', 'blue', 'orange'])
        plt.xticks(y_pos, objects)
        plt.ylabel('Deaths')
        plt.xlabel('Countries')
        plt.title('Deaths per Country \n' + str(df1.index[iv].strftime('%y-%m-%d')))
    else:
        plt.barh(y_pos, performance, align='center', color=['red', 'green', 'blue', 'orange'])
        plt.yticks(y_pos, objects)
        plt.xlabel('Deaths')
        plt.ylabel('Countries')animator = ani.FuncAnimation(fig, buildmebarchart, interval=100)plt.show()

在製作完成後,存儲這些動態圖就非常簡單了,可直接使用以下代碼:

animator.save(r'C:\temp\myfirstAnimation.gif')

感興趣的讀者如想獲得詳細信息可參考:https://matplotlib.org/3.1.1/api/animation_api.html。

原文鏈接:https://towardsdatascience.com/learn-how-to-create-animated-graphs-in-python-fce780421afe

近期十大熱門:
我總結的80頁《菜鳥學Python精選乾貨.pdf》,都是乾貨

笑噴了,我用Python幫韋小寶選最佳老婆組合
用Python一鍵生成炫酷九宮格圖片,火了朋友圈

菜鳥也瘋狂!8分鐘用Python做一個酷炫的家庭隨手記

Github獲8300星!用Python開發的一個命令行的網易雲音樂

一道Python面試題,硬是沒憋出來,最後憋出一身汗!
Python高手進階|實戰4大併發祕籍

讓你縱橫 GitHub 的五大神器

值得收藏!8大技巧,帶你瞭解菜鳥和高手的區別!

臥槽!Pdf轉Word用Python輕鬆搞定!

由菜鳥學Python原班人馬打造的公衆號【程序員GitHub】,專注於分享GitHub上有趣的資源包括,Python,Java,Go語言前端學習等優質的學習資源,爆料程序員圈的新鮮趣事,熱門乾貨,職場感悟,感興趣的小夥伴可以來捧場!

點的“在看”,否則就看不到我了555
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章