|
excelperfect 標(biāo)簽:Python,Matplotlib庫 Matplotlib是一個(gè)強(qiáng)大的Python繪圖庫,但許多人可能不知道它能夠創(chuàng)建動(dòng)畫圖。 
圖1 什么是動(dòng)畫? 簡單地說,動(dòng)畫由一系列略微有些變化的靜態(tài)圖像組成。當(dāng)把這些靜態(tài)圖像放在一起并快速翻閱時(shí),我們的眼睛和大腦會(huì)欺騙我們,讓我們覺得這些圖像在移動(dòng)(盡管它們不是)。 基于這種理解,要制作動(dòng)畫繪圖,需要: 1.創(chuàng)建大量靜態(tài)圖像/圖表 2.把它們按順序翻動(dòng) 庫 可以使用pip安裝matplotlib,只需在命令提示符/終端窗口中鍵入以下內(nèi)容: pip install matplotlib 使用Matplotlib制作動(dòng)畫 將用matplotlib制作一個(gè)簡單的動(dòng)畫:一個(gè)在半徑為1.5的圓中移動(dòng)的紅點(diǎn)。 首先,需要一個(gè)函數(shù)來計(jì)算圓的x和y坐標(biāo)。這里沒有使用x^2+y^2=r^2公式,而是使用圓的參數(shù)表示: x = cos(t) y = sin(t) 其中t是一個(gè)角度量 %matplotlib notebook import matplotlib.pyplot as plt import math from matplotlib.animation import FuncAnimation def circle_coords(r, step): coords = [] t = 0 while t < 2 * math.pi: coords.append((r*math.cos(t),r*math.sin(t))) t += step return coords coords = circle_coords(1.5, 0.1) 代碼運(yùn)行后,coords內(nèi)的結(jié)果如下圖2所示。 圖2 步驟1:創(chuàng)建一個(gè)靜態(tài)圖表 為坐標(biāo)系coords中的第一組(x,y)坐標(biāo)創(chuàng)建一個(gè)帶有紅點(diǎn)的圖表。 fig, ax = plt.subplots() ax.scatter(x=coords[0][0],y=coords[0][1],c='red', marker = 'o') 此代碼在(1.5,0)處創(chuàng)建一個(gè)紅點(diǎn): 圖3 步驟2:創(chuàng)建許多靜態(tài)圖表 下一步是創(chuàng)建大量略有變化的靜態(tài)圖表。將使用前5個(gè)坐標(biāo)創(chuàng)建5個(gè)圖表來說明這一點(diǎn): fig, axs = plt.subplots(nrows = 1,ncols = 5, figsize = (10, 5), tight_layout = True) for i, ax in enumerate(axs): ax.scatter(x=coords[i][0],y=coords[i][1], c='red', marker='o') ax.set_xlim([0,2]) ax.set_ylim([-0.5,2]) 結(jié)果如下圖4所示。 圖4 如此狹窄的圖表上是想說明,當(dāng)瀏覽每個(gè)圖表時(shí),圓點(diǎn)是向上和向右移動(dòng)的。 Matplotlib中的FuncAnimation模塊 從技術(shù)上講,只需要?jiǎng)?chuàng)建多個(gè)靜態(tài)圖表(每個(gè)坐標(biāo)對應(yīng)一個(gè)),然后將它們組合在一起,就會(huì)有一個(gè)動(dòng)畫。然而,matplotlib庫提供了一個(gè)FuncAnimation模塊來實(shí)現(xiàn)這一點(diǎn)。 要使用FuncAnimation,需要一個(gè)函數(shù)來繪制靜態(tài)圖表。繪圖函數(shù)的名稱無關(guān)緊要,這里將其命名為update(): 1.繪圖函數(shù)接受1個(gè)參數(shù)i,這意味著幀編號。 2.該函數(shù)將在每次調(diào)用開始時(shí)清除圖表,因此在每一幀只會(huì)看到一個(gè)紅點(diǎn)。 3.ax.set_xlim()和ax.set_ylim()函數(shù)以確保修復(fù)x軸和y軸。 4.ax.scatter()一次只畫一個(gè)紅點(diǎn)。 from matplotlib.animation import FuncAnimation def update(i): ax.clear() ax.set_facecolor(plt.cm.Blues(.2)) ax.set_xlim([-2,2]) ax.set_ylim([-2,2]) ax.set_title('circling') ax.scatter(x=coords[i][0],y=coords[i][1],c='red',marker='o') [spine.set_visible(False) for spine in ax.spines.values()] #移除圖表輪廓 現(xiàn)在,有了繪圖函數(shù),可以創(chuàng)建FuncAnimation對象,它接受以下參數(shù): 1.fig:要繪制的圖形對象 2.func:繪圖/更新函數(shù) 3.frames:要?jiǎng)?chuàng)建的幀數(shù)(靜態(tài)圖像) 4.interval:幀間延遲(毫秒) 甚至可以將動(dòng)畫保存為gif文件并發(fā)送給其他人: fig, ax =plt.subplots(figsize=(6,6)) anime = FuncAnimation( fig = fig, func = update, frames = len(coords), interval = 50 ) anime.save('circle.gif') 有興趣的朋友可以試試看!
|