日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

 東西二王 2019-05-16

全文共2153字,預計學習時長4分鐘或更長

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

用Matplotlib模擬雨

動畫是呈現(xiàn)各種現(xiàn)象的有趣方式。在描述像過去幾年的股票價格、過去十年的氣候變化、季節(jié)性和趨勢等時間序列數據時,與靜態(tài)圖相比,動畫更能說明問題。因為,從動畫中,我們可以看到特定參數是如何隨時間而變化的。

上圖是模擬雨的圖像。此圖由Matplotlib繪圖庫繪制而成,該繪圖庫常常被認為是python可視化數據包的原始數據組。Matplotlib通過50個分散點的比例和不透明度來模擬雨滴落在平面上的情景。如今,Plotly、Bokeh、Altair等一系列可視化工具均為Python中強大的可視化工具。這些庫可實現(xiàn)最先進的動畫和交互動作。但是,本文重點在于研究數據庫的一個方面——動畫。同時,我們也將關注實現(xiàn)動畫的方法。

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

概述

Matplotlib是一個 Python 的 2D繪圖庫,也是Python中最受歡迎的繪圖數據庫。大多數人在踏上數據可視化之旅時,都是首選Matplotlib。這是因為它可簡單地生成繪圖,直方圖、功率譜、條形圖、錯誤圖、散點圖等。不僅如此,它還無縫連接了Pandas、Seaborn等數據庫,甚至創(chuàng)建出更為復雜的可視化數據。

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

Matplotlib有幾大優(yōu)點:

· 其構造和MATLAB(矩陣實驗室)類似,所以兩者間易于切換

· 包含許多后端渲染

· 可以快速生成繪圖

· 已存在數十年以上,因此,有大量的用戶基礎

但是,Matplotlib除了這些優(yōu)點之外,也有許多不足之處:

· Matplotlib常常不可避免地存在冗繁的API(應用程序編程接口)

· 有時默認樣式設計不如人意

· 對web和交互式圖表的支持較低

· 處理大型及復雜的數據時速度常常較慢

對于進修者來說,Datacamp中有關于Matplotlib的必備知識可以幫助提高基礎知識。

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

動畫

Matplotlib的動畫基類負責處理動畫部分。其可提供構建動畫功能的框架。有兩個主要接口來實現(xiàn)此功能:

FuncAnimation:通過反復觸發(fā)func.功能創(chuàng)建動畫。

ArtistAnimation:利用已定義的Artist對象創(chuàng)建動畫。

但是,在上述兩種接口中,F(xiàn)uncAnimation更為方便。我們專注于FuncAnimation工具的研究。


要求

· 安裝numpy和matplotlib模塊。

· 安裝符合要求的 ffmpeg 或imagemagick方可將動畫以mp4或gif的形式儲存。

一切準備就緒,就可以開始在JupyterNotebooks中制作第一個基本動畫了。本文的訪問密碼可在GithubRepository中獲取。


基本動畫:移動的正弦波

在電腦中,利用FuncAnimation創(chuàng)建正弦波的基本動畫。動畫源代碼可在Matplotlib動畫教程中獲取。先來看看輸出代碼,然后將其破譯,并了解其中奧妙。

import numpy as np

from matplotlib import pyplot as plt

from matplotlib.animation import FuncAnimation

plt.style.use('seaborn-pastel')

fig = plt.figure()

ax = plt.axes(xlim=(0, 4), ylim=(-2, 2))

line, = ax.plot([], [], lw=3)

def init():

line.set_data([], [])

return line,

def animate(i):

x = np.linspace(0, 4, 1000)

y = np.sin(2 * np.pi * (x - 0.01 * i))

line.set_data(x, y)

return line,

anim = FuncAnimation(fig, animate, init_func=init,

frames=200, interval=20, blit=True)

anim.save('sine_wave.gif', writer='imagemagick')

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

· 在第7行到第9行,簡單地創(chuàng)建一個圖形窗口,圖中只有一個軸。然后,創(chuàng)建無內容的行對象,其本質上是在動畫中可修改的對象。稍后用數據來填充行對象。

· 在第11行到13行,創(chuàng)建init函數,觸發(fā)動畫發(fā)生。此函數初始化數據,并限定軸范圍。

· 最后,在第14行到第18行,定義動畫函數,該函數以幀數(i)作為參數,并創(chuàng)建一個正弦波(或任意其他的動畫),而其移動取決于i的值。此函數返回一個已修改的plot對象的元組,告知動畫框架plot中哪些部分需要動畫化。

· 在第20 行,創(chuàng)建實際的動畫對象。Blit參數確保只重新繪制已更改的部分。

· 這是在Matplolib中創(chuàng)建動畫的基本知識。只需對代碼稍作調整,就可以創(chuàng)建出一些有趣的可視化。接下來看看其中一些可視化的例子吧。

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

一個不斷擴大的線圈

同樣,在GreeksforGreeks中,有一個創(chuàng)建圖形的好例子。我們一起在animation模塊的幫助下創(chuàng)造一個緩慢展開的活動線圈。該代碼和正弦波圖極為相似,只有一些小調整。

import matplotlib.pyplot as plt

import matplotlib.animation as animation

import numpy as np

plt.style.use('dark_background')

fig = plt.figure()

ax = plt.axes(xlim=(-50, 50), ylim=(-50, 50))

line, = ax.plot([], [], lw=2)

# initialization function

def init():

# creating an empty plot/frame

line.set_data([], [])

return line,

# lists to store x and y axis points

xdata, ydata = [], []

# animation function

def animate(i):

# t is a parameter

t = 0.1*i

# x, y values to be plotted

x = t*np.sin(t)

y = t*np.cos(t)

# appending new points to x, y axes points list

xdata.append(x)

ydata.append(y)

line.set_data(xdata, ydata)

return line,

# setting a title for the plot

plt.title('Creating a growing coil with matplotlib!')

# hiding the axis details

plt.axis('off')

# call the animator

anim = animation.FuncAnimation(fig, animate, init_func=init,

frames=500, interval=20, blit=True)

# save the animation as mp4 video file

anim.save('coil.gif',writer='imagemagick')

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

實時更新圖

繪制股票數據、傳感器數據等其他與時間相關的動態(tài)數據時,實時更新圖就會派上用場。我們繪制一個基圖,在更多的數據被輸入系統(tǒng)后,基圖就會自動更新?,F(xiàn)在,來繪制某假定公司某月內的股價圖。

#importing libraries

import matplotlib.pyplot as plt

import matplotlib.animation as animation

fig = plt.figure()

#creating a subplot

ax1 = fig.add_subplot(1,1,1)

def animate(i):

data = open('stock.txt','r').read()

lines = data.split('\n')

xs = []

ys = []

for line in lines:

x, y = line.split(',') # Delimiter is comma

xs.append(float(x))

ys.append(float(y))

ax1.clear()

ax1.plot(xs, ys)

plt.xlabel('Date')

plt.ylabel('Price')

plt.title('Live graph with matplotlib')

ani = animation.FuncAnimation(fig, animate, interval=1000)

plt.show()

現(xiàn)在,打開終端并運行python文件,可以得到如下所示可自動更新的圖表:

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

其更新的時間間隔是1000毫秒或一秒。

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

3D圖中的動畫

創(chuàng)建3D圖形十分常見,但是如果可以將這些圖形視角動畫化呢?其方法是,在改變相機視圖后,利用生成后的所有圖像來創(chuàng)建動畫。而在PythonGraph Gallery(Python圖形庫)中有個專門的部分可以完成這類工作。

首先創(chuàng)建一個名為volcano的文件夾,放在與記事本相同的目錄中。然后,將所有會用于動畫化的圖形儲存在該文件夾中。

# library

from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt

import pandas as pd

import seaborn as sns

# Get the data (csv file is hosted on the web)

url =

data = pd.read_csv(url)

# Transform it to a long format

df=data.unstack().reset_index()

df.columns=['X','Y','Z']

# And transform the old column name in something numeric

df['X']=pd.Categorical(df['X'])

df['X']=df['X'].cat.codes

# We are going to do 20 plots, for 20 different angles

for angle in range(70,210,2):

# Make the plot

fig = plt.figure()

ax = fig.gca(projection='3d')

ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.viridis, linewidth=0.2)

ax.view_init(30,angle)

filename='Volcano/Volcano_step' str(angle) '.png'

plt.savefig(filename, dpi=96)

plt.gca()

這樣就可以在Volcano文件夾中創(chuàng)建多個PNG文件。接著,利用ImageMagick(一個創(chuàng)建、編輯、合成圖片的軟件)將這些PNG文件轉化成動畫。打開終端并導向Volcano文件夾,輸入以下指令:

convert -delay 10 Volcano*.pnganimated_volcano.gif

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

利用Celluloid模塊動畫化

Celluloid是python中的一個模塊,其在matplotlib中可簡化創(chuàng)建動畫的進程。這個庫創(chuàng)建一個matplotlib圖并從中創(chuàng)建相機。然后,重新啟用該圖,并在創(chuàng)建每幀動畫后,用上述相機拍快照。最后,利用所有捕捉到的幀創(chuàng)建動畫。

安裝

pip install celluloid

下面是利用Celluloid模塊的例子:

極小值

from matplotlib import pyplot as plt

from celluloid import Camera

fig = plt.figure()

camera = Camera(fig)

for i in range(10):

plt.plot([i] * 10)

camera.snap()

animation = camera.animate()

animation.save('celluloid_minimal.gif', writer = 'imagemagick')

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

子圖

import numpy as np

from matplotlib import pyplot as plt

from celluloid import Camera

fig, axes = plt.subplots(2)

camera = Camera(fig)

t = np.linspace(0, 2 * np.pi, 128, endpoint=False)

for i in t:

axes[0].plot(t, np.sin(t i), color='blue')

axes[1].plot(t, np.sin(t - i), color='blue')

camera.snap()

animation = camera.animate()

animation.save('celluloid_subplots.gif', writer = 'imagemagick')

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

圖例

import matplotlib

from matplotlib import pyplot as plt

from celluloid import Camera

fig = plt.figure()

camera = Camera(fig)

for i in range(20):

t = plt.plot(range(i, i 5))

plt.legend(t, [f'line {i}'])

camera.snap()

animation = camera.animate()

animation.save('celluloid_legends.gif', writer = 'imagemagick')

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

創(chuàng)造生動有趣的動畫,Matplotlib庫大顯身手

    本站是提供個人知識管理的網絡存儲空間,所有內容均由用戶發(fā)布,不代表本站觀點。請注意甄別內容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多