用Python做動態圖放到你的PPT看上去更高階

導語

哈嘍吖~鐵汁萌!大家有做過PPT嗎?無論是在學校裡完成課業還是辦公我們一般都需要做PPT~

用Python做動態圖放到你的PPT看上去更高階

今天呢小編就打算出一期教大家做動態圖放到PPT當中,讓做好的PPT看上去更高階一些!我們會發現那些能夠把知識、成果講透的博主很多都會做動態圖表。他們的徒弟是怎麼做的?難度大嗎?接下來就告訴你!

正文

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

用Python做動態圖放到你的PPT看上去更高階

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

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

用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 aniimport matplotlib。pyplot as pltimport numpy as npimport 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)

繪製三種常見動態圖表

繪製動態線型圖

用Python做動態圖放到你的PPT看上去更高階

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

import numpy as npimport matplotlib。pyplot as pltcolor = [‘red’, ‘green’, ‘blue’, ‘orange’]fig = plt。figure()plt。xticks(rotation=45, ha=“right”, rotation_mode=“anchor”) #rotate the x-axis valuesplt。subplots_adjust(bottom = 0。2, top = 0。9) #ensuring the dates (on the x-axis) fit in the screenplt。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 anianimator = ani。FuncAnimation(fig, buildmebarchart, interval = 100)plt。show()

動態餅狀圖

用Python做動態圖放到你的PPT看上去更高階

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

import numpy as npimport 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 anianimator = 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’)

end

好啦這期就分享到這裡結束了!希望對你們有幫助,喜歡的話記得給小編個三連噢~家人們的支援是小編更新最大的動力

想領取完整原始碼跟更多Python學習資料可私信我“666”