天天看點

matplotlib秘技:讓可視化圖形動起來

編者按:其實matplotlib有一個少有人知的功能animation.FuncAnimation,可以接受你編寫的動畫函數建立動圖。Viviane Kakerbeck通過一個例子展示了這一功能的用法,并介紹了通過增強資料和高斯平滑,讓動圖更美觀的技巧。
matplotlib秘技:讓可視化圖形動起來

美國的過量服用海洛因緻死數,使用seaborn建立

Python的matplotlib和seaborn是非常好用的繪圖庫。但它們建立的都是靜态圖像,難以通過動态、美觀的方式描述資料值的變化。如果你的下一次示範或者下一篇部落格文章,能用動态圖形展示資料的發展,該有多好?更妙的是,你可以繼續使用matplotlib、seaborn或者其他你喜歡用的庫。

我最近為一部關于美國的阿片樣物質危機的紀錄片制作了一些動态圖形,是以我會在這篇文章中使用相關的資料。資料來自美國國家藥物濫用研究所和CDC的公開資料,可以從以下網址下載下傳:https://www.drugabuse.gov/sites/default/files/overdose_data_1999-2015.xls

本文将使用matplotlib和seaborn繪制圖形,同時使用numpy和pandas處理資料。matplotlib提供了一些可以用來制作動畫的函數。閑話少叙,讓我們開始吧,首先,是引入所有依賴。

  1. import numpy as np

  2. import pandas as pd

  3. import seaborn as sns

  4. import matplotlib

  5. import matplotlib.pyplot as plt

  6. import matplotlib.animation as animation

然後我們加載資料,将其轉換成pandas的DataFrame。我還編寫了一個輔助函數,可以從感興趣的行加載資料,之後繪圖會用到。

  1. overdoses = pd.read_excel('overdose_data_1999-2015.xls',sheetname='Online',skiprows =6)

  2. def get_data(table,rownum,title):

  3. data = pd.DataFrame(table.loc[rownum][2:]).astype(float)

  4. data.columns = {title}

  5. return data

準備就緒,下面是本文主要部分,如何繪制動畫。

首先,如果你和我一樣,用的是jupyter notebook,那麼我建議你使用%matplotlib notebook指令,這樣可以直接在notebook中檢視動畫效果,無需等待儲存後再檢視。

我使用了之前編寫的輔助函數get_data取得海洛因服用過量數,并将其封裝入一個兩列的pandas DataFrame,一清單示年份,一清單示服用過量數。

  1. %matplotlib notebook

  2. title = 'Heroin Overdoses'

  3. d = get_data(overdoses,18,title)

  4. x = np.array(d.index)

  5. y = np.array(d['Heroin Overdoses'])

  6. overdose = pd.DataFrame(y,x)

  7. #XN,YN = augment(x,y,10)

  8. #augmented = pd.DataFrame(YN,XN)

  9. overdose.columns = {title}

接着我們初始化一個寫入器(writer),基于ffmpeg記錄20 fps(比特率為1800)。當然,你可以按照需要調整這些參數。

  1. Writer = animation.writers['ffmpeg']

  2. writer = Writer(fps=20, metadata=dict(artist='Me'), bitrate=1800)

接下來建立一個帶标簽的圖形。别忘了限定x軸和y軸的範圍,以免動畫在顯示資料時出現跳躍現象。

  1. fig = plt.figure(figsize=(10,6))

  2. plt.xlim(1999, 2016)

  3. plt.ylim(np.min(overdose)[0], np.max(overdose)[0])

  4. plt.xlabel('Year',fontsize=20)

  5. plt.ylabel(title,fontsize=20)

  6. plt.title('Heroin Overdoses per Year',fontsize=20)

制作動畫的關鍵是定義一個動畫函數,指定視訊的每一幀發生了什麼。這裡i表示動畫幀的索引。你可以選擇在i幀中可見的資料範圍。之後我使用seaborn的線圖繪制標明資料。最後兩行我調整了一些尺寸,使圖形看起來更美觀。

  1. def animate(i):

  2. data = overdose.iloc[:int(i+1)] # 標明資料範圍

  3. p = sns.lineplot(x=data.index, y=data[title], data=data, color="r")

  4. p.tick_params(labelsize=17)

  5. plt.setp(p.lines,linewidth=7)

定義了動畫函數後,使用matplotlib.animation.FuncAnimation定義動畫應當包含多少幀,也就是說,通過frames參數定義調用animate(i)的頻率。

  1. ani = matplotlib.animation.FuncAnimation(fig, animate, frames=17, repeat=True)

之後隻需調用ani.save()就可以将動畫儲存為mp4檔案。如果你想在儲存之前先看下效果,那麼可以使用plt.show()。

  1. ani.save('HeroinOverdosesJumpy.mp4', writer=writer)

好了,讓我們來看下效果。

matplotlib秘技:讓可視化圖形動起來

看起來效果還可以,但是感覺有點抖動。為了緩解抖動的現象,我們可以在已有資料中插入一些中間值,平滑一下。為此我們定義以下的資料增強函數:

  1. def augment(xold,yold,numsteps):

  2. xnew = []

  3. ynew = []

  4. for i in range(len(xold)-1):

  5. difX = xold[i+1]-xold[i]

  6. stepsX = difX/numsteps

  7. difY = yold[i+1]-yold[i]

  8. stepsY = difY/numsteps

  9. for s in range(numsteps):

  10. xnew = np.append(xnew,xold[i]+s*stepsX)

  11. ynew = np.append(ynew,yold[i]+s*stepsY)

  12. return xnew,ynew

之後我們隻需在資料上應用這一增強函數,并相應地增加matplotlib.animation.FuncAnimation函數中的幀數。這裡我調用augment函數時使用了參數numsteps=10,也就是說,我将資料點增加到160個,相應地,幀數設定為frames=160。增強資料之後,結果看起來平滑了很多,但在資料值變動處,曲線仍有一些尖角,看起來不是特别美觀。

為了讓圖像看起來更美觀,我們實作了一個高斯平滑函數:

  1. def smoothListGaussian(listin,strippedXs=False,degree=5):

  2. window=degree*2-1

  3. weight=np.array([1.0]*window)

  4. weightGauss=[]

  5. for i in range(window):

  6. i=i-degree+1

  7. frac=i/float(window)

  8. gauss=1/(np.exp((4*(frac))**2))

  9. weightGauss.append(gauss)

  10. weight=np.array(weightGauss)*weight

  11. smoothed=[0.0]*(len(listin)-window)

  12. for i in range(len(smoothed)): smoothed[i]=sum(np.array(listin[i:i+window])*weight)/sum(weight)

  13. return smoothe

我在這裡不會讨論高斯平滑的細節,感興趣的讀者可以看這篇文章:https://www.swharden.com/wp/2008-11-17-linear-data-smoothing-in-python/

最後我們略微調整下顔色和風格,就得到了文章開頭的動态圖形:

  1. sns.set(rc={'axes.facecolor':'lightgrey', 'figure.facecolor':'lightgrey','figure.edgecolor':'black','axes.grid':False})

matplotlib秘技:讓可視化圖形動起來

本文通過一個例子展現了matplotlib動畫函數的用法。當然,你可以将它用在任何你想要動畫化的圖形上。隻需調整animate()函數中的參數和圖形類型,便有無限可能。

我希望你喜歡matplotlib的整個功能,并能善加利用。另外,如果你對我之前提到的紀錄片感興趣,可以在YouTube上檢視:https://youtu.be/7xrvuSDLHiY

原文釋出時間為: 2018-11-23

本文作者:AI派

本文來自雲栖社群合作夥伴“

AI派

”,了解相關資訊可以關注“

”。